#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# UCS@school RADIUS 802.1X
#  NTLM-Authentication program
#
# Copyright (C) 2012-2017 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of the software contained in this package
# as well as the source package itself are made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this package provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use the software under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

import optparse
import os
import sys
import time
import univention.admin.filter
import univention.config_registry
import univention.pyMsChapV2 as pyMsChapV2
import univention.uldap

userToGroup = {}  # { "user_lowercase": ["group1", "group2", ], }
groupInfo = {}  # { "group1": (23, True, ), }
log_target = None


def debug(msg):
	if log_target:
		log_target.write('%s [%s] %s\n' % (time.strftime('%Y-%m-%d %H:%M:%S'), os.getpid(), msg))


def loadInfo():
	configRegistry = univention.config_registry.ConfigRegistry()
	configRegistry.load()
	for key in configRegistry:
		if key.startswith('proxy/filter/usergroup/'):
			group = key[len('proxy/filter/usergroup/'):]
			users = configRegistry[key].split(',')
			for user in users:
				userToGroup.setdefault(user.lower(), []).append(group)
		elif key.startswith('proxy/filter/groupdefault/'):
			group = key[len('proxy/filter/groupdefault/'):]
			rule = configRegistry[key]
			priority = 0
			try:
				priority = int(configRegistry.get('proxy/filter/setting/%s/priority' % (rule, ), ''))
			except ValueError:
				pass
			wlanEnabled = configRegistry.is_true('proxy/filter/setting/%s/wlan' % (rule, ))
			if wlanEnabled is not None:
				groupInfo[group] = (priority, wlanEnabled, )


SAMBA_ACCOUNT_FLAG_DISABLED = 'D'
SAMBA_ACCOUNT_FLAG_LOCKED = 'L'
DISALLOWED_SAMBA_ACCOUNT_FLAGS = frozenset((SAMBA_ACCOUNT_FLAG_DISABLED, SAMBA_ACCOUNT_FLAG_LOCKED, ))


def getNTPasswordHash(username, stationId):
	'''
	stationId may be None if it was not supplied to the program
	username may contain the direct username (e.g. 'anton123') or
	a hostname (e.g. 'win-02$') or
	a kerberos principal without realm (e.g. 'host/win-02.example.com'):
	'''
	debug('getNTPasswordHash: username=%r  stationId=%r' % (username, stationId.encode('hex')))
	if username.startswith('host/'):
		# seems to be a kerberos principal
		username = username.split('/', 1)[1]
		if '.' in username:
			username = username.split('.', 1)[0]
		username += '$'
	debug('getNTPasswordHash: username2=%r  stationId=%r' % (username, stationId.encode('hex')))

	groups = userToGroup.get(username.lower())
	if groups is None:
		debug('getNTPasswordHash: user not found in any relevant group - access denied')
		return None
	matchingGroups = [[group] + list(groupInfo[group]) for group in groups if group in groupInfo]
	if not matchingGroups:
		debug('getNTPasswordHash: user not found in any WLAN enabled group - access denied')
		debug('getNTPasswordHash: user groups=%r' % (groups,))
		debug('getNTPasswordHash: WLAN enabled groups=%r' % (groupInfo.keys(),))
		return None
	maxPriorityGroup = max(matchingGroups, key=lambda x: x[1])
	debug('getNTPasswordHash: maxPriorityGroup=%r' % (maxPriorityGroup,))
	if not any(True for (grpname, priority, wlanEnabled, ) in matchingGroups if priority == maxPriorityGroup[1] and wlanEnabled):
		debug('getNTPasswordHash: WLAN is not enabled in group with highest priority - access denied (maxPriorityGroup=%r)' % (maxPriorityGroup,))
		grpstatus = ['%s(prio=%s, wlan=%s)' % (grpname, priority, wlanEnabled) for (grpname, priority, wlanEnabled) in matchingGroups]
		debug('getNTPasswordHash: %s' % (' '.join(grpstatus),))
		return None
	# user is authorized to use the W-LAN, retrieve NT-password-hash from LDAP and return it
	result = ldapConnection.search(filter=str(univention.admin.filter.expression('uid', username)), attr=['sambaNTPassword', 'sambaAcctFlags'])
	if not result:
		debug('getNTPasswordHash: could not fetch sambaNTPassword for user %r - access denied' % (username,))
		return None
	sambaAccountFlags = frozenset(result[0][1]['sambaAcctFlags'][0])
	if sambaAccountFlags & DISALLOWED_SAMBA_ACCOUNT_FLAGS:
		debug('getNTPasswordHash: user is disabled via sambaAcctFlags - access denied')
		return None
	debug('getNTPasswordHash: returning sambaNTPassword hash')
	return result[0][1]['sambaNTPassword'][0].decode('hex')


def main():
	global log_target
	parser = optparse.OptionParser()
	parser.add_option('--request-nt-key', action='store_true', dest='requestNtKey')
	parser.add_option('--username', dest='Username')
	parser.add_option('--challenge', dest='Challenge')
	parser.add_option('--nt-response', dest='Response')
	parser.add_option('--station-id', dest='stationId')
	parser.add_option('--logfile', dest='logfile')
	(options, args, ) = parser.parse_args()
	if not options.requestNtKey:
		print 'Missing required parameter --request-nt-key!'
		return 1
	if not options.Username:
		print 'Missing required parameter --username!'
		return 1
	if not options.Challenge:
		print 'Missing required parameter --challenge!'
		return 1
	if not options.Response:
		print 'Missing required parameter --nt-response!'
		return 1
	if options.logfile:
		log_target = open(options.logfile, 'a')
	debug('main: username = %r' % (options.Username,))
	if not options.stationId:
		stationId = ''
	else:
		# safely decode station id (fails with exception on mis-formatted id, thus returning 1)
		stationId = options.stationId.lower()
		# remove all non-hex characters, so different formats may be decoded
		# e.g. 11:22:33:44:55:66 or 1122.3344.5566 or 11-22-33-44-55-66 or ...
		stationId = ''.join([c for c in stationId if c in '0123456789abcdef'])
		debug('main: reformatted stationId = %r' % (stationId,))
		stationId = stationId.decode('hex')
	debug('main: Challenge = %r' % (options.Challenge,))
	debug('main: Response = %r' % (options.Response,))
	options.Challenge = options.Challenge.decode('hex')
	options.Response = options.Response.decode('hex')
	PasswordHash = getNTPasswordHash(options.Username, stationId)
	if PasswordHash and pyMsChapV2.ChallengeResponse(options.Challenge, PasswordHash) == options.Response:
		debug('main: successfully authenticated')
		print 'NT_KEY: %s' % (pyMsChapV2.HashNtPasswordHash(PasswordHash).encode('hex').upper(), )
		return 0
	else:
		debug('main: authentication failed')
		print 'Logon failure (0xc000006d)'
		return 1


if __name__ == "__main__":
	ldapConnection = univention.uldap.getMachineConnection(ldap_master=False)
	loadInfo()
	sys.exit(main())
