account_backend.py 8.03 KB
Newer Older
Zack Wong's avatar
Zack Wong committed
1
2
3
4

import logging

from django.conf import settings
Zack Wong's avatar
Zack Wong committed
5
6
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.utils.translation import gettext_lazy as _
Zack Wong's avatar
Zack Wong committed
7

Zack Wong's avatar
Zack Wong committed
8
import re
9
import socket
10
11
12
13
from ldap3 import Server, Connection, MODIFY_REPLACE,MODIFY_ADD
from ldap3.core.results import RESULT_SUCCESS
from ldap3.core.exceptions import *

14
15
16
17

import subprocess
from subprocess import CalledProcessError, TimeoutExpired

Zack Wong's avatar
Zack Wong committed
18
import memberdb.models
Zack Wong's avatar
Zack Wong committed
19
20
21
from datetime import date
from squarepay import dispense

Zack Wong's avatar
Zack Wong committed
22
23
24
import shutil
import os

Zack Wong's avatar
Zack Wong committed
25

Zack Wong's avatar
Zack Wong committed
26
27
log = logging.getLogger('ldap')

28
# load config
Zack Wong's avatar
Zack Wong committed
29
ldap_uri = getattr(settings, 'AUTH_LDAP_SERVER_URI')
30
31
ldap_user_dn = getattr(settings, 'LDAP_USER_SEARCH_DN')
ldap_base_dn = getattr(settings, 'LDAP_BASE_DN')
32
33
ldap_bind_dn = getattr(settings, 'LDAP_BIND_DN')
ldap_bind_secret = getattr(settings, 'LDAP_BIND_SECRET')
root's avatar
root committed
34
make_home_cmd = ["sudo", "/services/uccportal/src/memberdb/root_actions.py"] 
Zack Wong's avatar
Zack Wong committed
35
36
37
make_mail_cmd = 'ssh -i %s [email protected] "/usr/local/mailman/bin/add_members" -r- ucc-announce <<< %[email protected]'
make_mail_key = './mooneye.key'

Zack Wong's avatar
Zack Wong committed
38

39
maxuid_dn = "CN=uccdomayne,CN=ypservers,CN=ypServ30,CN=RpcServices,CN=System,"+ldap_base_dn
Zack Wong's avatar
Zack Wong committed
40
41

#initalise ldap instace
42
43
44
45
46
47
_ldap_inst = Connection(
	Server(ldap_uri),
	client_strategy='SYNC',
	user=ldap_bind_dn,
	password=ldap_bind_secret,
	raise_exceptions=True,
48

49
	)
Zack Wong's avatar
Zack Wong committed
50

51
# get the ldap instance and bind if required
Zack Wong's avatar
Zack Wong committed
52
def get_ldap_instance():
53
54
55
56
57
58
	if not _ldap_inst.bound:
		try:
			_ldap_inst.bind()
		except LDAPInvalidCredentialsResult:
			log.error("LDAP: Invalid bind credentials")
			raise
Zack Wong's avatar
Zack Wong committed
59
60
	return _ldap_inst

61
def get_ldap_attrs(dn, filter, limit, attrs):
Zack Wong's avatar
Zack Wong committed
62
	ld = get_ldap_instance()
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
	ld.search(dn, filter, size_limit=limit, attributes=attrs)
	result = ld.result
	# fetch matched objects on success
	if (result['result'] == RESULT_SUCCESS):
		entries = ld.entries
	else:
		# otherwise raise an exception
		raise LDAPOperationResult(
			result=result['result'],
			description=result['description'],
			dn=result['dn'],
			message=result['message'],
			response_type=result['type'])

	if len(entries) == 0:
		raise LDAPNoSuchObjectResult()

	return entries;

def get_user_attrs(username, attrs):
	# find the user
	filter = "(cn=" + username + ')'

	result = get_ldap_attrs(ldap_user_dn, filter, 1, attrs)

	return result[0];

def get_maxuid():
	ld = get_ldap_instance()
	filter = "(cn=*)"
	attrs = ['msSFU30MaxUidNumber']
	result = get_ldap_attrs(maxuid_dn, filter, 1, attrs)
96

97
	return result[0]
Zack Wong's avatar
Zack Wong committed
98

Zack Wong's avatar
Zack Wong committed
99
100
101
102
def get_account_lock_status(username):
	ld = get_ldap_instance()
	try:
		result = get_user_attrs(username, ['userAccountControl'])
103
104
105
106
	# user does not exist
	except LDAPNoSuchObjectResult:
		return None
	# return UAC flag 0x002 ('ACCOUNT_DISABLE')
Zack Wong's avatar
Zack Wong committed
107
108
	return bool(result[1]['userAccountControl'] & 0x002)

109
110
def validate_username(value : str):
	# note: slug validator ensures that username only contains [a-z0-9_-]
Zack Wong's avatar
Zack Wong committed
111
	# usernames can't begin with a numeric
112
	if not value[0].isalpha():
113
		raise ValidationError(_('Username must begin with a letter'))
114
	# ensure username is lowercase
115
116
	if not value.islower():
		raise ValidationError(_('Username cannot contain uppercase characters'))
117
	# check if the user exists, this test should catch *most* cases
118
	if subprocess.call(["id", value], stderr=subprocess.DEVNULL) == 0:
119
120
121
122
123
124
125
126
127
		raise ValidationError(_('Username already taken (passwd)'))

	# usernames cannot conflict with hostnames
	try:
		socket.gethostbyname(value)
		raise ValidationError(
			_('Username already taken (CNAME)')
		)
	except socket.gaierror:
128
		pass
129
130
	# lookup user in ldap, required because not all users are mapped to *nix users
	try:
131
132
133
134
135
		get_user_attrs(value, None)
	except LDAPNoSuchObjectResult:
		pass
	else:
		raise ValidationError(_('Username already taken (AD)'))
136

Zack Wong's avatar
Zack Wong committed
137

Zack Wong's avatar
Zack Wong committed
138
139
140
141
142
143
144
145
146
147
148
# locks the specified User Account by performing the following actions:
# 1. set UAC ACCOUNTDISABLE flag (0x002) via ldap
# 2. set user shell to `/etc/locked20xx` via ldap
# 3. do `dispense user type disabled <username> <reason>`
def lock_account(username):
	# TODO: error handling
	ld = get_ldap_instance()
	today = date.today()
	try:
		# fetch current uac
		result = get_user_attrs(username, ['userAccountControl'])
149
150
151
152
153
154
155

		dn = result.entry_dn
		uac = result['userAccountControl'] | 0x002 # set ACCOUNTDISABLE
		actions = {
			"userAccountControl": [(MODIFY_REPLACE,[uac])],
			"userShell": [(MODIFY_REPLACE,["/etc/locked"+str(today.year)])]
			}
Zack Wong's avatar
Zack Wong committed
156
157
		# write record
		ld.modify(dn, actions)
158
159
	except LDAPOperationResult:
		raise
Zack Wong's avatar
Zack Wong committed
160
161
	finally:
		ld.unbind()
162

Zack Wong's avatar
Zack Wong committed
163
164
165
166
167
168
169
170
171
172
	reason = "account locked by uccportal on %s" % str(today)
	dispense.set_dispense_flag(username, 'disabled', reason)

def unlock_account(username):
	# TODO: error handling
	ld = get_ldap_instance()
	today = date.today()
	try:
		# fetch current uac
		result = get_user_attrs(username, ['userAccountControl'])
173

Zack Wong's avatar
Zack Wong committed
174
175
		dn = result[0]
		uac = result[1]['userAccountControl'] & ~0x002 # clear ACCOUNTDISABLE
176
177
178
179
		actions = {
			"userAccountControl": [(MODIFY_REPLACE,[uac])],
			"userShell": [(MODIFY_REPLACE,["/bin/zsh"])]
			}
Zack Wong's avatar
Zack Wong committed
180
181
		# write record
		ld.modify(dn, actions)
182
183
	except LDAPOperationResult:
		raise
Zack Wong's avatar
Zack Wong committed
184
185
186
187
188
	finally:
		ld.unbind()
	reason = "account unlocked by uccportal on %s" % str(today)
	dispense.set_dispense_flag(username, '!disabled', reason)

Zack Wong's avatar
Zack Wong committed
189
# Account creation
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def create_ad_user(form_data, member):
	log.info("I: creating new account for %s (%s)")

	# store user details
	# TODO add overides
	username=form_data['username']
	displayName = member.first_name + ' ' + member.last_name
	dn = 'CN=' + username +','+ ldap_user_dn

	# enclose password in quotes and convert to utf16 as required:
	# https://msdn.microsoft.com/en-us/library/cc223248.aspx
	quotedpass = '"'+ form_data['password']+'"'
	utf16pass = quotedpass.encode('utf-16-le')

	# generate uid
	try:
		result = get_maxuid()
	except:
		log.error("LDAP: cannot find base uid")
Zack Wong's avatar
Zack Wong committed
209
210
		raise

211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

	maxuid = int(result.msSFU30MaxUidNumber.value)

	# gets all uids >= maxuid
	# this is done so that we don't encounter the 1000 item limit to ad queries
	entries = get_ldap_attrs(ldap_user_dn,"(uidNumber>=%s)" % maxuid, 100, ['uidNumber'])

	# generate a new uid
	uids = []
	for user in entries:
		uids.append(int(user.uidNumber.value))

	uids.sort()
	# use max uid if it is free
	if uids[0] != maxuid:
		newuid = str(maxuid)
	else:
		prev = uids[0]
		for uid in uids:
			if uid - prev > 1:
				newuid = uid + 1
				break;
			prev = uid
		#increment uid
		newuid = str(prev + 1)

	# sanity check: make sure the uid is free
	if subprocess.call(["id", newuid], stderr=subprocess.DEVNULL) == 0:
		log.error("LDAP: uid already taken")
Zack Wong's avatar
Zack Wong committed
240
		raise ValueError
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264

	# create the new user struct
	objclass = ['top','posixAccount','person','organizationalPerson','user']
	attrs = {
		'cn' : username,
		'sAMAccountName' : username,
		'givenName' : member.first_name,
		'sn': member.last_name,
		'displayName': displayName,
		'userAccountControl' : '512',
		'unixHomeDirectory' : "/home/ucc/" + username,
		'loginShell' : '/bin/zsh',
		'gidNumber' : '20021',
		'uidNumber' : newuid,
		'gecos' : displayName,
		'mail' : username + '@ucc.gu.uwa.edu.au',
		'unicodePwd': utf16pass
	}

	# commit the new user to AD
	ld = get_ldap_instance()
	result = ld.add(dn, objclass, attrs)
	if not result:
		log.error("LDAP: user add failed")
Zack Wong's avatar
Zack Wong committed
265
		raise LDAPOperationsErrorResult
266
267
268
269

	# set maxuid
	result = ld.modify(maxuid_dn, {'msSFU30MaxUidNumber': [(MODIFY_REPLACE, newuid)]})
	if not result:
Zack Wong's avatar
Zack Wong committed
270
		log.warning("LDAP: user created but msSFU30MaxUidNumber not updated")
Zack Wong's avatar
Zack Wong committed
271

272
273
	ld.unbind();
	return True;
Zack Wong's avatar
Zack Wong committed
274

Zack Wong's avatar
Zack Wong committed
275
def make_home(formdata, member):
Zack Wong's avatar
Zack Wong committed
276
277
	user = member.username
	mail = formdata['email_address'] if formdata['forward'] else ""
Zack Wong's avatar
Zack Wong committed
278
279
280
281
282
	result = subprocess.call(make_home_cmd + [user, mail])
	if result == 0:
		return True
	else:
		raise CalledProcessError
Zack Wong's avatar
Zack Wong committed
283

284
def subscribe_to_list(member):
Zack Wong's avatar
Zack Wong committed
285
286
287
288
289
	result = os.system(make_mail_cmd % (make_mail_key, member.username))
	if result == 0:
		return True
	else:
		raise CalledProcessError
Zack Wong's avatar
Zack Wong committed
290

291
292
def set_pin(member, pin):
	return
Zack Wong's avatar
Zack Wong committed
293
294
295