I'm writing client-side code for Windows Kerberos authentication with a service (logging code omitted):
System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
// System.setProperty("sun.security.krb5.debug", "true");
Package thisPkg = AuthHelper.class.getPackage();
String configPath = Util.getConfigPath(thisPkg, "jaas.conf");
System.setProperty("java.security.auth.login.config", "=" + configPath);
GSSManager manager = GSSManager.getInstance();
GSSName peerName = manager.createName(spn, GSSName.NT_HOSTBASED_SERVICE);
GSSContext context = manager.createContext(peerName, null, null,
GSSContext.DEFAULT_LIFETIME);
context.requestMutualAuth(true); // required
context.requestCredDeleg(true); // required for publish
byte[] serverTokenBytes = new byte[0];
while (!context.isEstablished()) {
byte[] clientTokenBytes = context.initSecContext(serverTokenBytes, 0,
serverTokenBytes.length);
if (clientTokenBytes != null)
socket.send(createClientMessage(clientTokenBytes));
if (context.isEstablished()) break;
Message message = socket.receive();
String serverToken = message.getFirst("SERVERTOKEN").toString();
serverTokenBytes = Base64.decodeBase64(serverToken);
}
Where jaas.conf simply contains:
sp {
com.sun.security.auth.module.Krb5LoginModule required debug=true;
};
I have also set the allowtgtsessionkey registry key as required, and installed JCE Unlimited Strength Jurisdiction Policy Files 7.
The code sometimes works (i.e. mutual authentication is established); however, sometimes it gets stuck for a while at the first call to GSSContext.initSecContext, throwing an exception after about a minute:
Exception in thread "main" GSSException: No valid credentials provided (Mechanism level: Receive timed out)
...
Caused by: java.net.SocketTimeoutException: Receive timed out
...
When I enable Kerberos debugging output (by uncommenting the second line above), I can see that the protocol sometimes gets stuck at line:
getKDCFromDNS using UDP
A Java Kerberos troubleshooting website suggests that this is an issue with the Kerberos authentication server, but I know that the server is up and running, since we have similar code written in C# (using .NET libraries) that never gets stuck.
It seems like the DNS resolution for the Kerberos authentication server is going through some indirection, which is unreliable. If you specify the server explicitly (somewhere at the beginning of your code), it will bypass that redirection:
System.setProperty("java.security.krb5.realm", "<YOUR_KRB_REALM>");
System.setProperty("java.security.krb5.kdc", "<YOUR_KRB_SERVER_ADDR_OR_IP>");
EDIT: It turns out that communication with Kerberos servers was inherently unreliable due to the protocol using UDP, so it had a high chance of failing for servers that are relatively far away. Windows 8 uses TCP by default; to force TCP on previous versions:
XP/2000: In HKLM\System\CurrentControlSet\Control\Lsa\Kerberos, set DWORD MaxPacketSize to 1.
2003/Vista/7: In HKLM\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters, set DWORD MaxPacketSize to 1.
(Note that the same registry directory also needs DWORD AllowTGTSessionKey set to 1 for Kerberos to work at all.)
Related
Problem
I have some troubles configuring SNMP4J as SNMPv3 manager for a simple Get-Request.
SNMPv2 is working properly, both using net-snmp and SNMP4J.
Setup
On my local machine I have a running snmp daemon (via net-snmp).
zetts#zetts_x1_carbon~: cat /etc/snmp/snmpd.conf
rouser v3_ro_user priv .1
rocommunity start123
# sec.name source community
com2sec local localhost public
group MyRWGroup v1 local
group MyRWGroup v2c local
group MyRWGroup usm local
view all included .1 80
access MyROGroup "" any noauth exact all none none
access MyRWGroup "" any noauth exact all all none
A snmpget using net-snmp works as expected:
zetts#zetts_x1_carbon~: snmpget -v 3 -l authPriv -u v3_ro_user -a sha -A myAuthPw -x aes -X myPrivPw localhost .1.3.6.1.2.1.1.1.0
SNMPv2-MIB::sysDescr.0 = STRING: Linux zettsx1carbon 5.10.105-1-MANJARO #1 SMP PREEMPT Fri Mar 11 14:12:33 UTC 2022 x86_64
My SNMP4J implementation looks as follows:
public static void get() throws IOException {
SnmpBuilder snmpBuilder = new SnmpBuilder();
Snmp snmp = snmpBuilder.udp().v3().usm().build();
Address targetAddress = GenericAddress.parse("udp:127.0.0.1/161");
byte[] targetEngineID = snmp.discoverAuthoritativeEngineID(targetAddress, 1000);
if (targetEngineID != null) {
System.out.println("Trying with " + authPro.toString());
TargetBuilder<?> targetBuilder = snmpBuilder.target(targetAddress);
Target<?> target = targetBuilder
.user("v3_ro_user", targetEngineID)
.auth(TargetBuilder.AuthProtocol.hmac192sha256).authPassphrase("myAuthPw")
.priv(TargetBuilder.PrivProtocol.aes128).privPassphrase("myPrivPw")
.done()
.timeout(1500).retries(1)
.build();
target.setVersion(SnmpConstants.version3);
PDU pdu = targetBuilder.pdu().type(PDU.GET).contextName("").build();
pdu.add(new VariableBinding(new OID(".1.3.6.1.2.1.1.1.0")));
SnmpCompletableFuture snmpRequestFuture = SnmpCompletableFuture.send(snmp, target, pdu);
try {
List<VariableBinding> vbs = snmpRequestFuture.get().getAll();
System.out.println("Received: " + snmpRequestFuture.getResponseEvent().getResponse());
} catch (ExecutionException | InterruptedException ex) {
System.err.println("Request failed: " + ex.getCause().getMessage());
}
} else {
System.err.println("Timeout on engine ID discovery for " + targetAddress + ", GET not sent.");
}
snmp.close();
}
I sometimes used non-fluent syntax (e.g. target.setVersion()) since the corresponding fluent method was not working.
Analysis
SNMP4J run result: Request failed: SNMP Request timed out
I captured the localhost UDP port 161 traffic using tcpdump. First 4 packets can be seen for snmpget from net-snmp (successful), then 4 packets for from SNMP4J.
It looks as if the EngineID discovery works as well for SNMP4J, but the msgAuthenticationParameters in the next packet are way longer than in the corresponding net-snmp request packet.
The SNMP4J request is then answered with a report with OID “1.3.6.1.6.3.15.1.1.5.0” (oidUsmStatsWrongDigests).
SNMP daemon log:
zetts#zetts_x1_carbon~: cat snmpd.log
NET-SNMP version 5.9.1
Authentication failed for v3_ro_user
So it seems to be an authentication issue, but the username and password are definitely the same and correct. Is there something wrong with the authProtocol? Which version is net-snmp using when specifying only “SHA”?
Can someone provide further hints where to look for the root cause?
Thank you and best regards,
Sebastian
I'm unfamiliar with SNMP4J, but this block of code may need to have the security level defined as authPriv or however SNMP4J refers to it:
Target<?> target = targetBuilder
.user("v3_ro_user", targetEngineID)
.auth(TargetBuilder.AuthProtocol.hmac192sha256).authPassphrase("myAuthPw")
.priv(TargetBuilder.PrivProtocol.aes128).privPassphrase("myPrivPw")
.done()
.timeout(1500).retries(1)
.build();
target.setVersion(SnmpConstants.version3);
I solved it, in the end it was a SHA version issue:
net-snmp by default employs SHA-1, so I changed TargetBuilder.AuthProtocol.hmac192sha256 to TargetBuilder.AuthProtocol.sha1.
However, execution now failed instantly with:
SNMP error Authorization error on index 0
Also, the Net-SNMP daemon log was empty.
After debugging the SNMP4J execution and reading its in-file documentation I discovered that the SHA-1 protocol must be explicitly added to the Snmp instance since SNMP4J considers it to be unsafe.
Adding .securityProtocols(SecurityProtocols.SecurityProtocolSet.maxCompatibility) before .v3() in the Snmp building chain now resolves everything.
I am trying to connect to Hive2 server via JDBC with kerberos authentication. After numerous attempts to make it work, I can't get it to work with the Cloudera driver.
If someone can help me to solve the problem, I can greatly appreciate it.
I have this method:
private Connection establishConnection() {
final String driverPropertyClassName = "driver";
final String urlProperty = "url";
Properties hiveProperties = config.getMatchingProperties("hive.jdbc");
String driverClassName = (String) hiveProperties.remove(driverPropertyClassName);
String url = (String) hiveProperties.remove(urlProperty);
Configuration hadoopConfig = new Configuration();
hadoopConfig.set("hadoop.security.authentication", "Kerberos");
String p = config.getProperty("hadoop.core.site.path");
Path path = new Path(p);
hadoopConfig.addResource(path);
UserGroupInformation.setConfiguration(hadoopConfig);
Connection conn = null;
if (driverClassName != null) {
try {
UserGroupInformation.loginUserFromKeytab(config.getProperty("login.user"), config.getProperty("keytab.file"));
Driver driver = (Driver) Class.forName(driverClassName).newInstance();
DriverManager.registerDriver(driver);
conn = DriverManager.getConnection(url, hiveProperties);
} catch (Throwable e) {
LOG.error("Failed to establish Hive connection", e);
}
}
return conn;
}
URL for the server, that I am getting from the properties in the format described in Cloudera documentation
I am getting an exception:
2018-05-05 18:26:49 ERROR HiveReader:147 - Failed to establish Hive connection
java.sql.SQLException: [Cloudera][HiveJDBCDriver](500164) Error initialized or created transport for authentication: Peer indicated failure: Unsupported mechanism type PLAIN.
at com.cloudera.hiveserver2.hivecommon.api.HiveServer2ClientFactory.createTransport(Unknown Source)
at com.cloudera.hiveserver2.hivecommon.api.ZooKeeperEnabledExtendedHS2Factory.createClient(Unknown Source)
...
I thought, that it is missing AuthMech attribute and added AuthMech=1 to the URL. Now I am getting:
java.sql.SQLNonTransientConnectionException: [Cloudera][JDBC](10100) Connection Refused: [Cloudera][JDBC](11640) Required Connection Key(s): KrbHostFQDN, KrbServiceName; [Cloudera][JDBC](11480) Optional Connection Key(s): AsyncExecPollInterval, AutomaticColumnRename, CatalogSchemaSwitch, DecimalColumnScale, DefaultStringColumnLength, DelegationToken, DelegationUID, krbAuthType, KrbRealm, PreparedMetaLimitZero, RowsFetchedPerBlock, SocketTimeOut, ssl, StripCatalogName, transportMode, UseCustomTypeCoercionMap, UseNativeQuery, zk
at com.cloudera.hiveserver2.exceptions.ExceptionConverter.toSQLException(Unknown Source)
at com.cloudera.hiveserver2.jdbc.common.BaseConnectionFactory.checkResponseMap(Unknown Source)
...
But KrbHostFQDN is already specified in the principal property as required in the documentation.
Am I missing something or is this documentation wrong?
Below is the one of the similar kind of problem statement in Impala (just JDBC engine changes others are same) that is resolved by setting "KrbHostFQDN" related properties in JDBC connection string itself.
Try to use the URL below. Hopefully works for u.
String jdbcConnStr = "jdbc:impala://myserver.mycompany.corp:21050/default;SSL=1;AuthMech=1;KrbHostFQDN=myserver.mycompany.corp;KrbRealm=MYCOMPANY.CORP;KrbServiceName=impala"
I suppose that if you are not using SSL=1 but only Kerberos, you just drop that part from the connection string and don't worry about setting up SSL certificates in the java key store, which is yet another hassle.
However in order to get Kerberos to work properly we did the following:
Install MIT Kerberos 4.0.1, which is a kerberos ticket manager. (This is for Windows)
This ticket manager asks you for authentication every time you initiate a connection, creates a ticket and stores it in a kerberos_ticket.dat binary file, whose location can be configured somehow but I do not recall exactly how.
Finally, before launching your JAVA app you have to set an environment variable KRB5CCNAME=C:/path/to/kerberos_ticket.dat. In your java app, you can check that the variable was correctly set by doing System.out.println( "KRB5CCNAME = " + System.getenv( "KRB5CCNAME" ) ). If you are working with eclipse or other IDE you might even have to close the IDE,set up the environment variable and start the IDE again.
NOTE: this last bit is very important, I have observed that if this variable is not properly set up, the connection wont be established...
In Linux, instead MIT Kerberos 4.0.1, there is a program called kinit which does the same thing, although without a graphical interface, which is even more convenient for automation.
I wanted to put it in the comment but it was too long for the comment, therefore I am placing it here:
I tried your suggestion and got another exception:
java.sql.SQLException: [Cloudera]HiveJDBCDriver Error
creating login context using ticket cache: Unable to obtain Principal
Name for authentication .
May be my problem is, that I do not have environment variable KRB5CCNAME set.
I, honestly, never heard about it before.
What is supposed to be in that ticket file.
I do have, however, following line in my main method:
System.setProperty("java.security.krb5.conf", "path/to/krb5.conf");
Which is supposed to be used by
UserGroupInformation.loginUserFromKeytab(config.getProperty("login.user"), config.getProperty("keytab.file"));
to obtain the kerberos ticket.
To solve this issue update Java Cryptography Extension for the Java version that you use in your system.
Here's the link when you can download JCE for Java 1.7
Uncompress and overwrite those files in $JDK_HOME/jre/lib/security
Restart your computer.
I manage to perform a STARTTLS ldapmodify ( -ZZ) of an attribute, but fail to perform the same modification using javax.naming.ldap coding
The server is OpenLDAP. It has SSigned SSL Certificate for modification, and unsecured reading is allowed. Classical combination.
I run the following command from the same server on which I will try to execute the Java code (later):
ldapmodify -H ldap://my.ldap.server:389 -D "myldapadmin" -W -ZZ
Enter LDAP Password:
dn: CN=John Westood,OU=L100,DC=l,DC=woods
changetype: modify
replace: uPwd
uPwd:: 234WF34TG2U
modifying entry "CN=John Westood,OU=L100,DC=l,DC=woods"
... as you can see, it asks me for myldapadmin's password, I enter it, and the modification happens.
Here is what I am doing from Java, I want to do the same modification, I am running it on the same server. I have imported the SSigned LDAP SSL certificate into java first.
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://my.ldap.server:389");
// Create initial context
LdapContext ctx = new InitialLdapContext(env, null);
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, "myldapadmin");
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, "myadminpass");
// Start TLS (STARTTLS is also used by the console command ldapmodify)
StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new
StartTlsRequest());
SSLSession sess = tls.negotiate();
//Modification of 'uPwd' attribute
ModificationItem[] mods = new ModificationItem[1];
Attribute mod0 = new BasicAttribute("uPwd", "4G45G435G436UJWG");
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod0);
ctx.modifyAttributes("CN=John Westood,OU=L100,DC=l,DC=woods", mods);
// Stop TLS
tls.close();
// Context close
ctx.close();
I get exception in method ctx.modifyAttributes. The Exception is the following:
javax.naming.OperationNotSupportedException: [LDAP: error code 53 - 0000052D: SvcErr: DSID-031A12D2, problem 5003 (WILL_NOT_PERFORM), data 0
Anybody have idea why modify uPwd works with STARTLS from commandline, but not from Java ?
Appears you are trying to change perhaps a password against Microsoft Active Directory (Even though you show openLDAP)
(I have no idea what uPwd could be.)
Changing Microsoft Active Directory Passwords has several constraints.
Once you are confident you have an acceptable connection to Microsoft Active Directory, We have an example for Changing Microsoft Active Directory Password with JNDI
FYI: By default startTLS would use 389.
I am new to opc ua and not a pro in java. While setting up a client in java I'm having trouble with the certificate dealing. I want to connect to the server via Basic 256, SignAndEncrypt. As I understand, in this stage of security a certificate, created or loaded by the client, is send to the server, where it must be accepted. The server then sends a certificate back to the client, which then needs to be accepted by the client. Please, correct me, if I'm wrong.
Creating/Loading a certificate on the client side and sending it to the server does already work fine (see code below) and I can then accept it on the server side manually. But after that I'm stuck: How can I see this certificate validation in my code and how can I find the server certificate, let alone accept it?
I used the SampleConsoleClient of opc ua for some orientation during implementation. But in contrast to there, I do not use any user input.
Here's some of my code so far.
Initialization:
try {
client = new UaClient(serverUri);
} catch (final URISyntaxException e) {
throw new InitializationException("The server uri has an invalid syntax.", e);
}
try {
client.setApplicationIdentity(createApplicationIdentity());
} catch (final SecureIdentityException e) {
throw new InitializationException(
"Application Identity could not be created due to a Security Identity Exception.", e);
} catch (final IOException e) {
throw new InitializationException("Application Identity could not be created due to an IO Exception.",
e);
}
createApplicationIdentity():
final ApplicationDescription appDescription = new ApplicationDescription();
appDescription.setApplicationName(new LocalizedText(APPLICATION_NAME, Locale.ENGLISH));
appDescription.setApplicationUri(APPLICATION_URI);
appDescription.setProductUri(PRODUCT_URI);
appDescription.setApplicationType(ApplicationType.Client);
// Setting security features
client.setSecurityMode(SecurityMode.BASIC256_SIGN_ENCRYPT);
client.setCertificateValidator(validator);
validator.setValidationListener(myValidationListener); //myValidationListener is similar to most lines in MyCertificateValidationListener in the opc ua samples
final File privatePath = new File(validator.getBaseDir(), "private");
final KeyPair issuerCertificate = null;
final int[] keySizes = null;
final ApplicationIdentity identity = ApplicationIdentity.loadOrCreateCertificate(appDescription,
"Sample Organisation", "opcua", privatePath, issuerCertificate, keySizes, true);
identity.setApplicationDescription(appDescription);
return identity;
After initializing, I try to connect like this (with annotation, how I imagine the connection could work properly):
final String securityPolicy = client.getEndpoint() == null
? client.getSecurityMode().getSecurityPolicy().getPolicyUri()
: client.getEndpoint().getSecurityPolicyUri();
client.setSessionName(String.format("%s#%s/Session%d", APPLICATION_NAME,
ApplicationIdentity.getActualHostNameWithoutDomain(), ++sessionCount));
try {
//Idea: catch the server certificate and accept it. Only if that was possible: connect
client.connect();
} catch (final ServiceException e) {
e.printStackTrace();
}
client.setKeepSubscriptions(false);
// After that resolving namespace index (works fine)
}
And the error, that is thrown:
WARN (?:?): /<IPofServer> Error org.opcfoundation.ua.common.ServiceResultException: Bad_SecurityChecksFailed
(0x80130000) "An error occurred verifying security." at
org.opcfoundation.ua.transport.tcp.io.TcpConnection$ReadThread.run(Unknown Source)
com.prosysopc.ua.client.ConnectException: Failed to create secure channel to server: : opc.tcp://<IPofServer>
[http://opcfoundation.org/UA/SecurityPolicy#Basic256,SignAndEncrypt]
ServiceResult=Bad_SecurityChecksFailed (0x80130000) "An error occurred verifying security."
at com.prosysopc.ua.client.UaClient.n(Unknown Source)
at com.prosysopc.ua.client.UaClient.connect(Unknown Source)
at *lineOfCode*
Caused by: org.opcfoundation.ua.common.ServiceResultException:
Bad_SecurityChecksFailed (0x80130000) "An error occurred verifying security."
at org.opcfoundation.ua.transport.tcp.io.TcpConnection$ReadThread.run(Unknown Source)
With the lineOfCode being client.connect().
Thanks in advance for the help!!
The server will send it's certificate to the client. The client then has to
verify the validity of the certificate. This amounts to verifying the signature of the certificate, checking the validity, whether the hostname in the certificate matches the hostname in the endpoint, checking CRLs and so forth. Usually the SDK (the validator) should do this for you, but you might need to feed some parameters into the validator which checks should actually be performed. The security policy Basic256 imposes some minimal requirements on the certificate which the certificate should meet, of course. You can check the requirements here: http://opcfoundation-onlineapplications.org/profilereporting/ -- go to Security Category -> Facets -> Security policy.
check whether the server certificate is trusted. This usually amounts to checking whether a copy of the (puclic key) certificate has been put into some certicate store chosen as a trust store. If you write the client it's up to you to say which store to choose, but you will need to tell the validator where to look. I don't know that much about OPc UA development in Java, but you should check which certificate stores the validator expects. Maybe there is a default keyfile.
(On server side the same happens with the client certificate).
This asssumes you are starting out with self-signed certificates. If you are using certificates signed by a CA both applications (server and client) will need to be able to verify the whole chain of the other party. It can be stored locally in some store or can be send by the other party. At least one certificate in the chain has to be trustest (has to be put into the trust store).
For a general description on how UA security works have a look at this link:
https://opcfoundation.org/wp-content/uploads/2014/08/11_OPC_UA_Security_How_It_Works.pdf
For a detailed account you should consult the specification, available at GitHub.
Edit: one addtional remark which may help here: you seem to be using some SDK for the purpose in question. While validation of certificates, i.e. doing the signature checks etc, is usually covered by such an SDK the configuration of the application is the task of the application (programmer). This includes the location where you store trusted certificates and where and how you gather together missing parts of certificate chains. You might first try to check how demo clients and servers deal with this task, in other words check out the configuration tasks for such applications by trying to create a secure connection from, say, UA Expert to the sample servers from the OPC foundation. In the .Net SDK of the OPC foundation the location for the trust store defaults to a certain directory in the file system (a subfolder of C:\ProgramData\OpcFoundation, it's Windows only). You can, however, overwrite this when you initialize the validator. Other clients use their own directory structure for the storage of trusted certificates
You are obviously referring to the Prosys OPC UA Java SDK.
What always happens first, when you try to establish a secure connection for the first time, is that the server will deny access to your client application - and returns Bad_SecurityChecksFailed.
Only, after you have told the server to trust (the certificate of) your client application, will you get to the phase where the client application will try to verify the server's certificate - and your 'validationListener' will be triggered.
Thank you all for your answers. In the meantime, I tried basically copy/paste and modifying the connect() and initalize() methods from the SampleConsoleClient in the Prosys SDK samples And that worked. Guess it had something to do with renewing some information, but I'm not quite sure of that... Fact is, my application is now working, but thanks for your efforts!
Our code runs in weblogic and we MQ 6.0. No matter if I use the default createQueueConnection() or createQueueConnection("myuserid","mypassword") it always seems to use userid mqm. See code below.
When I connect from version 6.0 to an older mq installion 5 it seems to throw the following error javax.jms.JMSSecurityException: MQJMS2013: invalid security authentication supplied for MQQueueManager using the default createQueueConnection() unless I send a blank userid/password as in createQueueConnection("","")
How can I get myuserid to be send instead ?
Hashtable properties = new Hashtable(2);
properties.put(Context.PROVIDER_URL,context);
properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
InitialContext ctx = new InitialContext(properties);
QueueConnectionFactory qcf = (QueueConnectionFactory) ctx.lookup("QCF");
QueueConnection qc = qcf.createQueueConnection();
javax.jms.Queue q = (javax.jms.Queue) ctx.lookup("MYQUEUE");
QueueSession qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
TextMessage tm = qs.createTextMessage();
tm.setText(outString);
QueueSender sender = qs.createSender(q);
sender.send(tm);
sender.close();
qs.close();
qc.close();
If you are setting the ID in the createQueueConnection, rest assured, it is being presented to the queue manager. The problem you are seeing is that the SVRCONN channel definition on the QMgr has the value MCAUSER('mqm') hard coded. This overrides any value presented by the client app.
A couple of things to note here.
Although you can send the ID and password, WMQ accepts these at face value. The fields exist to make the credentials available for a channel exit that can validate them. Without such an exit the channel just runs as whatever ID the app claims to be and the password is ignored.
For the reason stated above, I always tell people not to trust the credentials presented unless they have such an exit. The administrator must code the appropriate value into the MCAUSER.
The administrative ID ('mqm' on UNIX flavors) is NOT the appropriate value. It confers administrative authority to anyone connecting on that channel.
For a LOT more on this topic and pointers to the WMQ security presentation and WMQ Security Lab guide from IMPACT, please see this SO question.