Seam Identity Management

During a recent coding getaway to Maine (see my post on the 2011 HackFestaThon) I decided to write a basic Seam project as a starting point for my future Seam based web applications.  The idea is to provide common features such as Login, Logout, Registration, Forgot Password, User Management, Audit Logging, Image Upload Handling, Video Upload Handling, etc… so next time I have an idea that I want to hack together I won’t have to re-write or copy-paste in basic functionality like that.

I spent about a day working on things before I discovered that I really should be using the Seam framework’s Identity Management feature.  So I threw out everything I’d done, and started by re-reading the docs, and went from there.  Seam’s Identity Management framework is VERY powerful, but is also a little complicated to get going and in many cases it seems like it would easier to just write stuff from scratch.  I’m banking on the powerful stuff being worth the initial learning curve and a little extra pain.

When I get the starter project in a more complete state I will be open sourcing the whole thing to help others along, but I wanted to share a few things I’ve learned so far:

In order to use the Email address as the login instead of a username, you need to remove the username property from your UserAccount entity and annotate the Email address property like so:

@NotNull
@UserPrincipal
@Email
public String getEmail() {
    return email;
}

Actions like Registration need a RunAsOperation inner class to handle the fine grained security controls that the Identity Management framework enforces:

    public void register() {
	verified = (confirm != null && confirm.equals(password));

	if (!verified) {
	    FacesMessages.instance().addToControl("confirmPassword", "Passwords do not match");
	}
	new RunAsOperation() {
	    public void execute() {
		try {
		    // Check if email address has already been used
		    if (identityManager.userExists(getEmail())) {
			FacesMessages.instance().addToControl("email", "Email has already been used.");
			return;
		    }
		    identityManager.createUser(email, password, mFirstName, mLastName);
		} catch (IdentityManagementException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		}
		identityManager.grantRole(email, "member");
	    }
	}.addRole("admin").run();

	// Login the user
	identity.getCredentials().setUsername(email);
	identity.getCredentials().setPassword(password);
	identity.login();
    }

Populating custom properties on the User during things like registration requires observing events:

    @Observer(JpaIdentityStore.EVENT_PRE_PERSIST_USER)
    public void prePersistUser(UserAccount pNewUser) {
	// Setup additional UserAccount properties before the user is created
	pNewUser.setRegistrationDate(new Date());
	pNewUser.setOptIn(isOptIn());
    }

You can log audit events with the user’s IP address by doing things like this:

@Scope(ScopeType.EVENT)
@Name("userEvents")
public class UserEvents {
    @Logger
    private Log mLog;

    @Observer(JpaIdentityStore.EVENT_USER_AUTHENTICATED)
    public void loginSuccessful(UserAccount pUser) {
	mLog.info("User logged in with email: #0", pUser.getEmail());
	pUser.setLastLoginDate(new Date());
	Contexts.getSessionContext().set("currentUser", pUser);
	AuditEvent loginEvent = new AuditEvent(((ServletRequest) FacesContext.getCurrentInstance().getExternalContext()
		.getRequest()).getRemoteAddr(), pUser.getId(), "Login Success", null);
	Events.instance().raiseEvent("auditEvent", loginEvent);
    }
}

Hopefully I’ll have the starter project ready soon and will share it with you all. In the meantime, happy hacking!

Spark::red is PCI Level 1 Certified!

image from Purpleslog

I’m happy to announce that Spark::red ATG Hosting has received our PCI DSS 1.2 Level 1 Certification as an eCommerce MSP.  We have been Level 2 certified for a while, but completing our Level 1 certification with TrustWave as our third-party auditor is a huge milestone for us.

PCI DSS is the Payment Card Industry’s Data Security Standard.  It is a set of requirements and guidelines designed to ensure merchants who handle or process credit cards, do so securely.  There are different levels based on transaction volume and Level 1 is the highest level, required for the largest volume merchants.  Level 1 is also the most difficult certification to gain, requiring the strictest security protections, the strongest policies, and a very in depth audit by a certified auditing company, such as TrustWave.  Our certification process has taken many months and the completion of our Level 1 Report of Compliance (RoC) is a testament to our dedication to providing the highest level of secure environments to our clients and safeguarding their systems and information, as well as the information of all our clients’ customers.

At Spark::red we focus strongly on Security and Performance beyond the core ATG hosting services.  We handle more PCI DSS requirements than any other ATG Hosting provider out there.  If you are looking for an ATG Hosting provider to help manage your ATG web application, we can offer PCI Level 1 compliant hosting and handle many of your security needs.

DDOS Against 10MinuteMail

You may have noticed 10MinuteMail was unavailable for a few minutes over the last couple of days. 10MinuteMail recently came under a DDOS attack which locked up the site a few times. Most of the malicious traffic came from the Netherlands, Germany, and to a lesser extend other European countries and the USA. Initially I dealt with it by generating a list of the malicious IPs and adding them to my block list. However, the DDOS kept spreading (botnet?) so I finally did what I should have done ages ago, and tuned my CSF/IPTables firewall to block DDOS patterns. So far so good:)

I have NO IDEA why anyone would be attacking 10MinuteMail. It’s very odd.

Automated ClamAV Virus Scanning

Automating Linux Anti-Virus Using ClamAV and Cron

Thankfully Linux isn’t a platform which has a significant problem with Viruses, however it is always better to be safe than sorry. Luckily ClamAV is an excellent free anti-virus solution for Linux servers. However, at least on RedHat Enterprise 5 (RHEL5) the default install doesn’t offer any automated scanning and alerting. So here is what I’ve done:

The following steps assume you are using RHEL5, but should apply to other Linux distributions as well.

First, you’ll want to install ClamAV:

yum install clamav clamav-db clamd
/etc/init.d/clamd start

On RHEL5 at least this automatically sets up a daily cron job that uses freshclam to update the virus definitions, so that’s good.

Next I recommend removing the test virus files, although you can save this until after you test the rest of the setup:

rm -rf /usr/share/doc/clamav-0.95.3/test/

Now we want to setup our automation. I have a daily cron job that scans the entire server which can take several minutes, and then an hourly cron job that only scans files which were created or modified within the last hour. This should provide rapid notification of any infection without bogging your server down for 5 minutes every hour. The hourly scans run in a couple of seconds.

Each scanning script then checks the scan logs to see if there were any infected files found, and if so immediately sends you a notification e-mail (you could set this address to your mobile phone’s SMS account if you wanted).

The Daily Scan:

emacs /etc/cron.daily/clamscan_daily

Paste in:

#!/bin/bash

# email subject
SUBJECT="VIRUS DETECTED ON `hostname`!!!"
# Email To ?
EMAIL="me@domain.com"
# Log location
LOG=/var/log/clamav/scan.log

check_scan () {

	# Check the last set of results. If there are any "Infected" counts that aren't zero, we have a problem.
	if [ `tail -n 12 ${LOG}  | grep Infected | grep -v 0 | wc -l` != 0 ]
	then
		EMAILMESSAGE=`mktemp /tmp/virus-alert.XXXXX`
		echo "To: ${EMAIL}" >>  ${EMAILMESSAGE}
		echo "From: alert@domain.com" >>  ${EMAILMESSAGE}
		echo "Subject: ${SUBJECT}" >>  ${EMAILMESSAGE}
		echo "Importance: High" >> ${EMAILMESSAGE}
		echo "X-Priority: 1" >> ${EMAILMESSAGE}
		echo "`tail -n 50 ${LOG}`" >> ${EMAILMESSAGE}
		sendmail -t < ${EMAILMESSAGE}
	fi

}

clamscan -r / --exclude-dir=/sys/ --quiet --infected --log=${LOG}

check_scan
chmod +x /etc/cron.daily/clamscan_daily

The Hourly Scan:

emacs /etc/cron.hourly/clamscan_hourly

Paste in:

#!/bin/bash

# email subject
SUBJECT="VIRUS DETECTED ON `hostname`!!!"
# Email To ?
EMAIL="me@domain.com"
# Log location
LOG=/var/log/clamav/scan.log

check_scan () {

	# Check the last set of results. If there are any "Infected" counts that aren't zero, we have a problem.
	if [ `tail -n 12 ${LOG}  | grep Infected | grep -v 0 | wc -l` != 0 ]
	then
		EMAILMESSAGE=`mktemp /tmp/virus-alert.XXXXX`
		echo "To: ${EMAIL}" >>  ${EMAILMESSAGE}
		echo "From: alert@domain.com" >>  ${EMAILMESSAGE}
		echo "Subject: ${SUBJECT}" >>  ${EMAILMESSAGE}
		echo "Importance: High" >> ${EMAILMESSAGE}
		echo "X-Priority: 1" >> ${EMAILMESSAGE}
		echo "`tail -n 50 ${LOG}`" >> ${EMAILMESSAGE}
		sendmail -t < ${EMAILMESSAGE}
	fi

}

find / -not -wholename '/sys/*' -and -not -wholename '/proc/*' -mmin -61 -type f -print0 | xargs -0 -r clamscan --exclude-dir=/proc/ --exclude-dir=/sys/ --quiet --infected --log=${LOG}
check_scan

find / -not -wholename '/sys/*' -and -not -wholename '/proc/*' -cmin -61 -type f -print0 | xargs -0 -r clamscan --exclude-dir=/proc/ --exclude-dir=/sys/ --quiet --infected --log=${LOG}
check_scan

chmod +x /etc/cron.hourly/clamscan_hourly

Protected System

You should now have a well protected system with low impact to system performance and rapid alerting. Anti-Virus is only one piece of protecting a server, but hopefully this makes it easy to implement for everyone.

Monster.com Security Breach

The Monster.com job board database was illegally accessed and large amounts of user data were stolen.

Monster

As is the case with many companies that maintain large databases of information, Monster is the target of illegal attempts to access and extract information from its database. We recently learned our database was illegally accessed and certain contact and account data were taken, including Monster user IDs and passwords, email addresses, names, phone numbers, and some basic demographic data. The information accessed does not include resumes. Monster does not generally collect – and the accessed information does not include – sensitive data such as social security numbers or personal financial data.

The fact that the database was accessed illegally (no word on if it was an internal or external access) is a huge deal. However the fact that they stored passwords in either plaintext, or in a weak enough hash that they feel all the user passwords are compromised, is the most disturbing part of this news in my opinion.

Photo by Dave

There is no excuse for either of those security failures. Especially after the highly public loss of 1.3 million users’ data in 2007.

Assume that your database will be accessed at some point by someone with nefarious intent. If it can happen to Monster.com it can happen to you. Therefore you should not store passwords in plaintext or weakly hashed.

Use a salted SHA-256 or bcrypt hashing algorithm to protect your users’ accounts.

If you use ATG please check out the open source SecurePassword ATG module. It replaces the default insecure password hashing algorithm with a salted SHA-256 hashing mechanism. (as a side note I will develop a bcrypt version shortly, but SSHA-256 is very secure).