niedziela, 18 września 2011

How to secure your webpage with lighttpd mod_auth

Here's the setup:
There's a web page served by lighttpd by my OpenWRT router. Unfortunately the content shouldn't be available for everyone. Here's the solution:

  1. Install mod_auth

    You can do it with:

    opkg install lighttpd-mod-auth
  2. Create password file
    I first used plain authentication just to see if it's that easy as it's written in documentation. It turned out it is! Better solution is to use htdigest. You just need to create a file that looks like this:
    user1:realm:passwordhash
    user2:realm:passwordhash
    user3:another realm:passwordhash
    Realm is a name of a section of your website that you declare in configuration file. I just use one realm called "download", because I don't need anything more at the moment.
    Password hash is md5 sum calculated from a following string:
    username:realm:password
    e. g. john:website:qwerty would result in hash: 329516de44fe7cf1216194bb02348284.
    Entry in the password file would look like this:
    john:website:329516de44fe7cf1216194bb02348284

    Put your file somewhere where it's not accessible from outside of your server. You don't want anyone to be able to download this file and get to know all users' passwords.
  3. Update configuration
    Uncomment mod_auth in server.modules, for example:
    server.modules = (
    #       "mod_rewrite",
            "mod_redirect",
            "mod_alias",
            "mod_auth",
    #       "mod_status",
    #       "mod_setenv",
    #       "mod_fastcgi",
    #       "mod_proxy",
    #       "mod_simple_vhost",
    #       "mod_cgi",
    #       "mod_ssi",
    #       "mod_usertrack",
    #       "mod_expire",
    #       "mod_webdav"
    )

    Then add this somewhere down the line:
    ## AUTH
    auth.debug = 0
    auth.backend = "htdigest"
    auth.backend.htdigest.userfile = "/path/to/your/file/called/for/example/htdigest.user"
    
    When you want to secure access to your website with a password add:
    auth.require = ( "" =>
                            (
                                    "method" => "digest",
                                    "realm" => "website",
                                    "require" => "valid-user"
                            )
                           )
    
  4. Restart lighttpd
    You can do it with:
    /etc/init.d/lighttpd restart

Now try to access your webpage. You should be greeted with a dialogbox asking for user name and password. In case it's not working increase debug level to 1 or 2 and check out /var/log/lighttpd/error.log to find out what's wrong. Maybe wrong file name, file permissions or password hash? Good luck.