radius.py 1.4 KB
Newer Older
Dmitry Lukhtionov's avatar
Dmitry Lukhtionov committed
1
2
3
# ---------------------------------------------------------------------
# RADIUS Authentication backend
# ---------------------------------------------------------------------
Dmitry Volodin's avatar
Dmitry Volodin committed
4
# Copyright (C) 2007-2018 The NOC Project
Dmitry Lukhtionov's avatar
Dmitry Lukhtionov committed
5
6
# See LICENSE for details
# ---------------------------------------------------------------------
Dmitry Volodin's avatar
Dmitry Volodin committed
7

Dmitry Lukhtionov's avatar
Dmitry Lukhtionov committed
8
# Third-party modules
9
import pyrad
Dmitry Volodin's avatar
Dmitry Volodin committed
10
from pyrad.packet import AccessAccept, AccessRequest
Dmitry Volodin's avatar
Dmitry Volodin committed
11
12
from pyrad.client import Client
from pyrad.dictionary import Dictionary
Dmitry Volodin's avatar
Dmitry Volodin committed
13

Vladimir Komarov's avatar
Vladimir Komarov committed
14
15
from noc.core.comp import smart_bytes

Dmitry Lukhtionov's avatar
Dmitry Lukhtionov committed
16
# NOC modules
17
from noc.config import config
Dmitry Volodin's avatar
Dmitry Volodin committed
18
from .base import BaseAuthBackend
Dmitry Volodin's avatar
Dmitry Volodin committed
19
20
21


class RADIUSBackend(BaseAuthBackend):
Dmitry Volodin's avatar
Dmitry Volodin committed
22
    RADIUS_DICT = Dictionary("services/login/backends/radius.dict")
Dmitry Volodin's avatar
Dmitry Volodin committed
23

24
    def authenticate(self, user: str = None, password: str = None, **kwargs) -> str:
25
        radius_server = config.login.radius_server
Vladimir Komarov's avatar
Vladimir Komarov committed
26
        radius_secret = smart_bytes(config.login.radius_secret)
Dmitry Volodin's avatar
Dmitry Volodin committed
27

Dmitry Volodin's avatar
Dmitry Volodin committed
28
29
        client = Client(server=radius_server, secret=radius_secret, dict=self.RADIUS_DICT)
        req = client.CreateAuthPacket(code=AccessRequest, User_Name=user, NAS_Identifier="noc")
Dmitry Volodin's avatar
Dmitry Volodin committed
30
31
32
        req["User-Password"] = req.PwCrypt(password)
        try:
            reply = client.SendPacket(req)
33
        except pyrad.client.Timeout:
Dmitry Volodin's avatar
Dmitry Volodin committed
34
35
            raise self.LoginError("Timed out")
        if reply.code != AccessAccept:
Dmitry Volodin's avatar
Dmitry Volodin committed
36
            raise self.LoginError("RADIUS Authentication failed. Code=%s", reply.code)
37
        return user