radius.py 1.38 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
Dmitry Volodin's avatar
Dmitry Volodin committed
9
from pyrad.packet import AccessAccept, AccessRequest
10
from pyrad.client import Client, Timeout
Dmitry Volodin's avatar
Dmitry Volodin committed
11
from pyrad.dictionary import Dictionary
Dmitry Volodin's avatar
Dmitry Volodin committed
12

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

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


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

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

Dmitry Volodin's avatar
Dmitry Volodin committed
27
28
        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
29
30
31
        req["User-Password"] = req.PwCrypt(password)
        try:
            reply = client.SendPacket(req)
32
        except Timeout:
Dmitry Volodin's avatar
Dmitry Volodin committed
33
34
            raise self.LoginError("Timed out")
        if reply.code != AccessAccept:
Dmitry Volodin's avatar
Dmitry Volodin committed
35
            raise self.LoginError("RADIUS Authentication failed. Code=%s", reply.code)
36
        return user