Skip to content

Commit

Permalink
Merge branch 'master' into patch-1
Browse files Browse the repository at this point in the history
  • Loading branch information
btimby authored Feb 19, 2019
2 parents c8be89a + ff943ff commit 0b3bf72
Show file tree
Hide file tree
Showing 5 changed files with 317 additions and 133 deletions.
126 changes: 126 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@

# Created by https://www.gitignore.io/api/python
# Edit at https://www.gitignore.io/?templates=python

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

### Python Patch ###
.venv/

# End of https://www.gitignore.io/api/python
7 changes: 6 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
sudo: required
dist: xenial
language: python
python:
- "2.7"
- "3.3"
- "3.4"
- "3.5"
- "3.6"
- "3.7"
install:
- make dependencies
before_script:
- sudo sysctl -w net.ipv6.conf.all.disable_ipv6=0
- sudo sysctl -w net.ipv6.conf.lo.disable_ipv6=0
script:
- make travis
after_success:
Expand Down
126 changes: 72 additions & 54 deletions radius.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import os
import sys
import socket
import logging
import struct

from select import select
from random import randint
from contextlib import closing, contextmanager
import contextlib

try:
from collections import UserDict
Expand All @@ -56,8 +56,6 @@
except ImportError:
from md5 import new as md5

from six import PY3


__version__ = '2.0.2'

Expand Down Expand Up @@ -240,6 +238,7 @@ class SocketError(NoResponse):
pass


PY3 = sys.version_info > (3, 0, 0)
if PY3:
# These functions are used to act upon strings in Python2, but bytes in
# Python3. Their functions are not necessary in PY3, so we NOOP them.
Expand Down Expand Up @@ -405,6 +404,10 @@ def unpack(data):
return Attributes(attrs)


class VerificationError(AssertionError):
pass


class Message(object):
"""
Represents a radius protocol packet.
Expand Down Expand Up @@ -470,10 +473,12 @@ def verify(self, data):
unpacks it.
"""
id = ord(data[1])
assert self.id == id, 'ID mismatch (%s != %s)' % (self.id, id)
if self.id != id:
raise VerificationError('ID mismatch (%s != %s)' % (self.id, id))
signature = md5(
data[:4] + self.authenticator + data[20:] + self.secret).digest()
assert signature == data[4:20], 'Invalid authenticator'
if signature != data[4:20]:
raise VerificationError('Invalid authenticator')
return Message.unpack(self.secret, data)


Expand Down Expand Up @@ -502,47 +507,60 @@ def port(self):
def secret(self):
return self._secret

@contextmanager
def connect(self):
with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as c:
c.connect((self.host, self.port))
LOGGER.debug('Connected to %s:%s', self.host, self.port)
yield c

def send_message(self, message):
send = message.pack()

try:
with self.connect() as c:
for i in range(self.retries):
LOGGER.debug(
'Sending (as hex): %s',
':'.join(format(ord(c), '02x') for c in send))

c.send(send)

r, w, x = select([c], [], [], self.timeout)
if c in r:
recv = c.recv(PACKET_MAX)
else:
# No data available on our socket. Try again.
LOGGER.warning('Timeout expired on try %s', i)
continue

LOGGER.debug(
'Received (as hex): %s',
':'.join(format(ord(c), '02x') for c in recv))

try:
return message.verify(recv)
except AssertionError as e:
LOGGER.warning('Invalid response discarded %s', e)
# Silently discard invalid replies (as RFC states).
continue

except socket.error as e: # SocketError
LOGGER.debug('Socket error', exc_info=True)
raise SocketError(e)
addrs = socket.getaddrinfo(
self.host,
self.port,
0,
socket.SOCK_DGRAM,
)

@contextlib.contextmanager
def connect(res):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socket.socket(af, socktype, proto)
sock.settimeout(self.timeout)
sock.connect(sa)
yield sock
finally:
if sock is not None:
sock.close()

def attempt(res):
with connect(res) as c:
c.send(send)
recv = c.recv(PACKET_MAX)

LOGGER.debug(
'Received (as hex): %s',
':'.join(format(ord(c), '02x') for c in recv))

return message.verify(recv)

err = None
LOGGER.debug(
'Sending (as hex): %s',
':'.join(format(ord(c), '02x') for c in send))

for i in range(self.retries):
for res in addrs:
try:
return attempt(res)
except socket.timeout:
LOGGER.warning('Timeout expired on try %s', i)
except VerificationError as e:
LOGGER.warning('Invalid response discarded %s', e)
# Silently discard invalid replies (as RFC states).
except socket.error as e:
LOGGER.debug('Socket error', exc_info=True)
err = e

if err is not None:
raise SocketError(err)

LOGGER.error('Request timed out after %s tries', i)
raise NoResponse()
Expand Down Expand Up @@ -604,6 +622,9 @@ def authenticate(self, username, password, **kwargs):


def main():
import sys
import traceback

host = raw_input("Host [default: 'radius']: ")
port = raw_input('Port [default: %s]: ' % DEFAULT_PORT)

Expand All @@ -627,40 +648,37 @@ def _status(outcome):
sys.exit(0)
else:
sys.exit('Authentication Failed')
err = None

try:
_status(authenticate(secret, username, password, host=host, port=port))
except ChallengeResponse as e:
pass
except Exception as e:
err = e
except Exception:
traceback.print_exc()
sys.exit('Authentication Error')

print('RADIUS server replied with a challenge.')

for m in e.messages:
for m in getattr(err, 'messages', []):
print(' - %s' % m)

response = None
while not response:
response = raw_input('Enter your challenge response: ')

a = Attributes()
if e.state:
a['State'] = e.state
state = getattr(err, 'state', None)
a = Attributes({'State': state} if state else {})

try:
_status(authenticate(secret, username, response, host=host, port=port,
attributes=a))
except Exception as e:
except Exception:
traceback.print_exc()
sys.exit('Authentication Error')


if __name__ == '__main__':
import sys
import traceback

LOGGER.addHandler(logging.StreamHandler())
LOGGER.setLevel(logging.DEBUG)

Expand Down
1 change: 0 additions & 1 deletion requirements.txt

This file was deleted.

Loading

0 comments on commit 0b3bf72

Please sign in to comment.