Do something before an application starts - c#

I've been looking for a way to do some stuff before an application starts and stop the started application and execute after "the stuff" is completed.
Like an Antivirus applications, when you open an application which may be dangerous or has no certification, it executes a scanning and only after that execution allow the application to starts.
Already tried with watchers and WMI (C#) but no success, since the calling event happens before the application starts and there is no way to cancel the opening.
If there is a name for that technique or someone knows an example code in C++ or C# or even any other language.
For those who are downvoting the question at least have the F** balls to explain why is downvoting...
It's a legitimate question! Maybe i miss explain it but still a legitimate question. Ohh I forgot, in many years of your career you already had to know everything... What would happen if you lost internet connection for three days? Are you still be productive? Maybe you guys had the API and documentation injected by Tank from Matrix... That's how NEO learn to fight.
Thanks

One option (which might be used by antiviruses, but not sure) is described here:
https://www.codeproject.com/Articles/11985/Hooking-the-native-API-and-controlling-process-cre
Basically, hooking the functions NtCreateFile(), NtOpenFile() or NtCreateSection() (the last one being mentioned as the preferred).
However, the hook must be done from inside a kernel mode driver, which might be a "slight inconvenience" (especially under 64-bit Windows, where the drivers must be signed AFAIK).
Some options also mentioned here: How does a Windows antivirus hook into the file access process?

Related

Get PID of process blocking a COM PORT

How to go about to get the process id of a process blocking a certain COM Port on Windows 7 and/or later?
I would like to get the PID programmatically. If possible using Python or C# but the language is not really important, I just want to understand the procedure.
This question has been asked numerous times on SO and many other forums for the last 10 years or so. The generally accepted answer is to use sysinternals to find the process using the particular file handle. Remember, a serial port is really just a file as far as the win32 api is concerned.
So, two answers for you:
Use sysinternals to find to offending application. I don't think this approach will work via python but you might hack something with .NET.
Use the NtQuerySystemInformation in a getHandles function. Take a look at the structures and figure out which fields are useful for identifying the offending process.
os.system("taskkill blah blah blah") against known serial port using apps. More on this idea at the end.
The 2nd idea sounds fun, however I just don't think the juice is worth the squeeze in this case. A relatively small number of processes actually use serial ports these days and if you are working in a specific problem domain, you are well aware of what the applications are called.
I would just run taskkill (via os.system) against any applications that I know 1) can be safely closed and 2) might actually have a port open. With this approach you'll save the headache of enumerating file handles and get back to focusing on what your application should really be doing.

Intermittent application hang on startup in Windows Store App

I am developing a Windows Store application. Currently, I am getting intermittent hangs as described in this blog post. The issue appears to be that not enough space is given to remainder-defined column widths and TextBlocks attempting to format themselves (possibly due to the ellipsis processing). My app tends to hang indefinitely when this happens.
The question I have less related to how to solve the issue (as it seems to be described fairly well in the blog post), but instead how to find the issues. I have one fairly regularly (approximately one in five or ten start-ups) on a Hub Page, so I've been looking through there (as it's the most notable instance of issue), but it's a true Heisenbug in that it never seems to happen when debugging (or when you look for it).
So, how do I find the offending code? Is there just a pattern I need to look for (ColumnWidth="*"?). Is there a simpler way to solve this, such as changing the base style to remove one of the possibly offending properties listed in the blog post?
It seems possible that this is being caused by another issue, but this seems to be the most likely/plausible as of right now (as with the hubs I have a similar situation to what is being described there).
Also, is there a way to track when this happens in the wild? MSFT provides crash dumps on hangs, but they seem to give little to no information in them at all (and on top of that they only appear 5 days after they happen, which is less than ideal).
Thanks!
This is a complicated question to answer.
First, I think you have identified a real problem with WinRT. You theorize that the layout subsystem seems busy calculating your layout, and based on some condition that occurs around 20% of the time it does not finish in any reasonable time. Reasonable guess.
The problem, then, is when such an event does not occur during debug. In my personal development experience, errors that do not occur in debug are 99.99% timing related. Something is not finishing before a second process begins. Debugging lets those first, long process finish.
This is a real computer science question, and not so much a WinRT or Windows 8 question. To that end, the best answer I can give you without any code samples (why no code samples?) is the typical approach I employ when I reach the same dilemma. I hope it helps, at least a little.
Start with your brain.
I have always joked with developers just how much debugging can be done outside the debugger - and in your mind. Mentally walking the pipeline of your app and looking for race-condition dependencies that might cause deadlocks. Believe it or not, this solves a lot of problems a debugger could never catch - because debuggers unwind timing dependencies.
Next is simplicity.
The more complex the problem the less likely you will find the culprit. In the case of a XAML application, I tend to remove or disable value converters first. Then, I look to remove data templates. If you have element bindings, those go next. If simplifying the XAML does help - that's just the beginning to figuring it out. If it doesn't, things just got easier.
Your code behind can be disabled with just a few keystrokes and found guilty or innocent. It's the most likely place for your problem, I find, and the reason we work so hard to keep it simple, clean, and minimal. After that, there's the view model. Though it's not impossible for your view model to be the one, and indeed you still have to check, it's probably not the root of your evil.
Lastly, there's the app pipeline that loads your page, loads your data, or does anything else. Step by step your only real option is to slowly remove things from your app until you don't see the problem. Removing the problem, though is not solving it. That's a case by case thing based on your app and the logic in it. Reality is, you might see the problem leave when removing XAML, while the real problem is in the view model or elsewhere.
What am I really saying? The silver bullet you are asking for really isn't there. There are several Microsoft tools and even more third party tools to look for bottlenecks, latency problems, slow code, and stuff - but in all reality, the scenario you describe is plain ole programming. I am not saying you aren't the victim of a bug. I'm saying, with the information we have, this is all I can do for you.
You'll get it.
Third thing to do is to add logging, and instrumentation to your app.
Best of luck.
Given that Jerry has answered this at a higher level I figured I would add in the lower level answers that from the way your question is phrased makes me think you are interested in. I guess first I would like to address the last item which is the dump files. There is a mechanism for getting dump files of a process 'in the wild' that Microsoft provides which is through Windows Error Reporting. If you are wanting to collect dump files from failed client processes you could sign up for Windows Error Reporting (I must admit I have never actually done it, but I did look into it and tried to get my current employer to allow me to do this, but it didn't end successfully). To sign up go to the Establish a Hardware/Desktop Account Page.
As far as what to do with dump files once you get them, you would be wanting to download the debugging tools for windows (part of the Windows SDK download) and/or the Debug Diag Tool (I must confess I am more of a debugging tools for windows user than a Debug Diag user). These will provide you with the tools to look into what is going on at a lower level. Obviously you can only go so far as you won't have access to private Microsoft symbols, but you do have access to public symbols and usually those are enough to give you a pretty good idea of the problem area.
Your primary tools will depend on how reproducible the issue is. If it is only reproducible on some client machines then you will have to rely on looking at a single dump file that you probably got a hold of from Windows Error Reporting. In this case what I would do is open it up using the appropriate version of Windbg (either x86 or x64) and look at what was going on at the time the dump was taken. Depending on how savvy you are depends on how far you can go. Probably a simple starter would be to run
.symfix
.reload
.loadby sos clr
!EEStack
This will load Microsoft public symbols, the sos extension dll for dealing with Managed code inspection, and then will dump the contents of the stack for each thread in the process. From looking at the names of the method that appear on the call stacks you might be able to get a pretty good idea of at least the area of the code where the lock is occuring.
You can go much farther than this as Windbg provides the ability to go pretty deep into deadlock analysis (for instance there is an extension available for Windbg called sosex that provides a command !dlk which can sometimes automate the detection of a deadlock for you from a single dump file. To load an extension dll into Windbg you just have to download it and then call .load fullpathtodll). If the problem is reproducible locally you might even be more successful with WPA/WPR or if you are really fortunate a simple procmon trace. These tools do have a pretty decent barrier to entry as they take some time to learn. But if you are really interested in the topic your best resources would be the Defrag Tools series on Channel9 and anything by Mario Hewardt (especially his book "Advanced .Net Debugging"). Again, getting familiar with these tools can take a bunch of time, but at the very least if you just know how to dump the contents of the stacks from a dump file you can sometimes get what you need just from that so a basic understanding of these tools can be beneficial as well.

Prevent a process from being killed in C#?

Ok, the title is my question.
No, this ain't for malware. It is for a parental control program for my own netbook.
Yes, I am tired of my brother's friends visiting porn sites on my laptop when I am away.
Oh, yes, I have red other questions and don't do the "You can't!" thing. It must be possible.
Well, you could run several processes, and when one of them is killed, one of the others would launch a replacement. You can also run a service that would monitor the process and launch another process when the process is killed.
Sorry, I can't comment so I've posted this as a 'answer'.
A few things to consider:
Is a 13 year old or his friends going to notice a process in taskmanager that shouldn't be there? (for example a second explorer.exe, svchost.exe etc.)
What are you trying to actually achieve as there may be other ways to do what it is you want. Are you trying to block them from going on certain sites? Are you trying to monitor what they do? Are you trying to prove to your mum what they are doing? Something else?
Unless you are trying to block them, will they care about anything you may have running? Would they bother to look for 'logging' software running on the PC? I would guess that they wouldn't bother to even open task manager unless the sites weren't working.
If you are trying to give proof or monitor your pc, running a VNC service in the background allows you to connect a viewer from another computer so that you/your mum can watch a live view of what they are up to.
If you want to monitor the sites then you have a wide range of options: keylogging software, browser logging software, proxy software or logging software on your router
If you want to block the sites then you also have a wide range of solutions: hosts file, dns based blocking (e.g. openDNS), blocking software on the pc (e.g. netnanny), blocking software on the router, etc.
Remember: If you are trying to block sites remember that nothing will block 100% of websites. You will only achieve 1 of 2 things: (Ideally) it becomes too much effort trying to find sites not blocked and they use another computer for their porn -or- they persist and find a way around it/to disable it/sites that it doesn't catch
what about unstoppable service ? MSDN
Yes, it is possible, I recently wanted to do the same thing, just came across what is known as Protected Windows Services.
I know this requires a lot of effort but when it's successfully implemented there's no way not even Admin can kill the process.
You'll need to write an additional ELAM Driver for this to work :ELAM Prerequisites - Microsoft Docs
Here is the link where it is described
Register service as protected service
Posted this answer as an Idea ...... If there's any problem I'll delete it.

Hide a C# program from the task manager?

Is there any way to hide a C# program from the Windows Task Manager?
EDIT:
Thanks for the overwhelming response! Well I didn't intend to do something spooky. Just wanted to win a bet with my friend that I can do it without him noticing. And I'm not a geek myself to be able to write a rootkit, as someone suggested though I'd love to know how to do it.
Not that I'm aware of - and there shouldn't be. The point of the task manager is to allow users to examine processes etc.
If the user should be able to do that, they should be able to find your program. If they shouldn't be poking around in Task Manager, group policy should prevent that - not your program.
Don't mean to zombie this but i thought i could contribute some useful information
If you want to hide a application there a two methods (that i can think of atm).
They both have their ups and downs
[1] SSDT Table hooking - basically you have to set the MDL of the table to writeable, overwrite the address of NtQuerySystemInformation (iirc) with the address of your function and have it call the original function after filtering the results.
This method doesn't suit your needs very well because the hooking function would always need to be in memory and would involve writing a kernel mode driver. Its a fun thing to do but debugging is a pain because an exception means a BSOD.
[2] Direct Kernel Object Manipulation (DKOM) - the list of processes is a doubly linked list, with a kernel mode driver you can alter the pointers of the records above and below your process to point around yours. This still requires the use of a kernel mode driver but there are rootkits such as FU that can be easily downloaded that contain an exe and the service. The exe could be called from inside your application as a child process (in the released version of FU, at least the one I found, there was a bug which I had to fix where if the hidden application exited the computer would BSOD, it was a trivial fix).
This will thankfully be caught by almost any decent antivirus so if you are trying to do something sneaky you'll have to learn to get around that (hint: they use a binary signature)
I have not used method 1 ever but method 2 has worked for me from a VB.Net application.
A third possible option is to just create the application as a windows service, this will show up in task manager by default but I'm willing to bet that there is a way to tell it to not show up there since there are plenty of other services which don't show up in task manager.
Hope I helped a little, my advice is that if you are interested in this kind of stuff to learn C++.
You could make your program a service and then it would appear as "svchost". There's a little more to it than that, but that should give you a hint to go in the right direction.
I'm not aware of any way to hide it from the task manager, but you could just disguise it by making it show up as "svchost.exe". It'll get lumped in with all the others (there's usually several), and will become indistinguishable.
You shouldn't hide it, but you could prevent the user from killing the process.
See Chris Smith's answer to this question.

Please help me with a program for virus detection using detection of malicious behavior

I know how antivirus detects viruses. I read few aticles:
How do antivirus programs detect viruses?
http://www.antivirusworld.com/articles/antivirus.php
http://www.agusblog.com/wordpress/what-is-a-virus-signature-are-they-still-used-3.htm
http://hooked-on-mnemonics.blogspot.com/2011/01/intro-to-creating-anti-virus-signatures.html
During this one month vacation I'm having. I want to learn & code a simple virus detection program:
So, there are 2-3 ways (from above articles):
Virus Dictionary : Searching for virus signatures
Detecting malicious behavior
I want to take the 2nd approach. I want to start off with simple things.
As a side note, recently I encountered a software named "ThreatFire" for this purpose. It does a pretty good job.
1st thing I don't understand is how can this program inter vent an execution of another between and prompt user about its action. Isnt it something like violation?
How does it scan's memory of other programs? A program is confined to only its virtual space right?
Is C# .NET correct for doing this kind of stuff?
Please post your ideas on how to go about it? Also mention some simple things that I could do.
This happens because the software in question likely has a special driver installed to allow it low level kernel access which allows it to intercept and deny various potentially malicious behavior.
By having the rights that many drivers do, this grants it the ability to scan another processes memory space.
No. C# needs a good chunk of the operating system already loaded. Drivers need to load first.
Learn about driver and kernel level programming. . . I've not done so, so I can't be of more help here.
I think system calls are the way to go, and a lot more doable than actually trying to scan multiple processes' memory spaces. While I'm not a low-level Windows guy, it seems like this can be accomplished using Windows API hooks- tie-ins to the low-level API that can modify system-wide response to a system call. These hooks can be installed as something like a kernel module, and intercept and potentially modify system calls. I found an article on CodeProject that offers more information.
In a machine learning course I took, a group decided to try something similar to what you're describing for a semester project. They used a list of recent system calls made by a program to determine whether or not the executing program was malicious, and the results were promising (think 95% recognition on new samples). In their project, they trained using SVMs on windowed call lists, and used that to determine a good window size. After that, you can collect system call lists from different malicious programs, and either train on the entire list, or find what you consider "malicious activity" and flag it. The cool thing about this approach (aside from the fact that it's based on ML) is that the window size is small, and that many trained eager classifiers (SVM, neural nets) execute quickly.
Anyway, it seems like it could be done without the ML if it's not your style. Let me know if you'd like more info about the group- I might be able to dig it up. Good luck!
Windows provides APIs to do that (generally the involve running at least some of your code in kernel). If you have sufficient privileges, you can also inject a .dll into other process. See http://en.wikipedia.org/wiki/DLL_injection.
When you have the powers described above, you can do that. You are either in kernel space and have access to everything, or inside the target process.
At least for the low-level in-kernel stuff you'd need something more low-level than C#, like C or C++. I'm not sure, but you might be able to do some of the rest things in a C# app.
The DLL injection sounds like the simplest starting point. You're still in user space, and don't have to learn how to live in the kernel world (it's completely different world, really).
Some loose ideas on topic in general:
you can interpose system calls issued by the traced process. It is generally assumed that a process cannot do anything "dangerous" without issuing a system call.
you can intercept its network traffic and see where it connects to, what does it send, what does it receive, which files does it touch, which system calls fail
you can scan its memory and simulate its execution in a sandbox (really hard)
with the system call interposition, you can simulate some responses to the system calls, but really just sandbox the process
you can scan the process memory and extract some general characteristics from it (connects to the network, modifies registry, hooks into Windows, enumerates processes, and so on) and see if it looks malicious
just put the entire thing in a sandbox and see what happens (a nice sandbox has been made for Google Chrome, and it's open source!)

Categories

Resources