Java - encrypt / decrypt user name and password from a configuration file - java

We are busy developing a Java web service for a client. There are two possible choices:
Store the encrypted user name / password on the web service client. Read from a config. file on the client side, decrypt and send.
Store the encrypted user name / password on the web server. Read from a config. file on the web server, decrypt and use in the web service.
The user name / password is used by the web service to access a third-party application.
The client already has classes that provide this functionality but this approach involves sending the user name / password in the clear (albeit within the intranet). They would prefer storing the info. within the web service but don't really want to pay for something they already have. (Security is not a big consideration because it's only within their intranet).
So we need something quick and easy in Java.
Any recommendations?
The server is Tomkat 5.5. The web service is Axis2.
What encrypt / decrypt package should we use?
What about a key store?
What configuration mechanism should we use?
Will this be easy to deploy?

As I understand anyhow in order to call 3rd party web service you pass password as plain text and no security certificates are involved.
Then I would say the easiest approach would be to store password in encrypted format (via java encryption mechanism) when the encryption/decryption key is just hard coded in the code.
I would definitely store it on the server side (file system or db) rather then distribute and maintain it on the multiple clients.
Here is how that could work with "DES" encryption:
// only the first 8 Bytes of the constructor argument are used
// as material for generating the keySpec
DESKeySpec keySpec = new DESKeySpec("YourSecr".getBytes("UTF8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
sun.misc.BASE64Encoder base64encoder = new BASE64Encoder();
sun.misc.BASE64Decoder base64decoder = new BASE64Decoder();
.........
// ENCODE plainTextPassword String
byte[] cleartext = plainTextPassword.getBytes("UTF8");
Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
cipher.init(Cipher.ENCRYPT_MODE, key);
String encrypedPwd = base64encoder.encode(cipher.doFinal(cleartext));
// now you can store it
......
// DECODE encryptedPwd String
byte[] encrypedPwdBytes = base64decoder.decodeBuffer(encryptedPwd);
Cipher cipher = Cipher.getInstance("DES");// cipher is not thread safe
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));

Being on the intranet certainly does not justify dismissing security. Most damage done to information is by insiders. Look at the value of what's being protected, and give due consideration to security.
It sounds like there's a third-party application, for which you have one set of credentials, and some clients that effectively share this identity when using the third-party application. If that's the case, I recommend the following approach.
Don't distribute the third-party password beyond your web server.
The safest way to do this is to provide it to the web application interactively. This could be ServletContextListener that prompts for the password as the application starts, or a page in the application so that a admin can enter it through a form. The password is stored in the ServletContext and used to authenticate requests to the third-party service.
A step down in safety is to store the password on the server's file system so that it's readable only by the user running the server. This relies on the server's file system permissions for protection.
Trying to store an encrypted form of the password, on the client or the server, is just taking one step backward. You fall into an infinite regress when trying to protect a secret with another secret.
In addition, the clients should authenticate themselves to the server. If the client is interactive, have the users enter a password. The server can then decide if that user is authorized to access the third-party service. If the client is not interactive, the next best security is to protect the client's password using file system permissions.
To protect the clients' credentials, the channel between the client and your web server should be protected with SSL. Here, operating on an intranet is advantageous, because you can use a self-signed certificate on the server.
If you do store passwords in a file, put them in a file by themselves; it makes the need to manage permissions carefully more conspicuous, and minimizes the need for many users to be editing that file and thus seeing the password.

Related

How to protect password sending through httpclient method in java

From SCAVA security scan tool it is reported that some of my code lines are subject to vulnerability.
The vulnerability classification is :
Insufficient_Sensitive_Transport_Layer
The vulnerable code contains
httpclient.addHeader() method sending password to login a server/api.
Application is in java langauge.
From google, I got to know that we can add some encryption method to avoid this vulnerability.
HttpGet getMethod = null;
getMethod = new HttpGet("http/https url to connect");
getMethod.addHeader(USERNAME,PASSWORD); // Vulnerability reported in
//this line as it is sending the password without any protection.
How can i prevent this vulnerability and pass the password in a secure way through some encryption method.
Thanks in advance.
Enable Transport Layer Security (TLS) each time you have to send credentials as plain text. If you have correctly configured https:// with latest secure version of TLS the communication will be secure.
Moreover, there are situations where sending plain text credentials can't be avoided e.g. user login process. Automatic scanning tools might not be smart enough to distinguish valid use cases and raise a false-positive.

Send hashed or encrypted password to AS400 jdbc connection

Need to send a hashed or encrypted password when creating the db connection, see details below:
We have a Spring application that connects to a DB2 AS400 database. We are currently using configuration files (.properties) to store the connection details, Spring reads thes files in the context creation phase and creates the datasource accordingly.
...
database.driverClassName=com.ibm.as400.access.AS400JDBCDriver
database.url=jdbc:as400:<host>:naming=sql;libraries=*LIBL,...;transaction isolation=none
database.username=<user>
database.password=<password>
database.initialPoolSize=2
database.maxPoolSize=5
...
This .properties file lives in the application/web server's file sytem.
I have a requirement to store a hashed password instead of the password directly, that way if someone looks at the file content cannot know what the real password is.
Like this using SHA:
...
database.password=5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
...
There must be a way for telling AS400 that the password being sent is hashed.
In my research I found that AS400 stores passwords using an index QSYUPTBL in the library QSYS, which is able to use DES or SHA hashing algorithms. So it will encrypt the received password and will compare the resulting hash with the one stored in the index. But is it possible to tell the DB's authentication process to expect the password being hashed and compare it directly?
New finding:
The documentation from IBM mentions one keyword: RMTAUTMTH for setting the remote authentication method, using the *ENCRYPTED value in that param will activate the encryption in user id and password:
...User ID and associated encrypted password is sent on a DDM connection request. Cryptographic support must be available on both systems for this authentication method to be used... extracted from http://publib.boulder.ibm.com/infocenter/iseries/v5r3/topic/cl/chgrdbdire.htm
So it seems that it can be configured in the AS400 side, but does not mention anything about the encryption algorithm being used and if the jdbc driver supports it.
There is no mention of a property in the IBM Toolbox for Java JDBC properties to accept a special hashed/encrypted password.
You are going to have to manage the hashing/encryption of the password within your application and provide it to the JDBC connection as plaintext.
The secure property of the JDBC connection can be used to force an SSL connection to the AS/400, assuming SSL is enabled, to ensure that all data is encrypted between the application and the database.

jdbcDigestAuthentication only works when providing the hash

I started a project setting up basic authentication. I now want to switch to Digest Authentication. The problem is that the authentication is validated only if I provide the hash of the actual password, and not the actual password.
I did the following to switch from BASIC to DIGEST:
changed in my web.xml the auth-method to DIGEST
changed the JAAS context of my JDBC Realm to "jdbcDigestRealm"
in my db, I used to have "password" as a password, I changed in to the result of MD5(webuser:postgres:webuser) (where webuser is the login, webuser is the password, and postgres is the realm), in other words I set the password in my table to c3c2681ed07a5a2a5cb772061a8385e8.
The problem I have is that the login popup is displayed by the browser when I try to access the resource, but using "webuser" as the password doesn't work. However, using "c3c2681ed07a5a2a5cb772061a8385e8" as the password works. It looks like I'm still in BASIC authentication mode.
Any clue ?
Thank you !
The DIGEST auth-method is same as HTTP Digest Authentication. It just encrypts the communication between the browser and the server. The server still has the password in plain text.
From http://java.boot.by/wcd-guide/ch05s03.html:
The difference between basic and digest authentication is that on the
network connection between the browser and the server, the password is
encrypted, even on a non-SSL connection. In the server, the password
can be stored in clear text or encrypted text, which is true for all
login methods and is independent of the choice that the application
deployer makes.
You should set the digest-algorithm property of your JDBC Realm to MD5. After that the JDBC Realm will hash the password.
Perhaps you may need to change the digest algorithm in the realm view from glassfish console to MD5. Default value from GlassFish 3.0.* is still MD5, but from GlassFish 3.1.* has changed to SHA-256. This could be solution.
Adem

Digital signing without password

I have to write an utility for digital signing. I have already done it using following sample code.
KeyStore ks = KeyStore.getInstance(KeyStoreType);
ks.load(new java.io.FileInputStream(pfxPath), password.toCharArray());
Now the problem/requirement is, that PFX owner is not ready to share the password and I also don't want to load PFX file every time since I assume thousands of hits in a second.
My question is, is there any way so i can create some keystore(or certificate database or something else) where PFX owner enters password first time and I can use this keystore further for signing.
You can develop a standalone code which can generate a serialized file having KS object. Your client can pass his password at his machine. So it'll be risk free.
You can deserialize file contents in your application for further use.

How can I make the JSch API log in to a Unix server without a password?

I'm trying to make a Java application, that executes shell scripts on a remote Unix server, using the JSch API.
I was wondering if it's possible to login to the server without a password. If so - how? Should I generate a pair of authentication keys on the servers, then make the application read information from the key file?
The Java application is on a Windows station.
Since it took awhile before made it work, here is a whole modified example:
JSch jsch=new JSch();
Session session=jsch.getSession("my_username", "my_host", my_port);
session.setConfig("PreferredAuthentications", "publickey");
jsch.setKnownHosts("~/.ssh/known_hosts");
jsch.addIdentity("~/.ssh/id_rsa");
session.setConfig("StrictHostKeyChecking", "no");
session.connect(30000);
Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect(3*1000);
Beware whether you have copied rsa or dsa key to the server and add a corresponding identity at line addIdentity - id_rsa or id_dsa.
(cat .ssh/id_rsa.pub | ssh me#servername 'cat >> .ssh/).
This is certainly doable. Have a look at the examples directory provided with jsch.
UserAuthPubKey.java is showing how to authenticate with a public key and and KeyGen.java is chowing how to create the public and private keys.
Once you have sorted out your keys there is a single line to enable connecting with a key rather than a password:
JSch jsch = new JSch();
jsch.addIdentity(".ssh/privateKey.pem");
The addIdentity method takes a single argument that points at the location of your private key file on your machine.
As said by jlliagre, it is possible.
Generate a key pair for your application, make the public key known to the server (often putting it in ~/.ssh/authorized_keys is a good way), and give both keys to the client JSch object, either as files or as byte[]. You might also want to change the PreferredAuthentications option to allow only public-key auth, to avoid asking for a password or trying something else.
Note: If you deliver your application to hosts not controlled by you, anyone which can access the application's files can use the private key to login to your server.
Thus you should make sure the account can't do anything harmful, or that the client machine (your account and any privileged one) is under your (or only known friendlies') total control. (Encrypting the private key with a passphrase does not help if the passphrase is distributed with your program. Neither does putting it in the program's jar file.)

Categories

Resources