I am currently attempting to read/write to memory through the use of JNA for Java. For the past week I have tried a multitude of solutions, mostly from [similar projects][1] I have found online, but nothing has resolved my problem.
I know I am receiving the correct process ID of the program, then I create a Pointer using the openProcess method. Then I call getBaseAddress using the newly created Pointer. The problem I believe lies within the EnumProcessModules/Psapi method/class.
Truthfully I am slightly in over my head but this is one of the last issues I am having with this program. My overall goal is to find the base address of the program, use various offsets to access the information I am trying to modify, and then modify it appropriately. The program is 32-bit, which I have seen other people say you need to use a EnumProcessModulesEx method for? but truthfully I am unsure of how/where to implement that.
Any help would be appreciated!
You're getting an Access Denied error because Windows requires you to enable Debug privilege on your current process before accessing the memory of another process. So you will need to both run your program as Administrator, and before you call your OpenProcess code, enable debug privilege.
Here's the JNA code in my application that does this. It's a static method as I only call it once for the entire application:
/**
* Enables debug privileges for this process, required for OpenProcess() to get
* processes other than the current user
*
* #return {#code true} if debug privileges were successfully enabled.
*/
private static boolean enableDebugPrivilege() {
HANDLEByReference hToken = new HANDLEByReference();
boolean success = Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(),
WinNT.TOKEN_QUERY | WinNT.TOKEN_ADJUST_PRIVILEGES, hToken);
if (!success) {
LOG.error("OpenProcessToken failed. Error: {}", Native.getLastError());
return false;
}
try {
WinNT.LUID luid = new WinNT.LUID();
success = Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_DEBUG_NAME, luid);
if (!success) {
LOG.error("LookupPrivilegeValue failed. Error: {}", Native.getLastError());
return false;
}
WinNT.TOKEN_PRIVILEGES tkp = new WinNT.TOKEN_PRIVILEGES(1);
tkp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED));
success = Advapi32.INSTANCE.AdjustTokenPrivileges(hToken.getValue(), false, tkp, 0, null, null);
int err = Native.getLastError();
if (!success) {
LOG.error("AdjustTokenPrivileges failed. Error: {}", err);
return false;
} else if (err == WinError.ERROR_NOT_ALL_ASSIGNED) {
LOG.debug("Debug privileges not enabled.");
return false;
}
} finally {
Kernel32.INSTANCE.CloseHandle(hToken.getValue());
}
return true;
}
I'm not sure from looking at your code whether you also have the right permissions for OpenProcess. Be sure you have the VM_READ permission. Here's what I use, your mileage may vary (I assume you'll need writing permissions as well).
final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(
WinNT.PROCESS_QUERY_INFORMATION | WinNT.PROCESS_VM_READ,
false, processID);
Related
thanks for taking the time to read this. I'm fairly new to JavaFX and have a weird error in my compiler that I would like some insight on.
Here's the error:
2018-09-13 19:09:36.387 java[8040:660455] unrecognized type is 4294967295
2018-09-13 19:09:36.387 java[8040:660455] *** Assertion failure in -[NSEvent _initWithCGEvent:eventRef:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1652/AppKit.subproj/NSEvent.m:1969
Here is the code I am working with:
This is in a .java file named applicationSettings
public static double lookupUser(String name, String password) throws IOException {
InputStream inputStream = applicationSettings.class.getResourceAsStream("/files/users.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheetAt(0);
Integer lastRow = sheet.getPhysicalNumberOfRows();
int currentRow = 1;
while(currentRow < lastRow) {
if(sheet.getRow(currentRow).getCell(0).getStringCellValue().toLowerCase().equals(name.toLowerCase())) {
if(sheet.getRow(currentRow).getCell(1).getStringCellValue().toLowerCase().equals(password.toLowerCase())) {
double accessLevel = sheet.getRow(currentRow).getCell(2).getNumericCellValue();
System.out.println(accessLevel);
return accessLevel;
}
}
currentRow++;
}
return 4.0;
}
}
This is in a .java file named loginScreen
EventHandler<ActionEvent> loginClicked = new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
double userFound = 0.0;
try {
userFound = applicationSettings.lookupUser(usernameField.getText(), passwordField.getText());
} catch (IOException e) {
e.printStackTrace();
}//END of Try/Catch
if(userFound == 1.0) { //1 is Admin Access
//TODO: Implement Login
System.out.println("Admin Login");
errorLabel.setVisible(false);
}else if(userFound == 2.0){ //2 is Elevated Access
//TODO: Elevated Access
System.out.println("Elevated Login");
errorLabel.setVisible(false);
}else if(userFound == 3.0){
//TODO: Basic Access
System.out.println("Basic Login");
errorLabel.setVisible(false);
}else{//Show Error
errorLabel.setVisible(true);
//TODO: Show Error
}//End If Statement
}
};
My Excel File is basically structured like this:
NAME PASSWORD ACCESS LEVEL
So for my login it would be like:
Trey Carey March3199; 1
This isn't going anywhere besides by church where it's not really doing anything besides automating some tedious tasks, so security isn't an issue.
Also, if there's anyway I can clean up some of these if statements and my code in general I would appreciate any tips or help!
Edit 2 13.11.2018:
This bug has been officially fixed now in JavaFX 12, was backported to JDK8 and approved to be backported to JFX 11. You can have a look at the bug report to find more information about it.JDK-8211304 Here is a link to the changes they've made. openjfx I'm personally not sure about the current license situation of JDK8 so I would advise to switch to the newest OpenJDK and OpenJFX if possible.
Hey there I'm experiencing the same issue you have and I can constantly reproduce it. The issue appears for me on JavaFX on macOS 10.14. You can simply create an application with a button that opens a second stage. If you invoke stage.showAndWait() (could be related to anything that holds the thread) on the second stage and then switch focus between different applications (I just alt-tab between my JavaFX app and Safari), the JavaFX Application crashes. Also reproducible in any IDE.
I actually found a bug report on the OpenJDK/OpenJFX bug tracker but there isn't much going on at the moment. JDK-8211137 Mac: JVM Crash due to uncaught exception
I don't have a solution yet as I'm having troubles pinning down the exact problem but I found a workaround that works in my specific case.
Edit:
If I'm using "stage.show()" I'm only getting the error but when using stage.showAndWait() or anything that does some kind of waiting loop, the application completely crashes.
I have this simple model written in Alloy:
module login
sig Email {}
sig Password {}
sig User {
login: one Login
}
sig Login {
email: one Email,
password: one Password,
owner: one User,
}
fact {
all u:User | u.login.owner = u
}
assert a {
all l:Login | one l.owner
all u:User | one u.login.email
all u:User | u.login.owner = u
}
check a for 3
If I run this with the alloy analyser GUI it says:
No counterexample found. Assertion may be valid. 11ms.
But if I run the same model with the API in my java program it returns:
---OUTCOME---
Unsatisfiable.
And not even 1 solutions is shown.
Can anyone help me to detect the problem?
Here goes the code in java using the API:
A4Reporter rep = new A4Reporter();
try {
Module loaded_model = CompUtil.parseEverything_fromFile(rep, null, model.getModelpath());
A4Options options = new A4Options();
options.solver = A4Options.SatSolver.SAT4J;
Command cmd = loaded_model.getAllCommands().get(0);
A4Solution sol = TranslateAlloyToKodkod.execute_command(rep, loaded_model.getAllReachableSigs(), cmd, options);
System.out.println(sol.toString());
while (sol.satisfiable()) {
System.out.println("[Solution]:");
System.out.println(sol.toString());
sol = sol.next();
}
} catch (Err e){
e.printStackTrace();
}
Thanks
In both cases no counter-examples are found.
Be aware that the command obtained via the method call loaded_model.getAllCommands().get(0) is check a for 3 in other words, you ask Alloy to look for counter examples.
If you would like to obtain an instance satisfying your constraints - i.e., not a counter-example - you should use a command containing the keyword run instead of check.
Busy trying to Call RPG function from Java and got this example from JamesA. But now I am having trouble, here is my code:
AS400 system = new AS400("MachineName");
ProgramCall program = new ProgramCall(system);
try
{
// Initialise the name of the program to run.
String programName = "/QSYS.LIB/LIBNAME.LIB/FUNNAME.PGM";
// Set up the 3 parameters.
ProgramParameter[] parameterList = new ProgramParameter[2];
// First parameter is to input a name.
AS400Text OperationsItemId = new AS400Text(20);
parameterList[0] = new ProgramParameter(OperationsItemId.toBytes("TestID"));
AS400Text CaseMarkingValue = new AS400Text(20);
parameterList[1] = new ProgramParameter(CaseMarkingValue.toBytes("TestData"));
// Set the program name and parameter list.
program.setProgram(programName, parameterList);
// Run the program.
if (program.run() != true)
{
// Report failure.
System.out.println("Program failed!");
// Show the messages.
AS400Message[] messagelist = program.getMessageList();
for (int i = 0; i < messagelist.length; ++i)
{
// Show each message.
System.out.println(messagelist[i]);
}
}
// Else no error, get output data.
else
{
AS400Text text = new AS400Text(50);
System.out.println(text.toObject(parameterList[1].getOutputData()));
System.out.println(text.toObject(parameterList[2].getOutputData()));
}
}
catch (Exception e)
{
//System.out.println("Program " + program.getProgram() + " issued an exception!");
e.printStackTrace();
}
// Done with the system.
system.disconnectAllServices();
The application Hangs at this lineif (program.run() != true), and I wait for about 10 minutes and then I terminate the application.
Any idea what I am doing wrong?
Edit
Here is the message on the job log:
Client request - run program QSYS/QWCRTVCA.
Client request - run program LIBNAME/FUNNAME.
File P6CASEL2 in library *LIBL not found or inline data file missing.
Error message CPF4101 appeared during OPEN.
Cannot resolve to object YOBPSSR. Type and Subtype X'0201' Authority
FUNNAME insert a row into table P6CASEPF through a view called P6CASEL2. P6CASEL2 is in a different library lets say LIBNAME2. Is there away to maybe set the JobDescription?
Are you sure FUNNAME.PGM is terminating and not hung with a MSGW? Check QSYSOPR for any messages.
Class ProgramCall:
NOTE: When the program runs within the host server job, the library list will be the initial library list specified in the job description in the user profile.
So I saw that my problem is that my library list is not setup, and for some reason, the user we are using, does not have a Job Description. So to over come this I added the following code before calling the program.run()
CommandCall command = new CommandCall(system);
command.run("ADDLIBLE LIB(LIBNAME)");
command.run("ADDLIBLE LIB(LIBNAME2)");
This simply add this LIBNAME, and LIBNAME2 to the user's library list.
Oh yes, the problem is Library list not set ... take a look at this discussion on Midrange.com, there are different work-around ...
http://archive.midrange.com/java400-l/200909/msg00032.html
...
Depe
I have a task to make a simple console pinger in Java.
I tried the following code and I have 2 main issues.
First of all even if I am connected to the internet (I can ping from console any site), when I run the code returns false.
Second, is it possible to track the time of response of the ping?
Here is the code:
try {
InetAddress address = InetAddress.getByName(the_link);
System.out.println(the_link);
// Try to reach the specified address within the timeout
// periode. If during this periode the address cannot be
// reach then the method returns false.
boolean reachable = address.isReachable(5000);
System.out.println("Is host reachable? " + reachable);
} catch (Exception e) {
e.printStackTrace();
}
This is not a good one to use for most external ips.
Instead following can be used
boolean reachable = (java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.lk").waitFor()==0);
Here is the scenario:
I want to use docuwiki to show help and other content to users. The users are grouped by to organization. Each organization gets their own content that should be private to them. Enter ACL. I get how I can create a user and limit him to a certain subsection of the wiki.
Now the fun part begins. How can I authenticate these users from my server? I'm running a Tomcat/Java/MSSQL stack. I have full control of both servers.
I'd imagine if it is possible, I would imagine I can post the username/password to the wiki from the servlet, and get some kinda token back that the user can access the site with. But I don't see anything in the documentation about this. If anyone has any ideas, pointers or alternatives, I'd appreciate it.
I think the thing that you need is named Single Sign On (SSO). As a possible solution you could setup an SSO provider (there is vast variety of them, also with support of Tomcat and dokuwiki) and configure your dokuwiki and tomcat to use it. Here is a sample of such provider.
For googlers that come after me:
I ended up writing my own authenticator. TO use authenticator place it in *\inc\auth* with the name sqlsrv.class.php (sqlsrv will be the code you use to specify this authenticator.)
Basically what happens with this is I generate a token on my server that uniquely identifies a logged in user. I then POST or GET to the wiki with the token. The authenticator then queries the server to see if the user should be authenticated, as well as to get the name, email and which ACL groups the user should belong to.
Notes: make sure you change the config options in the php file. And you'll need sqlsrv installed and enabled for your apache/php.
<?php
/**
* sqlsrv authentication backend
*
* #license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* #author Yuriy Shikhanovich <yuriys#gmail.com>
*/
class auth_sqlsrv extends auth_basic {
/**
* Constructor
*
* Carry out sanity checks to ensure the object is
* able to operate. Set capabilities.
*
* #author Yuriy Shikhanovich <yuriys#gmail.com>
*/
function __construct() {
global $config_cascade;
global $connection;
$this->cando['external'] = true;
}
function trustExternal()
{
//$msgTxt = $_SESSION[DOKU_COOKIE]['auth']['info']['user']."x";
//msg($msgTxt);
//return true;
global $USERINFO;
global $conf;
global $connection;
//already logged in, no need to hit server
if (!empty($_SESSION[DOKU_COOKIE]['auth']['info']))
{
$USERINFO['name'] = $_SESSION[DOKU_COOKIE]['auth']['info']['user'];
$USERINFO['mail'] = $_SESSION[DOKU_COOKIE]['auth']['info']['mail'];
$USERINFO['grps'] = $_SESSION[DOKU_COOKIE]['auth']['info']['grps'];
$_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
return true;
}
//check server based on token
try
{
$token = $_GET["token"];
if($token==null)
$token = $_POST["token"];
if($token==null)
$token = $_SESSION[DOKU_COOKIE]['auth']['token'];
if($token==null)
{
msg("Could not authenticate. Please contact your admin.");
return false;
}
//config //NOTE: replace with the appropriate values
$myServer = "1.1.1.1,1433";
$myUser = "sqlaccount";
$myPass = "sqlpassword";
$myDB = "dbName";
//end config
//get connection
$connectionInfo = array('UID' => $myUser, 'PWD' => $myPass, "Database"=>$myDB);
$link = sqlsrv_connect($myServer, $connectionInfo);
//check connection
if($link === FALSE)
{
msg("Could not get connection, contact your admin.");
return false;
}
//run token against proc
//NOTE: this needs to be implemented on your server, returns :
//"user" - Name of the user //this does not have to be setup in the wiki
//"email" - user's email //this does not have to be setup in the wiki
//"groups" - Which groups //this *does* have to be setup in the wiki to be used with ACL
$sql = "exec WikiLogin '".$token."'";
$stmt = sqlsrv_query( $link, $sql);
//check statement
if( $stmt === false)
{
msg("Could not get connection statement, contact your admin.");
return false;
}
//if returned results, set user and groups
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
// set the globals if authed
$USERINFO['name'] = $row['user'];
$USERINFO['mail'] = $row['email'];
$USERINFO['grps'] = split(" ",$row['groups']);
//msg(implode($row," "));
//msg(implode($USERINFO," "));
$_SERVER['REMOTE_USER'] = $row['user'];
//uncomment after testing
$_SESSION[DOKU_COOKIE]['auth']['user'] = $row['user'];
$_SESSION[DOKU_COOKIE]['auth']['mail'] = $row['email'];
$_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
$_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
sqlsrv_free_stmt( $stmt);
sqlsrv_close($link);
return true;
}
return false;
if(isset($link))
sqlsrv_close($link);
else
msg("Could not get connection, contact your admin.");
if(isset($stmt))
sqlsrv_free_stmt($stmt);
else
msg("Could not get connection, contact your admin.");
}
catch (Exception $e)
{
if(isset($link))
sqlsrv_close($link);
else
msg("Could not get connection, contact your admin.");
if(isset($stmt))
sqlsrv_free_stmt($stmt);
else
msg("Could not get connection, contact your admin.");
}
}
}