File: radius_auth.py

package info (click to toggle)
pyroute2 0.8.1-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,704 kB
  • sloc: python: 50,245; makefile: 280; javascript: 183; ansic: 81; sh: 44; awk: 17
file content (81 lines) | stat: -rw-r--r-- 2,189 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
'''
:test:argv:testing
:test:argv:secret
:test:environ:RADIUS_SERVER=127.0.0.1
:test:environ:RADIUS_SECRET=secret

An example of using RADIUS authentication with NDB.

In order to run the example you can setup a FreeRADIUS server::

    # /etc/raddb/clients
    client test {
        ipaddr = 192.168.122.101  # IP addr of your client
        secret = s3cr3t
    }

    # /etc/raddb/users
    testing Cleartext-Password := "secret"

Then setup your client::

    # download RADIUS dictionaries
    $ export GITSERVER=https://raw.githubusercontent.com
    $ export DICTPATH=pyradius/pyrad/master/example
    $ wget $GITSERVER/$DICTPATH/dictionary
    $ wget $GITSERVER/$DICTPATH/dictionary.freeradius

    # setup the environment
    $ cat radius.rc
    export RADIUS_SERVER=192.168.122.1
    export RADIUS_SECRET=s3cr3t
    export PYTHONPATH=`pwd`

    $ . radius.rc
    $ python3 examples/ndb/radius_auth.py testing secret

'''

import os
import sys
from pyrad.client import Client
from pyrad.dictionary import Dictionary
import pyrad.packet
from pyroute2 import NDB


class RadiusAuthManager(object):
    def __init__(self, user, password, log):
        client = Client(
            server=os.environ.get('RADIUS_SERVER'),
            secret=os.environ.get('RADIUS_SECRET').encode('ascii'),
            dict=Dictionary('dictionary'),
        )
        req = client.CreateAuthPacket(
            code=pyrad.packet.AccessRequest, User_Name=user
        )
        req['User-Password'] = req.PwCrypt(password)
        reply = client.SendPacket(req)
        self.auth = reply.code
        self.log = log

    def check(self, obj, tag):
        #
        self.log.info('%s access' % (tag,))
        return self.auth == pyrad.packet.AccessAccept


with NDB(log='debug') as ndb:
    # create a utility log channel
    log = ndb.log.channel('main')

    # create an AuthManager-compatible object
    log.info('request radius auth')
    am = RadiusAuthManager(sys.argv[1], sys.argv[2], ndb.log.channel('radius'))
    log.info('radius auth complete')

    # create an auth proxy for these credentials
    ap = ndb.auth_proxy(am)

    # validate access via that proxy
    print(ap.interfaces['lo'])