Merging in changes from MichaelBlume, with some modifications of my own.

This commit is contained in:
Josh VanderLinden 2010-10-01 17:41:38 -04:00
parent 75eef30053
commit 2c066c7080
5 changed files with 160 additions and 175 deletions

172
README
View file

@ -1,101 +1,137 @@
django-axes is a very simple way for you to keep track of failed login attempts, both for the Django admin and for the rest of your site. The name is sort of a geeky pun, since `axes` can be read interpretted as:
``django-axes`` is a very simple way for you to keep track of failed login
attempts, both for the Django admin and for the rest of your site. The name is
sort of a geeky pun, since ``axes`` can be read interpreted as:
# "access", as in monitoring access attempts
# "axes", as in tools you can use hack (generally on wood). In this case, however, the "hacking" part of it can be taken a bit further: `django-axes` is intended to help you *stop* people from hacking (popular media definition) your website. Hilarious, right? That's what I thought too!
* "access", as in monitoring access attempts
* "axes", as in tools you can use hack (generally on wood). In this case,
however, the "hacking" part of it can be taken a bit further: ``django-axes``
is intended to help you *stop* people from hacking (popular media
definition) your website. Hilarious, right? That's what I thought too!
==Requirements==
Requirements
============
`django-axes` requires Django 1.0 or later. The application is intended to work around the Django admin and the regular `django.contrib.auth` login-powered pages.
``django-axes`` requires Django 1.0 or later. The application is intended to
work around the Django admin and the regular ``django.contrib.auth``
login-powered pages.
==Installation==
Installation
============
Download `django-axes` using *one* of the following methods:
Download ``django-axes`` using **one** of the following methods:
===easy_install===
easy_install
------------
You can download the package from the [http://pypi.python.org/pypi/django-axes/ CheeseShop] or use
You can download the package from the `CheeseShop <http://pypi.python.org/pypi/django-axes/>`_ or use::
{{{
easy_install django-axes
}}}
easy_install django-axes
to download and install `django-axes`.
to download and install ``django-axes``.
===Package Download===
Package Download
----------------
Download the latest `.tar.gz` file from the downloads section and extract it somewhere you'll remember. Use `python setup.py install` to install it.
Download the latest ``.tar.gz`` file from the downloads section and extract it
somewhere you'll remember. Use ``python setup.py install`` to install it.
===Checkout from Mercurial===
Checkout from Mercurial
-----------------------
Execute the following command (or use the equivalent function in a GUI such as TortoiseHg), and make sure you're checking `django-axes` out somewhere on the `PYTHONPATH`.
Execute the following command (or use the equivalent function in a GUI such as
TortoiseHg), and make sure you're checking ``django-axes`` out somewhere on the
``PYTHONPATH``::
{{{
hg clone http://django-axes.googlecode.com/hg django-axes
hg clone http://bitbucket.org/codekoala/django-axes
}}}
hg clone http://django-axes.googlecode.com/hg django-axes
hg clone http://bitbucket.org/codekoala/django-axes
===Checkout from GitHub===
Checkout from GitHub
--------------------
Execute the following command, and make sure you're checking `django-axes` out somewhere on the `PYTHONPATH`.
Execute the following command, and make sure you're checking ``django-axes``
out somewhere on the ``PYTHONPATH``::
{{{
git clone git://github.com/codekoala/django-axes.git
}}}
git clone git://github.com/codekoala/django-axes.git
===Verifying Installation===
Verifying Installation
----------------------
The easiest way to ensure that you have successfully installed `django-axes` is to execute a command such as:
The easiest way to ensure that you have successfully installed ``django-axes``
is to execute a command such as::
{{{
python -c "import axes; print axes.get_version()"
}}}
python -c "import axes; print axes.get_version()"
If that command completes with some sort of version number, you're probably good to go. If you see error outout, you need to check your installation (I'd start with your `PYTHONPATH`).
If that command completes with some sort of version number, you're probably
good to go. If you see error output, you need to check your installation (I'd
start with your ``PYTHONPATH``).
==Configuration==
Configuration
=============
First of all, you must add this project to your list of `INSTALLED_APPS` in `settings.py`:
First of all, you must add this project to your list of ``INSTALLED_APPS`` in
``settings.py``::
{{{
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
...
'axes',
...
)
}}}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
...
'axes',
...
)
Next, install the `FailedLoginMiddleware` middleware:
Next, install the ``FailedLoginMiddleware`` middleware::
{{{
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'axes.middleware.FailedLoginMiddleware'
)
}}}
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'axes.middleware.FailedLoginMiddleware'
)
Run `manage.py syncdb`. This creates the appropriate tables in your database that are necessary for operation.
Run ``manage.py syncdb``. This creates the appropriate tables in your database
that are necessary for operation.
===Customizing Axes===
Customizing Axes
----------------
You have a couple options available to you to customize `django-axes` a bit. These should be defined in your `settings.py` file.
You have a couple options available to you to customize ``django-axes`` a bit.
These should be defined in your ``settings.py`` file.
* `AXES_LOGIN_FAILURE_LIMIT`: The number of login attempts allowed before a record is created for the failed logins. Default: `3`
* `AXES_LOCK_OUT_AT_FAILURE`: After the number of allowed login attempts are exceeded, should we lock out this IP (and optional user agent)? Default: `True`
* `AXES_USE_USER_AGENT`: If True, lock out / log based on an IP address AND a user agent. This means requests from different user agents but from the same IP are treated differently. Default: `False`
* `AXES_COOLOFF_TIME`: If set, defines a period of inactivity after which old failed login attempts will be forgotten. Can be set to a python timedelta object or an integer. If an integer, will be interpreted as a number of hours.
* `AXES_LOGGER`: If set, specifies a logging mechanism for axes to use.
* `AXES_LOCKOUT_TEMPLATE`: If set, specifies a template to render when a user is locked out. Template receives cooloff_time and failure_limit as context variables.
* `AXES_LOCKOUT_URL`: If set, specifies a URL to redirect to on lockout. If both AXES_LOCKOUT_TEMPLATE and AXES_LOCKOUT_URL are set, the template will be used.
* ``AXES_LOGIN_FAILURE_LIMIT``: The number of login attempts allowed before a
record is created for the failed logins. Default: ``3``
* ``AXES_LOCK_OUT_AT_FAILURE``: After the number of allowed login attempts
are exceeded, should we lock out this IP (and optional user agent)?
Default: ``True``
* ``AXES_USE_USER_AGENT``: If ``True``, lock out / log based on an IP address
AND a user agent. This means requests from different user agents but from
the same IP are treated differently. Default: ``False``
* ``AXES_COOLOFF_TIME``: If set, defines a period of inactivity after which
old failed login attempts will be forgotten. Can be set to a python
timedelta object or an integer. If an integer, will be interpreted as a
number of hours.
* ``AXES_LOGGER``: If set, specifies a logging mechanism for axes to use.
* ``AXES_LOCKOUT_TEMPLATE``: If set, specifies a template to render when a
user is locked out. Template receives cooloff_time and failure_limit as
context variables.
* ``AXES_LOCKOUT_URL``: If set, specifies a URL to redirect to on lockout. If
both AXES_LOCKOUT_TEMPLATE and AXES_LOCKOUT_URL are set, the template will
be used.
* ``AXES_VERBOSE``: If ``True``, you'll see slightly more logging for Axes.
Default: ``True``
==Usage==
Usage
=====
Using `django-axes` is extremely simple. Once you install the application and the middleware, all you need to do is periodically check the Access Attempts section of the admin. A log file is also created for you to keep track of the events surrounding failed login attempts. This log file can be found in your Django project directory, by the name of `axes.log`. In the future I plan on offering a way to customize options for logging a bit more.
Using ``django-axes`` is extremely simple. Once you install the application
and the middleware, all you need to do is periodically check the Access
Attempts section of the admin. A log file is also created for you to keep
track of the events surrounding failed login attempts. This log file can be
found in your Django project directory, by the name of ``axes.log``. In the
future I plan on offering a way to customize options for logging a bit more.
By default, django-axes will lock out repeated attempts from the same IP address. You can allow this IP to attempt again by deleting the relevant AccessAttempt records in the admin.
By default, django-axes will lock out repeated attempts from the same IP
address. You can allow this IP to attempt again by deleting the relevant
``AccessAttempt`` records in the admin.

1
README.rst Symbolic link
View file

@ -0,0 +1 @@
README

View file

@ -1,57 +1,33 @@
from datetime import datetime, timedelta
import logging
from django.conf import settings
from django.contrib.auth import logout
from django.shortcuts import render_to_response
from axes.models import AccessAttempt
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
import axes
import datetime
import logging
from django.core.cache import cache
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from axes.models import AccessAttempt
import axes
# see if the user has overridden the failure limit
try:
FAILURE_LIMIT = settings.AXES_LOGIN_FAILURE_LIMIT
except:
FAILURE_LIMIT = 3
FAILURE_LIMIT = getattr(settings, 'AXES_LOGIN_FAILURE_LIMIT', 3)
# see if the user has set axes to lock out logins after failure limit
try:
LOCK_OUT_AT_FAILURE = settings.AXES_LOCK_OUT_AT_FAILURE
except:
LOCK_OUT_AT_FAILURE = True
LOCK_OUT_AT_FAILURE = getattr(settings, 'AXES_LOCK_OUT_AT_FAILURE', True)
try:
USE_USER_AGENT = settings.AXES_USE_USER_AGENT
except:
USE_USER_AGENT = False
USE_USER_AGENT = getattr(settings, 'AXES_USE_USER_AGENT', False)
try:
COOLOFF_TIME = settings.AXES_COOLOFF_TIME
if isinstance(COOLOFF_TIME, int):
COOLOFF_TIME = datetime.timedelta(hours=COOLOFF_TIME)
except:
COOLOFF_TIME = None
COOLOFF_TIME = getattr(settings, 'AXES_COOLOFF_TIME', None)
if isinstance(COOLOFF_TIME, int):
COOLOFF_TIME = timedelta(hours=COOLOFF_TIME)
try:
LOGGER = settings.AXES_LOGGER
except:
LOGGER = 'axes.watch_login'
LOGGER = getattr(settings, 'AXES_LOGGER', 'axes.watch_login')
try:
LOCKOUT_TEMPLATE = settings.AXES_LOCKOUT_TEMPLATE
except:
LOCKOUT_TEMPLATE = None
try:
LOCKOUT_URL = settings.AXES_LOCKOUT_URL
except:
LOCKOUT_URL = None
try:
VERBOSE = settings.AXES_VERBOSE
except:
VERBOSE = True
LOCKOUT_TEMPLATE = getattr(settings, 'AXES_LOCKOUT_TEMPLATE', None)
LOCKOUT_URL = getattr(settings, 'AXES_LOCKOUT_URL', None)
VERBOSE = getattr(settings, 'AXES_VERBOSE', True)
def query2str(items):
return '\n'.join(['%s=%s' % (k, v) for k,v in items])
@ -77,13 +53,15 @@ def get_user_attempt(request):
attempts = AccessAttempt.objects.filter(
ip_address=ip
)
if not attempts:
return None
attempt = attempts[0]
if COOLOFF_TIME:
if attempt.attempt_time + COOLOFF_TIME < datetime.datetime.now():
attempt.delete()
return None
if COOLOFF_TIME and attempt.attempt_time + COOLOFF_TIME < datetime.now():
attempt.delete()
return None
return attempt
def watch_login(func):
@ -94,7 +72,7 @@ def watch_login(func):
def decorated_login(request, *args, **kwargs):
# share some useful information
if func.__name__ != 'decorated_login' and VERBOSE:
log.info('AXES: Calling decorated function: %s' % func)
log.info('AXES: Calling decorated function: %s' % func.__name__)
if args: log.info('args: %s' % args)
if kwargs: log.info('kwargs: %s' % kwargs)
@ -120,20 +98,21 @@ def watch_login(func):
return response
if LOCKOUT_TEMPLATE:
context = RequestContext(request)
context['cooloff_time'] = COOLOFF_TIME
context['failure_limit'] = FAILURE_LIMIT
context = RequestContext(request, {
'cooloff_time': COOLOFF_TIME,
'failure_limit': FAILURE_LIMIT,
})
return render_to_response(LOCKOUT_TEMPLATE, context)
if LOCKOUT_URL:
return HttpResponseRedirect(LOCKOUT_URL)
if COOLOFF_TIME:
return HttpResponse("Account locked: too many login attempts. "
"Please try again later."
)
"Please try again later.")
else:
return HttpResponse("Account locked: too many login attempts. "
"Contact an admin to unlock your account."
)
"Contact an admin to unlock your account.")
return response
return decorated_login
@ -147,14 +126,13 @@ def check_request(request, login_unsuccessful):
# no matter what, we want to lock them out
# if they're past the number of attempts allowed
if failures > FAILURE_LIMIT:
if LOCK_OUT_AT_FAILURE:
# We log them out in case they actually managed to enter
# the correct password.
logout(request)
log.warn('AXES: locked out %s after repeated login attempts.' %
attempt.ip_address)
return False
if failures > FAILURE_LIMIT and LOCK_OUT_AT_FAILURE:
# We log them out in case they actually managed to enter
# the correct password.
logout(request)
log.warn('AXES: locked out %s after repeated login attempts.' %
attempt.ip_address)
return False
if login_unsuccessful:
# add a failed attempt for this user
@ -174,7 +152,7 @@ def check_request(request, login_unsuccessful):
attempt.http_accept = request.META.get('HTTP_ACCEPT', '<unknown>')
attempt.path_info = request.META.get('PATH_INFO', '<unknown>')
attempt.failures_since_start = failures
attempt.attempt_time = datetime.datetime.now()
attempt.attempt_time = datetime.now()
attempt.save()
log.info('AXES: Repeated login failure by %s. Updating access '
'record. Count = %s' %
@ -194,7 +172,8 @@ def check_request(request, login_unsuccessful):
log.info('AXES: New login failure by %s. Creating access record.' %
ip)
else:
#user logged in -- forget the failed attempts
# user logged in -- forget the failed attempts
if attempt:
attempt.delete()
return True

View file

@ -4,8 +4,7 @@ def reset(ip=None, silent=False):
if not ip:
attempts = AccessAttempt.objects.all()
if attempts:
for attempt in AccessAttempt.objects.all():
attempt.delete()
attempts.delete()
else:
if not silent:
print 'No attempts found.'
@ -17,3 +16,4 @@ def reset(ip=None, silent=False):
print 'No matching attempt found.'
else:
attempt.delete()

View file

@ -1,54 +1,23 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import setup, find_packages
import axes
import sys, os
def fullsplit(path, result=None):
"""
Split a pathname into components (the opposite of os.path.join) in a
platform-neutral way.
"""
if result is None:
result = []
head, tail = os.path.split(path)
if head == '':
return [tail] + result
if head == path:
return result
return fullsplit(head, [tail] + result)
packages, data_files = [], []
root_dir = os.path.dirname(__file__)
if root_dir != '':
os.chdir(root_dir)
axes_dir = 'axes'
for path, dirs, files in os.walk(axes_dir):
# ignore hidden directories and files
for i, d in enumerate(dirs):
if d.startswith('.'): del dirs[i]
if '__init__.py' in files:
packages.append('.'.join(fullsplit(path)))
elif files:
data_files.append((path, [os.path.join(path, f) for f in files]))
setup(
name='django-axes',
version=axes.get_version(),
url='http://code.google.com/p/django-axes/',
author='Josh VanderLinden',
author_email='codekoala@gmail.com',
license='MIT',
packages=packages,
data_files=data_files,
description="Keep track of failed login attempts in Django-powered sites.",
long_description="""
django-axes is a very simple way for you to keep track of failed login attempts, both for the Django admin and for the rest of your site. All you need to do is install the application, a middleware, and syncdb!
""",
long_description=open('README.rst', 'r').read(),
keywords='django, security, authentication',
author='Josh VanderLinden, Philip Neustrom',
author_email='codekoala@gmail.com',
url='http://bitbucket.org/codekoala/django-axes/',
license='MIT',
package_dir={'axes': 'axes'},
include_package_data=True,
packages=find_packages(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',