]>
git.ipfire.org Git - ipfire-2.x.git/blob - config/ovpn/openvpn-authenticator
2 ###############################################################################
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2022 Michael Tremer #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
20 ###############################################################################
27 import logging
.handlers
33 OPENVPN_CONFIG
= "/var/ipfire/ovpn/ovpnconfig"
35 CHALLENGETEXT
= "One Time Token: "
37 log
= logging
.getLogger()
38 log
.setLevel(logging
.DEBUG
)
40 def setup_logging(daemon
=True, loglevel
=logging
.INFO
):
41 log
.setLevel(loglevel
)
43 # Log to syslog by default
44 handler
= logging
.handlers
.SysLogHandler(address
="/dev/log", facility
="daemon")
45 log
.addHandler(handler
)
48 formatter
= logging
.Formatter("%(name)s[%(process)d]: %(message)s")
49 handler
.setFormatter(formatter
)
51 handler
.setLevel(loglevel
)
53 # If we are running in foreground, we should write everything to the console, too
55 handler
= logging
.StreamHandler()
56 log
.addHandler(handler
)
58 handler
.setLevel(loglevel
)
62 class OpenVPNAuthenticator(object):
63 def __init__(self
, socket_path
):
64 self
.socket_path
= socket_path
70 char
= self
.sock
.recv(1)
77 line
= b
"".join(buf
).decode()
80 log
.debug("< %s" % line
)
84 def _write_line(self
, line
):
85 log
.debug("> %s" % line
)
87 if not line
.endswith("\n"):
96 def _send_command(self
, command
):
98 self
._write
_line
(command
)
100 return # XXX Code below doesn't work
103 response
= self
._read
_line
()
106 if not response
.startswith("SUCCESS:"):
107 log
.error("Command '%s' returned an error:" % command
)
108 log
.error(" %s" % response
)
114 self
.sock
= socket
.socket(socket
.AF_UNIX
, socket
.SOCK_STREAM
)
115 self
.sock
.connect(self
.socket_path
)
117 log
.info("OpenVPN Authenticator started")
120 line
= self
._read
_line
()
122 if line
.startswith(">CLIENT"):
123 self
._client
_event
(line
)
125 log
.info("OpenVPN Authenticator terminated")
127 def terminate(self
, *args
):
131 def _client_event(self
, line
):
132 # Strip away "CLIENT:"
133 client
, delim
, line
= line
.partition(":")
135 # Extract the event & split any arguments
136 event
, delim
, arguments
= line
.partition(",")
137 arguments
= arguments
.split(",")
141 if event
== "CONNECT":
142 environ
= self
._read
_env
(environ
)
143 self
._client
_connect
(*arguments
, environ
=environ
)
144 elif event
== "DISCONNECT":
145 environ
= self
._read
_env
(environ
)
146 self
._client
_disconnect
(*arguments
, environ
=environ
)
147 elif event
== "REAUTH":
148 environ
= self
._read
_env
(environ
)
149 self
._client
_reauth
(*arguments
, environ
=environ
)
150 elif event
== "ESTABLISHED":
151 environ
= self
._read
_env
(environ
)
153 log
.debug("Unhandled event: %s" % event
)
155 def _read_env(self
, environ
):
158 line
= self
._read
_line
()
160 if not line
.startswith(">CLIENT:ENV,"):
161 raise RuntimeError("Unexpected environment line: %s" % line
)
171 key
, delim
, value
= line
.partition("=")
176 def _client_connect(self
, cid
, kid
, environ
={}):
177 log
.debug("Received client connect (cid=%s, kid=%s)" % (cid
, kid
))
178 for key
in sorted(environ
):
179 log
.debug(" %s : %s" % (key
, environ
[key
]))
182 common_name
= environ
.get("common_name")
184 # Find connection details
185 conn
= self
._find
_connection
(common_name
)
187 log
.warning("Could not find connection '%s'" % common_name
)
190 log
.debug("Found connection:")
192 log
.debug(" %s : %s" % (key
, conn
[key
]))
194 # Perform no further checks if TOTP is disabled for this client
195 if not conn
.get("totp_status") == "on":
196 return self
._client
_auth
_successful
(cid
, kid
)
198 # Fetch username & password
199 username
= environ
.get("username")
200 password
= environ
.get("password")
202 # Client sent the special password TOTP to start challenge authentication
203 if password
== "TOTP":
204 return self
._client
_auth
_challenge
(cid
, kid
,
205 username
=common_name
, password
="TOTP")
207 elif password
.startswith("CRV1:"):
208 log
.debug("Received dynamic challenge response %s" % password
)
211 (command
, flags
, username
, password
, token
) = password
.split(":", 5)
214 username
= self
._b
64decode
(username
)
216 # Check if username matches common name
217 if username
== common_name
:
218 # Check if TOTP token matches
219 if self
._check
_totp
_token
(token
, conn
.get("totp_secret")):
220 return self
._client
_auth
_successful
(cid
, kid
)
222 # Restart authentication
223 self
._client
_auth
_challenge
(cid
, kid
,
224 username
=common_name
, password
="TOTP")
226 def _client_disconnect(self
, cid
, environ
={}):
228 Handles CLIENT:DISCONNECT events
232 def _client_reauth(self
, cid
, kid
, environ
={}):
234 Handles CLIENT:REAUTH events
237 self
._client
_auth
_successful
(cid
, kid
)
239 def _client_auth_challenge(self
, cid
, kid
, username
, password
):
241 Initiates a dynamic challenge authentication with the client
243 log
.debug("Sending request for dynamic challenge...")
246 "client-deny %s %s \"CRV1\" \"CRV1:R,E:%s:%s:%s\"" % (
249 self
._b
64encode
(username
),
250 self
._b
64encode
(password
),
251 self
._escape
(CHALLENGETEXT
),
255 def _client_auth_successful(self
, cid
, kid
):
257 Sends a positive authentication response
259 log
.debug("Client Authentication Successful (cid=%s, kid=%s)" % (cid
, kid
))
262 "client-auth-nt %s %s" % (cid
, kid
),
267 return base64
.b64encode(s
.encode()).decode()
271 return base64
.b64decode(s
.encode()).decode()
275 return s
.replace(" ", "\ ")
277 def _find_connection(self
, common_name
):
278 with
open(OPENVPN_CONFIG
, "r") as f
:
279 for row
in csv
.reader(f
, dialect
="unix"):
280 # Skip empty rows or rows that are too short
281 if not row
or len(row
) < 5:
284 # Skip disabled connections
285 if not row
[1] == "on":
288 # Skip any net-2-net connections
289 if not row
[4] == "host":
292 # Skip if common name does not match
293 if not row
[3] == common_name
:
299 "common_name" : row
[3],
305 "totp_protocol" : row
[43],
306 "totp_status" : row
[44],
307 "totp_secret" : row
[45],
315 def _check_totp_token(self
, token
, secret
):
317 ["oathtool", "--totp", "-w", "3", "%s" % secret
],
321 # Catch any errors if we could not run the command
323 log
.error("Could not run oathtool: %s" % p
.stderr
)
327 # Reading returned tokens looking for a match
328 for line
in p
.stdout
.split(b
"\n"):
329 # Skip empty/last line(s)
333 # Decode bytes into string
336 # Return True if a token matches
344 if __name__
== "__main__":
345 parser
= argparse
.ArgumentParser(description
="OpenVPN Authenticator")
348 parser
.add_argument("--daemon", "-d", action
="store_true",
349 help="Launch as daemon in background")
350 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
353 parser
.add_argument("--socket", default
="/var/run/openvpn.sock",
354 metavar
="PATH", help="Path to OpenVPN Management Socket")
356 # Parse command line arguments
357 args
= parser
.parse_args()
360 loglevel
= logging
.WARN
363 if args
.verbose
== 1:
364 loglevel
= logging
.INFO
365 elif args
.verbose
>= 2:
366 loglevel
= logging
.DEBUG
368 # Create an authenticator
369 authenticator
= OpenVPNAuthenticator(args
.socket
)
371 with daemon
.DaemonContext(
372 detach_process
=args
.daemon
,
373 stderr
=None if args
.daemon
else sys
.stderr
,
375 signal
.SIGINT
: authenticator
.terminate
,
376 signal
.SIGTERM
: authenticator
.terminate
,
379 setup_logging(daemon
=args
.daemon
, loglevel
=loglevel
)