Skip to content

Commit

Permalink
Initial
Browse files Browse the repository at this point in the history
  • Loading branch information
myfear committed Jul 30, 2012
1 parent ac19dc9 commit 4d77c59
Show file tree
Hide file tree
Showing 8 changed files with 660 additions and 0 deletions.
17 changes: 17 additions & 0 deletions glassfish-realm/nb-configuration.xml
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?><project-shared-configuration>
<!--
This file contains additional configuration written by modules in the NetBeans IDE.
The configuration is intended to be shared among all the users of project and
therefore it is assumed to be part of version control checkout.
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
-->
<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
<!--
Properties that influence various parts of the IDE, especially code formatting and the like.
You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
That way multiple projects can share the same settings (useful for formatting rules for example).
Any value defined here will override the pom.xml file value but is only applicable to the current project.
-->
<netbeans.compile.on.save>all</netbeans.compile.on.save>
</properties>
</project-shared-configuration>
110 changes: 110 additions & 0 deletions glassfish-realm/pom.xml
@@ -0,0 +1,110 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>net.eisele.security</groupId>
<artifactId>glassfish-realm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>glassfish-realm</name>
<url>http://maven.apache.org</url>


<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<driver>com.mysql.jdbc.Driver</driver>
<url>jdbc:mysql://localhost:3306/jdbcrealmdb</url>
<username>root</username>
<password>root</password>
</properties>

<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.3</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
</dependencies>
<configuration>
<driver>${driver}</driver>
<url>${url}</url>
<username>${username}</username>
<password>${password}</password>
<skip>${maven.test.skip}</skip>
<srcFiles>
<srcFile>src/test/data/drop-and-create-table.sql</srcFile>
</srcFiles>
</configuration>
<executions>
<execution>
<id>create-table</id>
<phase>test-compile</phase>
<goals>
<goal>execute</goal>
</goals>
</execution>
</executions>
</plugin>


<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>


<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.4.2</version>
<configuration>
<systemProperties>
<property>
<name>user</name>
<value>${username}</value>
</property>
<property>
<name>password</name>
<value>${password}</value>
</property>
</systemProperties>
</configuration>
</plugin>

</plugins>
</build>


<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>3.1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,99 @@
package net.eisele.security.glassfishrealm;

import com.sun.appserv.security.AppservRealm;
import com.sun.enterprise.security.auth.realm.BadRealmException;
import com.sun.enterprise.security.auth.realm.InvalidOperationException;
import com.sun.enterprise.security.auth.realm.NoSuchRealmException;
import com.sun.enterprise.security.auth.realm.NoSuchUserException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import net.eisele.security.util.Password;
import net.eisele.security.util.SecurityStore;

/**
* High Security UserRealm for GlassFish Server. Implementing password salting.
*
* @author eiselem
*/
public class UserRealm extends AppservRealm {

private String jaasCtxName;
private String dataSource;

/**
* Init realm from properties
*
* @param props
* @throws BadRealmException
* @throws NoSuchRealmException
*/
@Override
protected void init(Properties props) throws BadRealmException, NoSuchRealmException {
_logger.fine("init()");
jaasCtxName = props.getProperty("jaas-context", "UserRealm");
dataSource = props.getProperty("dataSource", "jdbc/userdb");
}

/**
* {@inheritDoc }
*
* @return
*/
@Override
public String getJAASContext() {
return jaasCtxName;
}

/**
* {@inheritDoc }
*
* @return
*/
@Override
public String getAuthType() {
return "High Security UserRealm";
}

/**
* Authenticates a user against GlassFish
*
* @param uid The User ID
* @param givenPwd The Password to check
* @return String[] of the groups a user belongs to.
* @throws Exception
*/
public String[] authenticate(String name, String givenPwd) throws Exception {
SecurityStore store = new SecurityStore(dataSource);
// attempting to read the users-salt
String salt = store.getSaltForUser(name);

// Defaulting to a failed login by setting null
String[] result = null;

if (salt != null) {
Password pwd = new Password();
// get the byte[] from the salt
byte[] saltBytes = pwd.bytesFrombase64(salt);
// hash password and salt
byte[] passwordBytes = pwd.hashWithSalt(givenPwd, saltBytes);
// Base64 encode to String
String password = pwd.base64FromBytes(passwordBytes);
_logger.log(Level.FINE, "PWD Generated {0}", password);
// validate password with the db
if (store.validateUser(name, password)) {
result[0] = "ValidUser";
}
}
return result;
}

/**
* {@inheritDoc }
*/
@Override
public Enumeration getGroupNames(String string) throws InvalidOperationException, NoSuchUserException {
//never called. Only here to make compiler happy.
return null;
}
}
113 changes: 113 additions & 0 deletions glassfish-realm/src/main/java/net/eisele/security/util/Password.java
@@ -0,0 +1,113 @@
package net.eisele.security.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
* A utility library for creating secure hashes with salts.
*
* @author eiselem
*/
public class Password {

private SecureRandom random;
private static final String CHARSET = "UTF-8";
private static final String ENCRYPTION_ALGORITHM = "SHA-512";
private BASE64Decoder decoder = new BASE64Decoder();
private BASE64Encoder encoder = new BASE64Encoder();

/**
* Generate a secure salt from SecureRandom with a given length
*
* @param length
* @return
*/
public byte[] getSalt(int length) {
random = new SecureRandom();
byte bytes[] = new byte[length];
random.nextBytes(bytes);
return bytes;
}

/**
* Hash a password with a salt.
*
* @param password
* @param salt
* @return
*/
public byte[] hashWithSalt(String password, byte[] salt) {
byte[] hash = null;
try {
byte[] bytesOfMessage = password.getBytes(CHARSET);
MessageDigest md;
md = MessageDigest.getInstance(ENCRYPTION_ALGORITHM);
md.reset();
md.update(salt);
md.update(bytesOfMessage);
hash = md.digest();

} catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
Logger.getLogger(Password.class.getName()).log(Level.SEVERE, "Encoding Problem", ex);
}
return hash;
}

/**
* Hash with a slow salt. PBKDF2WithHmacSHA1
*
* @param password
* @param salt
* @return
*/
public byte[] hashWithSlowsalt(String password, byte[] salt) {
SecretKeyFactory factory;
Key key = null;
try {
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keyspec = new PBEKeySpec(password.toCharArray(), salt, 1000, 512);
key = factory.generateSecret(keyspec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
Logger.getLogger(Password.class.getName()).log(Level.SEVERE, null, ex);
}
return key.getEncoded();
}

/**
* Get a string from byte[] with bas64 encoding
*
* @param text
* @return
*/
public String base64FromBytes(byte[] text) {
return encoder.encode(text);
}

/**
* Get a byte[] from a string with base64 encoding
*
* @param text
* @return
*/
public byte[] bytesFrombase64(String text) {
byte[] textBytes = null;
try {
textBytes = decoder.decodeBuffer(text);
} catch (IOException ex) {
Logger.getLogger(Password.class.getName()).log(Level.SEVERE, "Encoding failed!", ex);
}
return textBytes;
}
}

0 comments on commit 4d77c59

Please sign in to comment.