]>
git.ipfire.org Git - people/pmueller/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
)
102 self
.sock
= socket
.socket(socket
.AF_UNIX
, socket
.SOCK_STREAM
)
103 self
.sock
.connect(self
.socket_path
)
105 log
.info("OpenVPN Authenticator started")
109 line
= self
._read
_line
()
111 if line
.startswith(">CLIENT"):
112 self
._client
_event
(line
)
114 # Terminate the daemon when it loses its connection to the OpenVPN daemon
115 except ConnectionResetError
as e
:
116 log
.error("Connection to OpenVPN has been lost: %s" % e
)
118 log
.info("OpenVPN Authenticator terminated")
120 def terminate(self
, *args
):
124 def _client_event(self
, line
):
125 # Strip away "CLIENT:"
126 client
, delim
, line
= line
.partition(":")
128 # Extract the event & split any arguments
129 event
, delim
, arguments
= line
.partition(",")
130 arguments
= arguments
.split(",")
134 if event
== "CONNECT":
135 environ
= self
._read
_env
(environ
)
136 self
._client
_connect
(*arguments
, environ
=environ
)
137 elif event
== "DISCONNECT":
138 environ
= self
._read
_env
(environ
)
139 self
._client
_disconnect
(*arguments
, environ
=environ
)
140 elif event
== "REAUTH":
141 environ
= self
._read
_env
(environ
)
142 self
._client
_reauth
(*arguments
, environ
=environ
)
143 elif event
== "ESTABLISHED":
144 environ
= self
._read
_env
(environ
)
146 log
.debug("Unhandled event: %s" % event
)
148 def _read_env(self
, environ
):
151 line
= self
._read
_line
()
153 if not line
.startswith(">CLIENT:ENV,"):
154 raise RuntimeError("Unexpected environment line: %s" % line
)
164 key
, delim
, value
= line
.partition("=")
169 def _client_connect(self
, cid
, kid
, environ
={}):
170 log
.debug("Received client connect (cid=%s, kid=%s)" % (cid
, kid
))
171 for key
in sorted(environ
):
172 log
.debug(" %s : %s" % (key
, environ
[key
]))
175 common_name
= environ
.get("common_name")
177 # Find connection details
178 conn
= self
._find
_connection
(common_name
)
180 log
.warning("Could not find connection '%s'" % common_name
)
183 log
.debug("Found connection:")
185 log
.debug(" %s : %s" % (key
, conn
[key
]))
187 # Perform no further checks if TOTP is disabled for this client
188 if not conn
.get("totp_status") == "on":
189 return self
._client
_auth
_successful
(cid
, kid
)
191 # Fetch username & password
192 username
= environ
.get("username")
193 password
= environ
.get("password")
195 # Client sent the special password TOTP to start challenge authentication
196 if password
== "TOTP":
197 return self
._client
_auth
_challenge
(cid
, kid
,
198 username
=common_name
, password
="TOTP")
200 elif password
.startswith("CRV1:"):
201 log
.debug("Received dynamic challenge response %s" % password
)
204 (command
, flags
, username
, password
, token
) = password
.split(":", 5)
207 username
= self
._b
64decode
(username
)
209 # Check if username matches common name
210 if username
== common_name
:
211 # Check if TOTP token matches
212 if self
._check
_totp
_token
(token
, conn
.get("totp_secret")):
213 return self
._client
_auth
_successful
(cid
, kid
)
215 # Restart authentication
216 self
._client
_auth
_challenge
(cid
, kid
,
217 username
=common_name
, password
="TOTP")
219 def _client_disconnect(self
, cid
, environ
={}):
221 Handles CLIENT:DISCONNECT events
225 def _client_reauth(self
, cid
, kid
, environ
={}):
227 Handles CLIENT:REAUTH events
230 self
._client
_auth
_successful
(cid
, kid
)
232 def _client_auth_challenge(self
, cid
, kid
, username
, password
):
234 Initiates a dynamic challenge authentication with the client
236 log
.debug("Sending request for dynamic challenge...")
239 "client-deny %s %s \"CRV1\" \"CRV1:R,E:%s:%s:%s\"" % (
242 self
._b
64encode
(username
),
243 self
._b
64encode
(password
),
244 self
._escape
(CHALLENGETEXT
),
248 def _client_auth_successful(self
, cid
, kid
):
250 Sends a positive authentication response
252 log
.debug("Client Authentication Successful (cid=%s, kid=%s)" % (cid
, kid
))
255 "client-auth-nt %s %s" % (cid
, kid
),
260 return base64
.b64encode(s
.encode()).decode()
264 return base64
.b64decode(s
.encode()).decode()
268 return s
.replace(" ", "\ ")
270 def _find_connection(self
, common_name
):
271 with
open(OPENVPN_CONFIG
, "r") as f
:
272 for row
in csv
.reader(f
, dialect
="unix"):
273 # Skip empty rows or rows that are too short
274 if not row
or len(row
) < 5:
277 # Skip disabled connections
278 if not row
[1] == "on":
281 # Skip any net-2-net connections
282 if not row
[4] == "host":
285 # Skip if common name does not match
286 if not row
[3] == common_name
:
292 "common_name" : row
[3],
298 "totp_protocol" : row
[43],
299 "totp_status" : row
[44],
300 "totp_secret" : row
[45],
308 def _check_totp_token(self
, token
, secret
):
310 ["oathtool", "--totp", "-w", "3", "%s" % secret
],
314 # Catch any errors if we could not run the command
316 log
.error("Could not run oathtool: %s" % p
.stderr
)
320 # Reading returned tokens looking for a match
321 for line
in p
.stdout
.split(b
"\n"):
322 # Skip empty/last line(s)
326 # Decode bytes into string
329 # Return True if a token matches
337 if __name__
== "__main__":
338 parser
= argparse
.ArgumentParser(description
="OpenVPN Authenticator")
341 parser
.add_argument("--daemon", "-d", action
="store_true",
342 help="Launch as daemon in background")
343 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
346 parser
.add_argument("--socket", default
="/var/run/openvpn.sock",
347 metavar
="PATH", help="Path to OpenVPN Management Socket")
349 # Parse command line arguments
350 args
= parser
.parse_args()
353 loglevel
= logging
.WARN
356 if args
.verbose
== 1:
357 loglevel
= logging
.INFO
358 elif args
.verbose
>= 2:
359 loglevel
= logging
.DEBUG
361 # Create an authenticator
362 authenticator
= OpenVPNAuthenticator(args
.socket
)
364 with daemon
.DaemonContext(
365 detach_process
=args
.daemon
,
366 stderr
=None if args
.daemon
else sys
.stderr
,
368 signal
.SIGINT
: authenticator
.terminate
,
369 signal
.SIGTERM
: authenticator
.terminate
,
372 setup_logging(daemon
=args
.daemon
, loglevel
=loglevel
)