I want to call one command(user defined) from C program(Windows) - c

I want to call one command(user defined) from C program(Windows).
Can you tell me the function available?

system() is the simplest way to call external programs.
It's a matter of doing something like:
system ("runme.exe");
The Win32 API has a lot of process control calls as well, which give you better control and monitoring. Look for CreateProcess and its brethren.

Related

Intercept executed commands in linux

I need to know is it possible to intercept user executed command in loadable kernel module. I know that system calls can be intercepted such as open(). But what i need to do is intercepts user entered command/ process and add some validations. for example, if user enters cp command, before executing the command i need to perform some validations against it. If we cannot do this in LKM, what are the alternative approaches?
You need to look up how many actual system calls there are for execvp() and friends (probably 1, maybe 2 — it could be more, but probably isn't), and then intercept those system calls. You might need to worry about posix_spawn() and friends too. They're the only ways that new processes can be run. There isn't any other way to intercept them.
You could try using an LKM or a systemtap plugin(which compiles to an LKM). The kernel functions that you should hook are execve and execveat. In case you are doing this for programming fun and want to write hooking code by yourself, you might want to look at kprobes and know that you can get kernel function addresses from /proc/kallsyms.
Of course, recompiling the kernel with your own hooking code is another option if that is a possibility.
In both the cases above you probably want to intercept the execve calls made by a specific uid; if so, you should filter calls from that uid.
A userspace approach might be to try writing a seccomp filter. Here is a tutorial on how to go about writing one.

Run program within C _without_ using a shell

I'm trying to run an application in C, but the only way I could find that is reasonably easy to use works like this:
system("command here");
It works, of course, but it's really slow (especially when repeating this a lot). I'm just wondering if there is a way of running a program without having to interact with a shell, something like python's subprocess module.
I have heard of execl, and I would use that (forking it first, of course), but I'm wondering if there is a simpler way that wouldn't require forking first.
EDIT: I also want to be able to know the return code of the program
As I'm sure you already know, system already employs the fork/exec strategy. I understand you want to circumvent the shell and are looking for a simple approach, I'm just saying you could just as easily write a function to wrap the fork/exec pattern as is done in system. Indeed it would probably be most straightforward to just do that. An alternative as Gabe mentioned in the comments is posix_spawn.
A faster (but apparently discouraged) alternative is vfork() / exec, but this is generally discouraged and is obsolete in the latest POSIX standards.
4.3BSD; POSIX.1-2001 (but marked OBSOLETE). POSIX.1-2008 removes the
specification of vfork().
It's meant to be immediately followed by an exec or _exit. Otherwise all kinds of weird bugs can arise since the virtual memory pages and page tables aren't duplicated (child uses same data/heap/stack segments). The parent/calling process blocks until the child execs or _exits. Regular fork's modern implementations have copy-on-write semantics which approach the speed of vfork, without the potential bugs incurred by vfork's memory sharing semantics.
If you want even further control over memory-sharing semantics and process inheritance, and the consequent potential speed-up (and are on Linux), look into clone() (wrapper for system-call sys_clone()) which is what some process-creating system calls delegate their work to. Be sure to carefully comb over all of the various flags.
You can use waitpid to get the exit status of the process.
If neither system() nor popen() provides the mechanism you need, then the easy way to do it is with fork() and execv() (or, perhaps, execl(), but the argument list must be fixed at compile time, not variable, to use it). Really! It is not hard to do fork() and exec(), and any alternative will encapsulate that processing.
The Python subprocess module is simply hiding fork() and exec() for you behind a convenient interface. That's probably appropriate for a high-level language like Python. C is a lower-level language and doesn't really need the complexity.
The hard way to do it is with posix_spawn(). You have to create arguments to describe all the actions you want done in the child between the fork() and the exec(), which is far harder to set up than it is to simply do the fork(), make the changes, and then use exec() after all. This (posix_spawn()) is what you get when you design the code to spawn a child process without visibly using fork() and exec() and ensure that it can handle almost any reasonable circumstance.
You'll need to consider whether you need to use wait() or waitpid() or a variant to determine when the child is complete. You may need to consider whether to handle the SIGCHLD signal (which will notify you when a child dies).

Preventing processes to execute certain system calls

I'm writing a program that spawns child processes. For security reasons, I want to limit what these processes can do. I know of security measures from outside the program such as chroot or ulimit, but I want to do something more than that. I want to limit the system calls done by the child process (for example preventing calls to open(), fork() and such things). Is there any way to do that? Optimally, the blocked system calls should return with an error but if that's not possible, then killing the process is also good.
I guess it can be done wuth ptrace() but from the man page I don't really understand how to use it for this purpose.
It sounds like SECCOMP_FILTER, added in kernel version 3.5, is what you're after. The libseccomp library provides an easy-to-use API for this functionality.
By the way, chroot() and setrlimit() are both system calls that can be called within your program - you'd probably want to use one or both of these in addition to seccomp filtering.
If you want to do it the ptrace way, you have some options (and some are really simple). First of all, I recommend you to follow the tutorial explained here. With it you can learn how to know what system calls are being called, and also the basic ptrace knowledge (don't worry, it's a very short tutorial). The options (that I know) you have are the following:
The easiest one would be to kill the child, that is this exact code here.
Secondly you could make the child fail, just by changing the registers with PTRACE_SETREGS, putting wrong values in them, and you can also change the return value of the system call if you want (again, with PTRACE_SETREGS).
Finally you could skip the system call. But for that you should know the address after the system call call, make the intruction register point there and set it (again, with PTRACE_SETREGS).

How can I create a process in a portable manner?

I'm trying to write a program which needs to create some other processes. I'm used to the Windows API but now I need my program to be able to run in a Linux platform too.
Is it possible to do it in a portable manner? Do I have to use the preprocessor for that purpose?
EDIT: I need to wait for it to finish before continuing to do things.
In my opinion the system function should always be avoided: it's unreliable, since you don't know what shell will handle your command and it doesn't have means to return you an unambiguous error code. Moreover, on platforms like Windows where processes are quite heavyweight it's not a good idea to launch a new process just to launch another one, and, by the way, some security suites may emit a warning for each process your app tries to launch, and doubling this notice (one for the command interpreter, one for the app actually launched) may doubly annoy the user.
If you just need to create a new process, you may just create your wrapper function around the actual platform-specific code, that will be selected automatically when the program will be compiled thanks to the preprocessor. Something like this:
int CreateProcess(const char * Executable, const char * CommandLine)
{
#if defined (_WIN32)
return CreateProcess(Executable, CommandLine /* blah blah blah */)!=FALSE;
#elif defined (_POSIX)
/* put here all the usual fork+exec stuff */
#else
#error The CreateProcess function is not defined for the current platform.
#endif
}
By the way, the function can be expanded easily to be blocking, you may simply add a flag (int Blocking, or whatever is now used in C99 for the booleans) that will trigger a WaitForSingleObject for the win32 section and a waitpid for the POSIX section.
The APIs are different, so there's no way around either writing two pieces of code or linking to a library which does the same.
The Apache Portable Runtime is a good option for writing portable low-level programs in C.
How much control over the other threads do you need? If it is a simple matter of just starting them, then the system() function is probably a good fit. If you want more control over them, I'd look into a library. I know that Qt makes it fairly easy to do some aspects of multi-process programming.
Try system() as it exists on both Posix and Windows.
#Jeff - system() is a blocking call, it will not return until the child process exits.

Asynchronous APIs

When trying to implement an asynchronous API calls / Non-blocking calls, I know a little in a All Plain-C application I have, I read a about APM (Asynchronous Programming Model) by 'Delegates'. Basically what I want to do is call one API f1() to do a functionality(which takes long time 8-10 seconds), So I call that API f1(), forget about it, and continue doing some other work, e.g. I/O for to fetch data for next call of the f1() or some functionality not dependent on result of f1().
If any one has used that APM model of programming, I am looking at some concise explanation for implementing non-blocking calls.
Is there any other way of implementing asynchronous APIs , any other library/framework which might help in this?
You basically need to create a multi-threaded (or multi-process) application. The f1() API needs to spawn a thread (or process) to process the data in a separate execution space. When it completes, the f1() routine needs to signal the main process that the execution is done (signal(), message queues, etc).
A popular way to do asynchronous programming in a plain C programs is to use an "event loop". There are numerous libraries that you could use. I suggest to take a look at
glib.
Another alternative is to use multiple pre-emptive threads (one for each concurrent operation) and synchronize them with mutexes and condition variables. However, pre-emptive threading in plain C is something I would avoid, especially if you want to write portable programs. It's hard to know which library functions are re-entrant, signal handling in threaded programs is a hassle, and in general C libraries and system functions have been designed for single-threaded use.
If you're planning to run your application only on one platform (like Windows) and the work done with f1() is a relatively simple thing, then threading can be OK.
If the function f1() which you are referring to is not itself implemented in a asynchronous fashion, you will need to wrap it up in its own thread yourself. When doing this, you need to be careful with regards to side effects that may be caused by that particular function being called. Many libraries are not designed in a thread-safe way and multiple concurrent invocations of functions from such libraries will lead to data corruption. In such cases, you may need to wrap up the functionality in an external worker process. For heavy lifting that you mention (8-10 seconds) that overhead may be acceptable. If you will only use the external non-threadsafe functions in one thread at a time, you may be safe.
The problem with using any form of event-loop is that an external function which isn't aware of your loop will never yield control back to your loop. Thus, you will not get to do anything else.
Replace delegates with pointers to functions in C, everything else is basically same to what you have read.
Well. Basically I've seen 2 types of async API:
Interrupt. You give a call a callback which should be performed after the call. GIO (part of previously mentioned GLib) works in such a way. It is relatively easy to program with but you usually have the thread in which the callback will be run changed (except if it is integrated with the main loop as in the case of GIO).
Poll. You check if the data is available. The well-known BSD Sockets operate in such a manner. It has an advantage of not necessarily being integrated with the main loop and running callback in a specific thread.
If you program for Gnome or Gtk+-based I'd like to add that GTask seems to be a very nice (potentially nice? I haven't used it). Vala will have better support for GIO-like async calls.

Resources