File: nnrpd_auth.py

package info (click to toggle)
inn2 2.7.3-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 10,728 kB
  • sloc: ansic: 102,029; perl: 16,837; sh: 16,752; makefile: 4,014; yacc: 798; lex: 270; python: 268; sql: 192
file content (139 lines) | stat: -rw-r--r-- 5,523 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
##  This is a sample authentication module for the Python nnrpd hook.
##
##  See the INN Python Filtering and Authentication Hooks documentation
##  for more information.
##  The python_auth: parameter in readers.conf is used to load this script.
##
##  An instance of AUTH class is passed to nnrpd via the set_auth_hook()
##  function imported from nnrpd.  The following methods of that class
##  are known to nnrpd:
##
##  __init__()                  - Use this method to initialize your
##                                general variables or open a common
##                                database connection.  May be omitted.
##  authen_init()               - Init function specific to
##                                authentication.  May be omitted.
##  authenticate(attributes)    - Called when a python_auth statement
##                                is reached in the processing of
##                                readers.conf.  Returns a response
##                                code, an error string and an
##                                optional string to appear in the
##                                logs as the username (make sure that
##                                such a message is properly encoded
##                                in UTF-8 so as to comply with the
##                                NNTP protocol).
##  authen_close()              - Called on nnrpd termination.  Save
##                                your state variables or close a database
##                                connection.  May be omitted.
##
##  If there is a problem with return codes from any of these methods,
##  then nnrpd will die and syslog the exact reason.
##
##  There are also a few Python functions defined in nnrpd:
##
##  set_auth_hook()             - Called by nnrpd as this module is loaded.
##                              It is used to pass a reference to an
##                              instance of authentication class to nnrpd.
##  syslog()                    - An equivalent replacement for regular syslog.
##                              One consideration for using it is to
##                              uniform nnrpd logging.


##  Sample authentication class.  It defines all auth methods known to nnrpd.
class AUTH:
    """Provide authentication callbacks to nnrpd."""

    def __init__(self):
        """This is a good place to initialize variables or open a
        database connection."""

        # Create a list of NNTP codes to respond on authentication.
        self.authcodes = {
            "ALLOWED": 281,
            "DENIED": 481,
            "ERROR": 403,
        }

        syslog("notice", "nnrpd authentication class instance created")

    def authen_init(self):
        """Called when this script is initialized."""
        pass

    def authenticate(self, attributes):
        """Called when python_auth: is encountered in readers.conf."""

        # Just for debugging purposes (in Python 3.x syntax).
        # By default, do not log passwords (available in attributes["pass"]).
        #  syslog(
        #      "notice",
        #      "n_a authenticate() invoked: hostname %s, ipaddress %s,"
        #      " port %lu, interface %s, intipaddr %s, intport %lu, user %s"
        #      % (
        #          attributes["hostname"]
        #          .tobytes()
        #          .decode(errors="backslashreplace"),
        #          attributes["ipaddress"].tobytes().decode(),
        #          attributes["port"],
        #          attributes["interface"].tobytes().decode(),
        #          attributes["intipaddr"].tobytes().decode(),
        #          attributes["intport"],
        #          (
        #              attributes["user"]
        #              .tobytes()
        #              .decode(errors="backslashreplace")
        #              if attributes["user"]
        #              else "-"
        #          ),
        #      ),
        #  )

        # Do username password authentication.
        # Python 2.x syntax:
        #  if (
        #      attributes["user"]
        #      and attributes["pass"]
        #      and "foo" == str(attributes["user"])
        #      and "foo" == str(attributes["pass"])
        #  ):
        # Python 3.x syntax:
        #  if (
        #      attributes["user"]
        #      and attributes["pass"]
        #      and b"foo" == attributes["user"].tobytes()
        #      and b"foo" == attributes["pass"].tobytes()
        #  ):
        #      syslog("notice", "authentication by username succeeded")
        #      return (self.authcodes["ALLOWED"], "No error", "default_user")

        syslog("notice", "authentication by username failed")
        return (self.authcodes["DENIED"], "Access Denied!")

    def authen_close(self):
        """Called on nnrpd termination."""
        pass


##  The rest is used to hook up the auth module on nnrpd.  It is unlikely
##  you will ever need to modify this.

##  Import functions exposed by nnrpd.  This import must succeed, or nothing
##  will work!
from nnrpd import *

##  Create a class instance.
myauth = AUTH()

##  ...and try to hook up on nnrpd.  This would make auth object methods
##  visible to nnrpd.
import sys

try:
    set_auth_hook(myauth)
    syslog("notice", "authentication module successfully hooked into nnrpd")
except Exception:  # Syntax valid in both Python 2.x and 3.x.
    e = sys.exc_info()[1]
    syslog(
        "error",
        "Cannot obtain nnrpd hook for authentication method: %s" % e.args[0],
    )