Possible to grab hardware ID with Java applet? - java

I want to grab a hardware ID with a java webapplet. Is this doable? If not, is there any web language I can do this with to help with a more secure authentication?

You can use any one approach as described below:
Use Signed Java Applet to load some JNI compatible shared library and get your job done.
public NativeHelloApplet() {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
System.load(System.getProperty("user.home") +"/libhello.so");
displayHelloWorld();
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
});
}
Use VB Script embedded in your web-page. Here is a sample:
Use the Win32_SystemEnclosure class, and the properties SerialNumber and SMBIOSAssetTag.
strComputer = "." Set objWMIService =
GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\"
_
& strComputer & "\root\cimv2") Set colSMBIOS = objWMIService.ExecQuery _
("Select * from Win32_SystemEnclosure") For Each
objSMBIOS in colSMBIOS
Wscript.Echo "Part Number: " & objSMBIOS.PartNumber
Wscript.Echo "Serial Number: " _
& objSMBIOS.SerialNumber
Wscript.Echo "Asset Tag: " _
& objSMBIOS.SMBIOSAssetTag Next
Design plug-in for every browser of your interest and collect data using them. MS uses this for Authenticated Software checking with FireFox.
Feel comfortable to let me know if you want to know more. That case, I shall write on my blog at http://puspendu.wordpress.com/

You can get a general idea of What Applets Can and Cannot Do, including access to certain system properties. In particular, unsigned applets "cannot load native libraries," which would probably be required for any kind of hardware identification.

If not, is there any web language I can do this with to help with a more secure authentication?
The issue is not strength of authentication. Rather it is whether a web language running in the user's browser should allow remote web services to access the user's hardware, files, etc. The answer is an emphatic "NO IT SHOULD NOT" ... unless the user implicitly grants permission by either installing a trusted plugin or a certificate.

Related

OpenProcess() fails for some users with access denied

I'm using Java JNA in order to access a process' memory on Windows. My code looks like this:
static WinNT.HANDLE openProcessHandle(int processId)
{
val processAccessRights = PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_TERMINATE
| PROCESS_NAME_NATIVE | PROCESS_SUSPEND_RESUME | PROCESS_QUERY_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION;
val processHandle = Kernel32.INSTANCE.OpenProcess(processAccessRights, false, processId);
if (processHandle == null)
{
val lastError = Native.getLastError();
val formatMessageFromLastErrorCode = Kernel32Util.formatMessageFromLastErrorCode(lastError);
val message = "OpenProcess() failed to open process id "
+ processId + ": " + formatMessageFromLastErrorCode;
throw new IllegalStateException(message);
}
return processHandle;
}
I'm already not using PROCESS_ALL_ACCESS due to the problems it causes.
According to this answer, I also need to enable the debug privilege for my process. However, despite calling this code successfully (e.g. all return values indicate success) before OpenProcess(), some users still get the error message OpenProcess() failed to open process id xxxx: Access denied. My application is not running as administrator. Why does it work for me and most users without administrator rights but not all users? What exactly causes this inconsistency? I would prefer to understand and tackle this problem specifically rather than making all users run my software as administrator since my software generally doesn't need those extra rights.
I authored the answer you cited in 2017, and learned last year that I had missed something key. I probably should edit that older answer to update it, but I'd forgotten about it. See this answer for a corrected version of the code that I'll be editing into the previous one you cited.
The API for AdjustTokenPrivileges() is somewhat broken in that it will give a false indication of success:
If the function succeeds, the return value is nonzero. To determine whether the function adjusted all of the specified privileges, call GetLastError, which returns one of ... ERROR_SUCCESS ... ERROR_NOT_ALL_ASSIGNED.
Given you are attempting to adjust the privileges with a non-admin user, you are not able to actually do so, and the other users will not be able to OpenProcess() for other users' processes. I don't think there is a workaround other than running your program with the necessary administrative power (SE_DEBUG_PRIVILEGE), which must be assigned by an administrator at some point.
It is likely you are still getting a misleading indication of success, but need to check GetLastError() to see if it actually worked.

how windows will do auto java update checks?

First of all sorry for my poor English.
I want to know how the windows will do auto java update check behind the User Interface ?
The UI will just react based on our input which is in the link , http://java.com/en/download/help/java_update.xml#howto .
But , how windows checks the updates programmatically.
I wrote a small program in java ,
public class JavaLatestVersion {
public static void main(String[] args){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new URL(
"http://java.com/applet/JreCurrentVersion2.txt").openStream())) ;
String fullVersion = br.readLine();
System.out.println("fullVersion : "+fullVersion);
String version = fullVersion.split("_")[0];
String revision = fullVersion.split("_")[1];
System.out.println("Version " + version + " revision " + revision);
} catch (IOException e) {
e.printStackTrace();
}
}
}
My questions :
1. Is the above program is the reliable way to get the latest java version ? Or any other standard way to get the latest java version (Not in the computer) ?
2. Is windows use the same way to determine the latest java version ?
3. Is windows use this link for updates http://java.com/applet/JreCurrentVersion2.txt ?
Any one know the secret code behind how windows will check for latest java updates?
Thanks in advance.
Checking for Java updates is done by Java Auto Updater. It is ordinary application (which is ran when Windows starts up).
Yes, it is reliable way to get the latest version of Java (as updater can not only update Java, it can also update itself). But pay attention to firewall/group policy settings which can prohibit updater to access the Web.
Windows doesn't update Java.
Only debugging Java Auto Updater can help to determine what URL it uses.
Unfortunately, Java Auto Updater has only graphical interface and hides all work behind the scenes. So finding a "secret code" is not easy to do. All the more in many cases reverse-engineering non-open source software is illegal from a license point of view.
URL that you provided above doesn't works. Because it says 8.0_51. But latest version of Java on Downloads page is 8u65 / 8u66.
Seems that latest available version (as plain text) can be determined only by fetching http://www.oracle.com/technetwork/java/javase/downloads/index.html web page, then parsing it, handling cases when page is moved to another location, etc.

I need to give a java application super user access to view protected files on a mac

As above.
I have scoured the web, i also rang mac support and annoyed a mac (OSX Lion) genius (out of desperation).
I have no idea how to do this, I really don't want to have to sit on top of a terminal and give it commands.
Has any one encountered this or got a solution?
Try looking at Greg Guerin's AuthKit library. It is a Mac-specific library that wraps Mac OS X Authorization Services.
Here is an example:
import glguerin.authkit.*;
Privilege priv = new Privilege("system.privilege.admin");
Authorization auth = new MacOSXAuthorization();
try
{
// This will cause an authentication prompt to be
// shown to the user, requesting the "system.privilege.admin"
// privilege.
auth.authorize(priv, true);
// If we reach this point, we can execute privileged programs.
// Load the secured file.
Process proc = auth.execPrivileged(new String[] { "/bin/cat", "/root/securefile" });
InputStream inputStream = proc.getInputStream();
// Use standard I/O mechanisms to read the input.
}
catch (UnauthorizedCancellation e)
{
// User chose not to authorize the application.
// Handle appropriately.
}
The auth.authorize() call will cause the standard "Please enter your password to allow program X to make changes" dialog. The user can cancel if desired, causing glguerin.authkit.UnauthorizedCancellation to be thrown.
This solution has a huge advantage over using sudo or setuid: it only runs the necessary tasks as root.
One last gotcha: the default JNI loader for AuthKit uses the Cocoa/Java bridge, which was removed from Mac OS X as of Snow Leopard. So on recent versions of Mac OS X, the code above will fail with UnsatisfiedLinkError. To work around this, use the following:
// Put this class somewhere:
public class AuthKitLibLoader extends LibLoader
{
#Override
protected File makeFallbackDir()
{
return new File(".");
}
}
// Then, before calling AuthKit (using the above example), do this:
// Hook in our "Snow Leopard-safe" extension to AuthKit (see below).
System.setProperty("glguerin.util.LibLoader.imp", AuthKitLibLoader.class.getName());
Finally, be sure to read the AuthKit documentation for more detail.
If you run the application as the root user, the application will have full access to everything.
This is a dangerous operation however because it gives the application full privileges.
Another option would be to run it as a user that has the needed permissions to the files in question. This can be done by putting the user or the files in the appropriate group.
You probably need to SETUID the application to root.
> su
Enter password:
> chown root:wheel myJavaApp
> chmod ug+s myJavaApp
> exit
Now whenever someone in the wheel group runs myJavaApp, it will run as its owner (root). Just make sure you're in the wheel group (or whatever other group)
Alternatively, you could chmod a+s myJavaApp ... but that would let ANYONE AT ALL run the program as root. I would think carefully about that.

Lotus Notes Java app can’t find notes.ini

Both the systems described are Windows XP with Lotus Notes 8.5.
I have a Java app (sample code below) that uses notes.jar to interact with Lotus Notes. The app works fine on a system that has notes.ini in the Lotus install dir of c:\Program Files\Lotus\Notes and the user ID file is in c:\Program Files\Lotus\Notes\Data. The user has to type a password to login to Lotus. This system has HKLM\Software\Lotus\Notes\MultiUser set to 0 (single user system). On this machine, the below code displays good values on the four println’s.
On a problem system, this app prints the four headings but blanks for the four values (the user name, key filename, mailfile, and mailserver are all blank). This problem system has notes.ini and the user ID file in D:\Data\johnsmith\NotesData. Lotus is installed in C:\Program Files\Lotus\Notes. This problem system also has HKLM\Software\Lotus\Notes\MultiUser set to 1 (implying it is multiuser instead of single user). Finally, under Lotus’s File -> Security -> User Security dialog the "Log in to Notes using your operating system login" box is checked (so the user doesn’t type in a password to login to Lotus).
So, it appears that on the problem system, the notes.ini file can’t be found (since notes.ini is where the four output values are supposed to be read from). I’ve looked through the Notes.jar API and can’t see any way to specify the location of notes.ini. The dir where notes.ini resides is in the Windows PATH, but that doesn’t help.
Any help would be appreciated.
import java.io.*;
import lotus.domino.*;
public static void main(String[] args) throws IOException {
try {
NotesThread.sinitThread();
Session session = NotesFactory.createSession();
System.out.println("Common user name: " + session.getCommonUserName());
System.out.println("KeyFilename: " + session.getEnvironmentString("KeyFilename", true));
System.out.println("MailFile: " + session.getEnvironmentString("MailFile", true));
System.out.println("MailServer: " + session.getEnvironmentString("MailServer", true));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
NotesThread.stermThread();
}
}
As mentioned in the original question, if HKEY_LOCAL_MACHINE\Software\Lotus\Notes\MultiUser has a value of 1, then you have a multi-user installation (even if you are the only user of Lotus).
Here is a solution that worked. Find the location of Notes.ini, probably somewhere like C:\Documents and Settings\(username)\Lotus. Edit or create the string value below and set it to your Notes.ini directory. HKEY_CURRENT_USER\Software\Lotus\Notes\(optional-version)\NotesIniPath.
In a multi-user environment, Lotus Notes gets the ini filename from the NotesIniPath registry value.
Add a new command-line parameter, "=c:\data\johnsmith\NotesData\notes.ini" . To make this happen, you need to use NotesFactory.CreateSession(String host, String args[], String user, String passwd); method, after setting up a new String array containing that parameter and whatever other arguments were passed, since itis basically supposed to be the String args[] as passed to static Main. (The =fullpath\notes.ini parameter just needs to be in the array, it doesn't need to be in any specific location.)
This permits the session to be initialized with the absolute path to the notes.ini file used, and appears to be supported since (though I could be wrong) Notes 5.0.5.
Notably, the Directory= line is going to be taken from that notes.ini and used for all error reporting and logging, as the user's private data directory.
There is a number of things you can try:
Notes actually comes with its own JVM and I found using this JVM makes Java applications run more reliably with Notes classes since any eventually needed support library would be properly configured.
What happens if notes is already running before you start your program. There are 2 variations here: Checkbox "Don't prompt for a password from other Notes-based programs" is checked or unchecked.
Make sure to switch to the directory where the Notes.ini is at home before you run the app. (And verify that the user can't see any other notes.ini variables)

Automating HP Quality Center with Python or Java

We have a project that uses HP Quality Center and one of the regular issues we face is people not updating comments on the defect.
So I was thinkingif we could come up with a small script or tool that could be used to periodically throw up a reminder and force the user to update the comments.
I came across the Open Test Architecture API and was wondering if there are any good Python or java examples for the same that I could see.
Thanks
Hari
Example of using Python (win32com) to connect to HP Quality Center via OTA
HP Quality Center exposes a com based API called OTA.
Documentation on this is downloadable from an QC server
(OTA_API_Reference.chm) (Weirdly it is very hard to find online)
The documentation uses VBScript (The officially supported internal language for QC)
and you will need to mentally translate to Python. THis is usually very simple, but
a couple of gotchas exist.
You will need to install on your machine the Quality Center local code, this is on your windows PC
if you have been able to get to QC through the web interface.
You will also need to know the URL of the server and you username and password and the domain
of the QC project you are working on.
from win32com.client import Dispatch
conn = get_QCConnection()
for bug in get_bugs(qcConn):
print bug.Title
put_QCConnection(conn)
#below code needs to be in seperate module or at least above the fold but here
# for clarity
def get_QCConnection():
'''Get the hardcoded connection to the server and domain.
Can be made a "real" engine if you try hard.
Use makepy utility to determine if the version number has changed (TDApiOle80)
but this works to current version'''
QCConnection = Dispatch("TDApiOle80.TDConnection")
url = "http://qc.example.com/qcbin"
QCConnection.InitConnectionEx(url)
QCConnection.login("USER", "PASS")
QCConnection.Connect("google_projects", "Google_Chrome")
return QCConnection
def put_QCConnection(qcConn):
#If one person logged in to QC changes *anything* on a bug,
# they hold a global lock on writing to that bug till
# thier session times out, so really really remember to logout
# its painful to wait for your own session to time out
qcConn.Logout()
def get_bugs(qcConn):
'''just following boiler plate from vbscript
PS the SetFilter is not in QTA API, it uses Filter.
But due to the workarounds in
the very brilliant pythoncom code it supplies a virtual wrapper class
called SetFilter - this is one of those gotchas '''
BugFactory = qcConn.BugFactory
BugFilter = BugFactory.Filter
BugFilter.SetFilter(u"Status", "New")
#NB - a lot of fields in QC are malleable - and vary from site to site.
#COntact your admins for a real list of fields you can adjust
buglist = BugFilter.NewList()
return buglist
This is not a bad basis for going forward, however I create a dummy class for defects and run something like:
dfcts = [defect(b) for b in buglist]
Then I can put worker code into defect class and keep things neater.
One thing you want to do is keep access to the raw qc bug internal to the python wrapper class.
Information for others who may view this thread.
To start all this You will need install pywin32, like from here http://sourceforge.net/projects/pywin32/files/pywin32/Build216/
First of all You will need to import pywin32
'''#author: www.qcintegration.com #mailto:contact#qcintegration.com'''
import pywintypes
import win32com.client as w32c
from win32com.client import gencache, DispatchWithEvents, constants
Then as second operation I include here action on login to server
def connect_server(qc, server):
'''Connect to QC server
input = str(http adress)
output = bool(connected) TRUE/FALSE '''
try:
qc.InitConnectionEx(server);
except:
text = "Unable connect to Quality Center database: '%s'"%(server);
return qc.Connected;
def connect_login(qc, username, password):
'''Login to QC server
input = str(UserName), str(Password)
output = bool(Logged) TRUE/FALSE '''
try:
qc.Login(username, password);
except pywintypes.com_error, err:
text = unicode(err[2][2]);
return qc.LoggedIn;
def connect_project(qc, domainname, projectname):
'''Connect to Project in QC server
input = str(DomainName), str(ProjectName)
output = bool(ProjectConnected) TRUE/FALSE '''
try:
qc.Connect(domainname, projectname)
except pywintypes.com_error, err:
text = "Repository of project '%s' in domain '%s' doesn't exist or is not accessible. Please contact your Site Administrator"%(projectname, domainname);
return qc.ProjectConnected;
Second of all method which will include OTAapi dll file
def qc_instance():
'''Create QualityServer instance under variable qc
input = None
output = bool(True/False)'''
qc= None;
try:
qc = w32c.Dispatch("TDApiole80.TDConnection");
text = "DLL QualityCenter file correctly Dispatched"
return True, qc;
except:
return False, qc;
Then main method to connect to QCserver
def qcConnect(server, username, password, domainname, projectname):
print("Getting QC running files");
status, qc = qc_instance();
if status:
print("Connecting to QC server");
if connect_server(qc, server):
##connected to server
print("Checking username and password");
if connect_login(qc, username, password):
print("Connecting to QC domain and project");
if connect_project(qc, domainname, projectname):
text = "Connected"
connected = True;
return connected, text;
else:
text = "Not connected to Project in QC server.\nPlease, correct DomainName and/or ProjectName";
connected = False;
return connected, text;
else:
text = "Not logged to QC server.\nPlease, correct UserName and/or Password";
connected = False;
return connected, text;
else:
text = "Not connected to QC server.\nPlease, correct server http address";
connected = False;
return connected, text;
else:
connected = False;
text = "Unable to find QualityCenter installation files.\nPlease connect first to QualityCenter by web page to install needed files"
return connected, text;
And at the end how to execute all of those methods in one place with example of use
if __name__ == "__main__":
server= r"http://qualitycenterServer:8080/qcbin"
username= "alex_qc"
password= ""
domainname= "DEFAULT"
projectname= "QualityCenter_Demo"
connection_status, text = qcConnect(server, username, password, domainname, projectname);
print "connection_status:", connection_status
In case of any more question mailto: contact#qcintegration.com
or directly to web side: http://www.qcintegration.com
I'm not sure there are any good samples for Java, because OTA can't be consumed by Java directly, it needs a Java to COM bridnge like JIntegra.
About Python, well you can use Python COM api's. And then any OTA example will do. You got plenty in QC documentation of OTA.
But I think the real question here is, why would you want to do it in Python or Java. Why not write what you need directly in QC using it's Workflow feature. Which will allow you to write your logic in VBScript, and have it invoked inside QC UI on user actions. For instance you can bind to the Post event of a Defect / Bug and check if there is a comment and if there is not prompt the user directly with a message.
There is a REST API to HPQC (ALM11 and newer) if you want to access it from Linux without running a Windows COM component.
Here is an example that pulls in a "requirement" record (# 1202) after authenticating.
import requests
session = requests.session()
user='hpqc'
password='xxxxx'
r = session.get("http://hpqc-server:8080/qcbin/authentication-point/authenticate",auth=(user,password))
r = session.get("http://hpqc-server:8080/qcbin/rest/domains/Foo/projects/Bar/requirements/1202")
print(r.text)
The parsing of r.text from XML is left as an exercise.
Though you have asked for a Python or Java based solution, sharing the following VBA code that you can use insde HPQC/ALM's script editor (Defects module script) to accomplish the goal.
Function Bug_FieldCanChange(FieldName, NewValue)
On Error Resume Next
if not changed then
strCommentBeforeUpdate = Bug_Fields("BG_DEV_COMMENTS").Value
end if
If FieldName = "BG_DEV_COMMENTS" and blnAddCommentClicked = False Then
Msgbox "Cannot update the comments." & Chr(13)& "Changes made will not be saved."&Chr(13)& "Please use 'Add comment' button to insert new comment." &Chr(13)& " Or click Cancel without saving."
blnUpdateCommentError = true
blnAddCommentClicked = False
changed = true
End If
Bug_FieldCanChange = DefaultRes
End Function
You can use a new Test and select type (VPXP_API) which allow script to run. The good thing there is that you'd have the function definition ready to be dragged from within QC instead of having to heavily rely on doc.
I've done an implementation in Python running some script from within QC still using its API but via a QC test which is handy to retrieve directly the result (Output) etc.. going through some shell command which can then call any script on any server etc...

Categories