query a process by PID windows javascript - wsh

I have a few processes on windows and have there pid. It is RUNNING on the machine.
How can I query using js if the a process with the pid is up ?
Can I ensure in js that this the process (and not other process)

You can get a handle to a process by its ID using WMI:
var proc = GetObject("winmgmts:").Get("Win32_Process.Handle='" + pid + "'");
There are a few different properties you can access from the resulting object, such as Caption or ExecutablePath, to make sure it is the process you're looking for:
if (proc.ExecutablePath == "C:\\Windows\\System32\\cmd.exe") {
// ...
}

JavaScript doesn't natively have access to the Operating System. However you may be able to access system calls from RingoJS or Node.js, if you're using Server Side JavaScript. Please provide more details about the environment you're using.

Related

Running a salix webApp through an IDE menu

I have a bit of code that creates a salix webapp and runs it from an IDE popup menu by making use of util::Webserver. In order to allow for the command to be used multiple times, I try to shutdown any existing webserver at that address first but it doesn't seem to be working. No matter what it always comes up with an illegal argument error stating "shutdown" not possible.
void run_game(Tree t, loc s){
t = annotate(t);
PSGAME g = ps_implode(t);
Checker c = check_game(g);
Engine engine = compile(c);
loc host = |http://localhost:9050/|;
try { util::Webserver::shutdown(host);} catch: ;
util::Webserver::serve(host, load_app(engine)().callback, asDaemon = true);
println("Serving content at <host>");
}
What I expect to happen is that the first time this function it run, shutdown throws an error that is silenced because no webserver exists and then serve starts the webserver. If the user tries to run the function again then shutdown successfully runs, clearing the address bind and serve binds successfully to the address.
What actually happens the second time, is that shutdown still errors, the error is silenced and then serve complains that the address is already in use.
I'm looking for any solution that would allow me to start a salix app through the IDE's popup menu (previously registered) at the same address.
PS_contributions =
{
PS_style,
popup(
menu(
"PuzzleScript",
[
action("Run Game", run_game)
]
)
)
};
registerContributions(PS_NAME, PS_contributions);
Right; we ran into similar issues and decided to special case actions that run web apps. So we added this:
data Menu = interaction(str label, Content ((&T <: Tree) tree, loc selection) server)
See https://github.com/usethesource/rascal-eclipse/blob/bb70b0f6e8fa6f8c227e117f9d3567a0c2599a54/rascal-eclipse/src/org/rascalmpl/eclipse/library/util/IDE.rsc#L119
Content comes from the Content module which basically wraps any Response(Request) servlet.
So you can wrap your salix webApp in a Content and return it given a current selection and the current tree.
The IDE will take care to start and also shutdown the server. It does that every time an interaction with the same label is created or after 30 minutes of silence on the given HTTP port.

How to let Dart run a separate process in a server?

For example, here is a simple dart code:
#import('dart:io');
main() {
var server = new HttpServer();
server.listen('127.0.0.1', 8080);
server.defaultRequestHandler = (HttpRequest request, HttpResponse response) {
response.outputStream.write('Hello, world'.charCodes());
response.outputStream.close();
};
}
when the web server print the 'Hello, world', I would like to run a progress to run a
long heavy task, but don't want to it blocking the current process. May I know how to handle it? Thanks.
I tried with Process.run and Process.start with no success.
From you comment I can tell there are a misunderstanding of how Dart works spawning external processes. When you spawn a process in Dart it is by default running so the Dart program and the external program are running separate (so in different processes) and the Dart program can execute other stuff. You can then await for the result from the program (e.g. when it closes).
Therefore it does not make much sense to run the process with "&" as parameter (I guess this was an attempt to tell it should run separately from the Dart program).
But, since you are spawning another Dart program your should also consider using an Isolate which can execute both your own method on another thread or run external code by using:
https://api.dart.dev/stable/2.6.0/dart-isolate/Isolate/spawnUri.html

Uptodate list of running docker containers stated in an exported golang variable

I am trying to use the Golang SDK of Docker in order to maintain a slice variable with currently running containers on the local Docker instance. This slice is exported from a package and I want to use it to feed a web page.
I am not really used to goroutines and channels and that's why I am wondering if I have spotted a good solution for my problem.
I have a docker package as follows.
https://play.golang.org/p/eMmqkMezXZn
It has a Running variable containing the current state of running containers.
var Running []types.Container
I use a reload function to load the running containers in the Running variable.
// Reload the list of running containers
func reload() error {
...
Running, err = cli.ContainerList(context.Background(), types.ContainerListOptions{
All: false,
})
...
}
And then I start a goroutine from the init function to listen to Docker events and trigger the reload function accordingly.
func init() {
...
// Listen for docker events
go listen()
...
}
// Listen for docker events
func listen() {
filter := filters.NewArgs()
filter.Add("type", "container")
filter.Add("event", "start")
filter.Add("event", "die")
msg, errChan := cli.Events(context.Background(), types.EventsOptions{
Filters: filter,
})
for {
select {
case err := <-errChan:
panic(err)
case <-msg:
fmt.Println("reloading")
reload()
}
}
}
My question is, is it proper to update a variable from inside a goroutine (in terms of sync)? Maybe there is a cleaner way to achieve what I am trying to build?
Update
My concern here is not really about caching. It is more about hiding the "complexity" of the process of listening and update from the Docker SDK. I wanted to provide something like an index to easily let the end user loop and display currently running containers.
I was aware of data-races problems in threaded programs but I did not realize I was as actually in a context of concurrence here (I never wrote concurrent programs in Go before).
I effectively need to re-think the solution to be more idiomatic. As far as I can see, I have two options here: either protecting the variable with a mutex or re-thinking the design to integrate channels.
What means the most to me is to hide or encapsulate the method of synchronization used so the package users need not concern of how the shared state is protected.
Would you have any recommendations?
Thanks a lot for your help,
Loric
No, it is not idiomatic Go to share the Running variable between two goroutines. You do this by sharing it between the routine that runs your main function, and the listen function which is started with go—which spawns another goroutine.
Why, is because it breaks with
Do not communicate by sharing memory; instead, share memory by
communicating. ¹
So the design of the API needs to change in order to be idiomatic; you need to remove the Running variable and replace it with what? It depends on what you are trying to achieve. If you are trying to cache the cli.ContainerList because you need to call it often, and it might be expensive, you should implement a cache which is invalidated on each cli.Events.
What is your motivation?

Detect & Block Read/WriteProcessMemory calls from a Driver

Hi i'm relativly new to kernel programming (i've got a lot of c++ development experience though) and have a goal that i want to achieve:
Detecting and conditionally blocking attempts from userland programs to write or read to specific memory addresses located in my own userland process. This has to be done from a driver.
I've setup a development enviorment (virtual machine running the latest windows 10 + virtualkd + windbg) and already successfully deployed a small kmdf test driver via the visual studio integration (over lan).
So my question is now:
How do i detect/intercept Read/WriteProcessMemory calls to my ring3 application? Simply blocking handles isn't enough here.
It would be nice if some one could point me into the right direction either by linking (a non outdated) example or just by telling me how to do this.
Update:
Read a lot about filter drivers and hooking Windows Apis from kernel mode, but i really dont want to mess with Patchguard and dont really know how to filter RPM calls from userland. Its not important to protect my program from drivers, only from ring3 applications.
Thank you :)
This code from here should do the trick.
OB_PREOP_CALLBACK_STATUS PreCallback(PVOID RegistrationContext,
POB_PRE_OPERATION_INFORMATION OperationInformation)
{
UNREFERENCED_PARAMETER(RegistrationContext);
PEPROCESS OpenedProcess = (PEPROCESS)OperationInformation->Object,
CurrentProcess = PsGetCurrentProcess();
PsLookupProcessByProcessId(ProtectedProcess, &ProtectedProcessProcess); // Getting the PEPROCESS using the PID
PsLookupProcessByProcessId(Lsass, &LsassProcess); // Getting the PEPROCESS using the PID
PsLookupProcessByProcessId(Csrss1, &Csrss1Process); // Getting the PEPROCESS using the PID
PsLookupProcessByProcessId(Csrss2, &Csrss2Process); // Getting the PEPROCESS using the PID
if (OpenedProcess == Csrss1Process) // Making sure to not strip csrss's Handle, will cause BSOD
return OB_PREOP_SUCCESS;
if (OpenedProcess == Csrss2Process) // Making sure to not strip csrss's Handle, will cause BSOD
return OB_PREOP_SUCCESS;
if (OpenedProcess == CurrentProcess) // make sure the driver isnt getting stripped ( even though we have a second check )
return OB_PREOP_SUCCESS;
if (OpenedProcess == ProtectedProcess) // Making sure that the game can open a process handle to itself
return OB_PREOP_SUCCESS;
if (OperationInformation->KernelHandle) // allow drivers to get a handle
return OB_PREOP_SUCCESS;
// PsGetProcessId((PEPROCESS)OperationInformation->Object) equals to the created handle's PID, so if the created Handle equals to the protected process's PID, strip
if (PsGetProcessId((PEPROCESS)OperationInformation->Object) == ProtectedProcess)
{
if (OperationInformation->Operation == OB_OPERATION_HANDLE_CREATE) // striping handle
{
OperationInformation->Parameters->CreateHandleInformation.DesiredAccess = (SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION);
}
else
{
OperationInformation->Parameters->DuplicateHandleInformation.DesiredAccess = (SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION);
}
return OB_PREOP_SUCCESS;
}
}
This code, once registered with ObRegisterCallback, will detect when a new handle is created to your protected process and will kill it if it's not coming from Lsass, Csrss, or itself. This is to prevent blue screens from critical process being denied a handle to
your application.

Using Neo4j with React JS

Can we use graph database neo4j with react js? If not so is there any alternate option for including graph database in react JS?
Easily, all you need is neo4j-driver: https://www.npmjs.com/package/neo4j-driver
Here is the most simplistic usage:
neo4j.js
//import { v1 as neo4j } from 'neo4j-driver'
const neo4j = require('neo4j-driver').v1
const driver = neo4j.driver('bolt://localhost', neo4j.auth.basic('username', 'password'))
const session = driver.session()
session
.run(`
MATCH (n:Node)
RETURN n AS someName
`)
.then((results) => {
results.records.forEach((record) => console.log(record.get('someName')))
session.close()
driver.close()
})
It is best practice to close the session always after you get the data. It is inexpensive and lightweight.
It is best practice to only close the driver session once your program is done (like Mongo DB). You will see extreme errors if you close the driver at a bad time, which is incredibly important to note if you are beginner. You will see errors like 'connection to server closed', etc. In async code, for example, if you run a query and close the driver before the results are parsed, you will have a bad time.
You can see in my example that I close the driver after, but only to illustrate proper cleanup. If you run this code in a standalone JS file to test, you will see node.js hangs after the query and you need to press CTRL + C to exit. Adding driver.close() fixes that. Normally, the driver is not closed until the program exits/crashes, which is never in a Backend API, and not until the user logs out in the Frontend.
Knowing this now, you are off to a great start.
Remember, session.close() immediately every time, and be careful with the driver.close().
You could put this code in a React component or action creator easily and render the data.
You will find it no different than hooking up and working with Axios.
You can run statements in a transaction also, which is beneficial for writelocking affected nodes. You should research that thoroughly first, but transaction flow is like this:
const session = driver.session()
const tx = session.beginTransaction()
tx
.run(query)
.then(// same as normal)
.catch(// errors)
// the difference is you can chain multiple transactions:
const tx1 = await tx.run().then()
// use results
const tx2 = await tx.run().then()
// then, once you are ready to commit the changes:
if (results.good !== true) {
tx.rollback()
session.close()
throw error
}
await tx.commit()
session.close()
const finalResults = { tx1, tx2 }
return finalResults
// in my experience, you have to await tx.commit
// in async/await syntax conditions, otherwise it may not commit properly
// that operation is not instant
tl;dr;
Yes, you can!
You are mixing two different technologies together. Neo4j is graph database and React.js is framework for front-end.
You can connect to Neo4j from JavaScript - http://neo4j.com/developer/javascript/
Interesting topic. I am using the driver in a React App and recently experienced some issues. I am closing the session every time a lifecycle hook completes like in your example. When there where more intensive queries I would see a timeout error. Going back to my setup decided to experiment by closing the driver in some more expensive queries and it looks like (still need more testing) the crashes are gone.
If you are deploying a real-world application I would urge you to think about Authentication and Authorization when using a DB-React setup only as you would have to store username/password of the neo4j server in the client. I am looking into options of having the Neo4J server issuing a token and receiving it for Authorization but the best practice is for sure to have a Node.js server in the middle with something like Passport to handle Authentication.
So, all in all, maybe the best scenario is to only use the driver in Node and have the browser always communicating with the Node server using axios...

Resources