]>
git.ipfire.org Git - people/teissler/ipfire-2.x.git/blob - config/ovpn/openvpn-authenticator
25d96ca348866b0cd0233e290100936257626b67
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(",")
143 line
= self
._read
_line
()
145 if not line
.startswith(">CLIENT:ENV,"):
146 raise RuntimeError("Unexpected environment line: %s" % line
)
156 key
, delim
, value
= line
.partition("=")
159 if event
== "CONNECT":
160 self
._client
_connect
(*arguments
, environ
=environ
)
161 elif event
== "DISCONNECT":
162 self
._client
_disconnect
(*arguments
, environ
=environ
)
163 elif event
== "REAUTH":
164 self
._client
_reauth
(*arguments
, environ
=environ
)
166 log
.debug("Unhandled event: %s" % event
)
168 def _client_connect(self
, cid
, kid
, environ
={}):
169 log
.debug("Received client connect (cid=%s, kid=%s)" % (cid
, kid
))
170 for key
in sorted(environ
):
171 log
.debug(" %s : %s" % (key
, environ
[key
]))
174 common_name
= environ
.get("common_name")
176 # Find connection details
177 conn
= self
._find
_connection
(common_name
)
179 log
.warning("Could not find connection '%s'" % common_name
)
182 log
.debug("Found connection:")
184 log
.debug(" %s : %s" % (key
, conn
[key
]))
186 # Perform no further checks if TOTP is disabled for this client
187 if not conn
.get("totp_status") == "on":
188 return self
._client
_auth
_successful
(cid
, kid
)
190 # Fetch username & password
191 username
= environ
.get("username")
192 password
= environ
.get("password")
194 # Client sent the special password TOTP to start challenge authentication
195 if password
== "TOTP":
196 return self
._client
_auth
_challenge
(cid
, kid
,
197 username
=common_name
, password
="TOTP")
199 elif password
.startswith("CRV1:"):
200 log
.debug("Received dynamic challenge response %s" % password
)
203 (command
, flags
, username
, password
, token
) = password
.split(":", 5)
206 username
= self
._b
64decode
(username
)
208 # Check if username matches common name
209 if username
== common_name
:
210 # Check if TOTP token matches
211 if self
._check
_totp
_token
(token
, conn
.get("totp_secret")):
212 return self
._client
_auth
_successful
(cid
, kid
)
214 # Restart authentication
215 self
._client
_auth
_challenge
(cid
, kid
,
216 username
=common_name
, password
="TOTP")
218 def _client_disconnect(self
, cid
, environ
={}):
220 Handles CLIENT:DISCONNECT events
224 def _client_reauth(self
, cid
, kid
, environ
={}):
226 Handles CLIENT:REAUTH events
229 self
._client
_auth
_successful
(cid
, kid
)
231 def _client_auth_challenge(self
, cid
, kid
, username
, password
):
233 Initiates a dynamic challenge authentication with the client
235 log
.debug("Sending request for dynamic challenge...")
238 "client-deny %s %s \"CRV1\" \"CRV1:R,E:%s:%s:%s\"" % (
241 self
._b
64encode
(username
),
242 self
._b
64encode
(password
),
243 self
._escape
(CHALLENGETEXT
),
247 def _client_auth_successful(self
, cid
, kid
):
249 Sends a positive authentication response
251 log
.debug("Client Authentication Successful (cid=%s, kid=%s)" % (cid
, kid
))
254 "client-auth-nt %s %s" % (cid
, kid
),
259 return base64
.b64encode(s
.encode()).decode()
263 return base64
.b64decode(s
.encode()).decode()
267 return s
.replace(" ", "\ ")
269 def _find_connection(self
, common_name
):
270 with
open(OPENVPN_CONFIG
, "r") as f
:
271 for row
in csv
.reader(f
, dialect
="unix"):
276 # Skip disabled connections
277 if not row
[1] == "on":
280 # Skip any net-2-net connections
281 if not row
[4] == "host":
284 # Skip if common name does not match
285 if not row
[3] == common_name
:
291 # General connection data
292 conn
['name'] = row
[2]
293 conn
['common_name'] = row
[3]
296 conn
['totp_protocol'] = row
[43]
297 conn
['totp_status'] = row
[44]
298 conn
['totp_secret'] = row
[45]
303 def _check_totp_token(self
, token
, secret
):
305 ["oathtool", "--totp", "-w", "3", "%s" % secret
],
309 # Catch any errors if we could not run the command
311 log
.error("Could not run oathtool: %s" % p
.stderr
)
315 # Reading returned tokens looking for a match
316 for line
in p
.stdout
.split(b
"\n"):
317 # Skip empty/last line(s)
321 # Decode bytes into string
324 # Return True if a token matches
332 if __name__
== "__main__":
333 parser
= argparse
.ArgumentParser(description
="OpenVPN Authenticator")
336 parser
.add_argument("--daemon", "-d", action
="store_true",
337 help="Launch as daemon in background")
338 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
341 parser
.add_argument("--socket", default
="/var/run/openvpn.sock",
342 metavar
="PATH", help="Path to OpenVPN Management Socket")
344 # Parse command line arguments
345 args
= parser
.parse_args()
348 loglevel
= logging
.WARN
351 if args
.verbose
== 1:
352 loglevel
= logging
.INFO
353 elif args
.verbose
>= 2:
354 loglevel
= logging
.DEBUG
356 # Create an authenticator
357 authenticator
= OpenVPNAuthenticator(args
.socket
)
359 with daemon
.DaemonContext(
360 detach_process
=args
.daemon
,
361 stderr
=None if args
.daemon
else sys
.stderr
,
363 signal
.SIGINT
: authenticator
.terminate
,
364 signal
.SIGTERM
: authenticator
.terminate
,
367 setup_logging(daemon
=args
.daemon
, loglevel
=loglevel
)