Přeskočit na hlavní obsah

Zabezpečení webových aplikací

Nedávno jsem dostal za úkol implementovat autentizaci a autorizaci (přihlašování a implementace přístupových práv) v několika webových aplikacích u zákazníka. Aplikace sice využívají Hibernate, ale bohužel už ne Spring, pro který existuje security framework Acegi, poskytující přesně tu funkcionalitu, kterou potřebujeme. Acegi už jsem v jednom projektu úspěšně použil a tak jsem nebyl nadšenej z toho, že musím hledat jiné řešení.

Nakonec jsem část Acegi (zdrojáků) přeci jen použil. A to mírně upravené třídy z balíku org.acegisecurity.context, pomocí kterých lze jednoduše (s využitím servlet filtru) získat kdekoliv v aplikaci právě přihlášeného uživatele.

Další krok bylo vynucení přihlášení pro přístup k chráněným částem aplikace. Přemýšlel jsem o využití možností servlet kontejneru (např. Security Realm v Tomcatu), ale nevýhodou je, že pak pro deploy aplikace nestačí mít soubor s archivem (war), ale musíte také nakonfigurovat daný Realm přímo v instalaci Tomcatu. Navíc je toto řešení obtížně přenositelné mezi různými kontejnery, díky neexistující specifikaci, která by řešila detaily tohoto přístupu.

Nakonec jsem našel řešení v podobě knihovny SecurityFilter, která zajišťuje stejnou funkcionalitu jako Security Realm u Tomcatu, ale funguje na principu servlet filteru, takže se nemusíte zatěžovat konfigurováním servlet kontejneru ani se obávat nekompatibility mezi různými kontejnery. Stačí zaregistrovat filtr ve web.xml vytvořit implementaci pro interface org.securityfilter.realm.SecurityRealmInterface, a nakonfigurovat které role mají kam přístup a je to.

Jednoduchá implementace SecurityRealmInterface může vypadat následovně.

/**
* Returns object which returns Principal (in our case instance of class User).
* User which has given username and password is loaded by Hibernate and returned.
* @param username case insensitiv username
* @param password case sensitive password
* @see org.securityfilter.realm.SecurityRealmInterface#authenticate(java.lang.String, java.lang.String)
*/
public Principal authenticate(String username, String password) {
  log.debug("authenticate start");
  if (username==null || password==null) {
    log.info("username or password is null");
    return null;
  }
  final Session tmpSess = HibernateUtils.getCurrentSession();
  final boolean tmpInitTrans = ! tmpSess.getTransaction().isActive();
  if (tmpInitTrans) {
    tmpSess.beginTransaction();
  }
  final Query tmpQuery = tmpSess.createQuery(
      "FROM User u WHERE upper(u.username) = upper(:username)" +
      " AND u.password= :password");
  final User tmpUser =
    (User) tmpQuery
      .setString("username", username)
      .setString("password", password)
      .uniqueResult();
  if (tmpInitTrans) {
    tmpSess.getTransaction().commit();
  }
  return tmpUser;
}

/**
* Returns true if given user is in given role.
* @param user object of class User (see authenticate())
* @param role role name to test
* @return true if user is mapped to the role
* @see org.securityfilter.realm.SecurityRealmInterface#isUserInRole(Principal, String)
*/
public boolean isUserInRole(Principal user, String role) {
  if (user==null || role==null || !(user instanceof User)) {
    return false;
  }
  final User tmpUser = (User) user;
  final boolean tmpResult = tmpUser.isInRole(role);
  return tmpResult;
}

Třída User implementuje rozhraní java.security.Principal, což je snad ze zápisu zřejmé. Jestliže pracujete na tomcatu, je možné použít i realmy tomcatovské (např. org.apache.catalina.realm.JDBCRealm), pro které je v SecurityFiltru přibalen Catalina adaptér (org.securityfilter.realm.catalina.CatalinaRealmAdapter).

Kompletní konfigurační soubor securityfilter-config.xml v mém příkladu vypadá následovně:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE securityfilter-config PUBLIC
    "-//SecurityFilter.org//DTD Security Filter Configuration 2.0//EN"
    "http://www.securityfilter.org/dtd/securityfilter-config_2_0.dtd">

<securityfilter-config>

   <security-constraint>
      <web-resource-collection>
         <web-resource-name>Restricted pages</web-resource-name>
         <url-pattern>/protected/*</url-pattern>
      </web-resource-collection>
      <auth-constraint>
         <role-name>admin</role-name>
      </auth-constraint>
   </security-constraint>

   <login-config>
      <auth-method>FORM</auth-method>
      <form-login-config>
         <form-login-page>/login.do</form-login-page>
         <form-error-page>/loginError.jsp</form-error-page>
         <form-default-page>/start.do</form-default-page>
         <form-logout-page>/logout.jsp</form-logout-page>
      </form-login-config>
   </login-config>

   <realm className="cz.cacek.myapp.MyAppRealm"/>

</securityfilter-config>

A integrace do web.xml:

<filter>
 <filter-name>Security Filter</filter-name>
 <filter-class>org.securityfilter.filter.SecurityFilter</filter-class>
 <init-param>
  <description>Configuration file location (this is the default value)</description>
  <param-name>config</param-name>
  <param-value>/WEB-INF/securityfilter-config.xml</param-value>
 </init-param>
 <init-param>
  <description>Validate config file if set to true</description>
  <param-name>validate</param-name>
  <param-value>true</param-value>
 </init-param>
 <init-param>
  <description>
   As an example a login form can define "logMeIn" as it action in place of the standard
   "j_security_check" which is a special flag user by app servers for container managed security.
  </description>
  <param-name>loginSubmitPattern</param-name>
  <param-value>/logMeIn.do</param-value>
 </init-param>
</filter>

Ještě je potřeba tento filtr namapovat na požadovaný tvar URL nebo na servlet.

Při zabezpečování se nesmí zapomenout na kontrolu oprávnění na straně serveru. Opravdu není dostatečné řešení, kdy se pouze skryjí před neautorizovaným uživatelem URL na která by se neměl dostat. Co není povoleno, musí být zakázáno.

Stejně tak kontrola vstupních parametrů musí být samozřejmostí. Když je například editován objekt, ke kterému má daný uživatel právo, ale zlý uživatel v odesílaném formuláři změní ID objektu (bývá uloženo v hidden inputu) je dost dobře možné, že se mu podaří změnit cizí záznamy.

Metody zde popsané rozhodně nepřináší úplný výčet bodů pro zabezpečení webové aplikace. Pro další rady se můžete podívat do konference java.cz, kde se nedávno toto téma probíralo.

Linky:

Komentáře

Populární příspěvky z tohoto blogu

Three ways to redirect HTTP requests to HTTPs in WildFly and JBoss EAP

WildFly application server (and JBoss EAP) supports several simple ways how to redirect the communication from plain HTTP to TLS protected HTTPs. This article presents 3 ways. Two are on the application level and the last one is on the server level valid for requests to all deployments. 1. Request confidentiality in the deployment descriptor The first way is based on the Servlet specification. You need to specify which URLs should be protected in the web.xml deployment descriptor. It's the same approach as the one used for specifying which URLs require authentication/authorization. Just instead of requesting an assigned role, you request a transport-guarantee . Sample content of the WEB-INF/web.xml <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1...

Simple TLS certificates in WildFly 18

It's just 2 weeks when WildFly 18 was released. It includes nice improvements in TLS certificates handling through ACME protocol (Automatic Certificate Management Environment), it greatly simplifies obtaining valid HTTPS certificates. There was already a support for the Let's Encrypt CA in WildFly 14 as Farah Juma described in her blog post last year. New WildFly version allows using other CA-s with ACME protocol support. It also adds new switch --lets-encrypt to interactive mode of security enable-ssl-http-server JBoss CLI commands. Let's try it. Before we jump on WildFly configuration, let's just mention the HTTPs can be used even in the default configuration and a self-signed certificate is generated on the fly. Nevertheless, it's not secure and you should not use it for any other purpose than testing. Use Let's Encrypt signed certificate for HTTPs application interface Start WildFly on a machine with the public IP address. Run it on the defaul...

JSignPKCS11 - when your smartcard is too smart

TL;DR Yes, you can add digital signatures in Java even when you use newer hardware tokens such as Gemalto SafeNet eToken 5110 CC. JSignPKCS11 might help. Maybe you've seen the infamous PKCS11 error message CKR_USER_NOT_LOGGED_IN already. Thrown even when the SunPKCS11 security provider and the keystore settings were properly configured for your hardware token. java.security.ProviderException: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_USER_NOT_LOGGED_IN at jdk.crypto.cryptoki/sun.security.pkcs11.P11Signature.engineSign(P11Signature.java:685) at java.base/java.security.Signature$Delegate.engineSign(Signature.java:1404) at java.base/java.security.Signature.sign(Signature.java:713) ... Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_USER_NOT_LOGGED_IN at jdk.crypto.cryptoki/sun.security.pkcs11.wrapper.PKCS11.C_Sign(Native Method) at jdk.crypto.cryptoki/sun.security.pkcs11.P11Signature.engineSign(P11Signature.java:664) ...