Add ud-lock
[mirror/userdir-ldap.git] / ud-lock
1 #!/usr/bin/python
2
3 # Copyright (c) 2010 Peter Palfrader <peter@palfrader.org>
4
5 # This script, non-interactively, sets a great many accounts to
6 # 'retiring', locking their password, removing keys, setting shadow
7 # information to expired and setting accountstatus appropriatly.
8
9
10 #   This program is free software; you can redistribute it and/or modify
11 #   it under the terms of the GNU General Public License as published by
12 #   the Free Software Foundation; either version 2 of the License, or
13 #   (at your option) any later version.
14 #
15 #   This program is distributed in the hope that it will be useful,
16 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
17 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 #   GNU General Public License for more details.
19 #
20 #   You should have received a copy of the GNU General Public License
21 #   along with this program; if not, write to the Free Software
22 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 import sys
25 import optparse
26 import os
27 import pwd
28 import time
29 from userdir_ldap import *;
30
31 dry_run = False
32
33 def connect(user):
34     l = connectLDAP()
35     binddn = "uid=%s,%s"%(user, BaseDn)
36     bindpw = None
37     if 'LDAP_PASSWORD' in os.environ:
38         bindpw = os.environ['LDAP_PASSWORD']
39     else:
40         bindpw = getpass.getpass(user + "'s password: ")
41
42     try:
43        l.simple_bind_s(binddn, bindpw)
44     except ldap.LDAPError, e:
45        sys.stderr.write("LDAP error: %s\n"%(e.args[0]['desc']))
46        sys.exit(1)
47     return l
48
49
50 class Account:
51     def __init__(self, user):
52         searchresult = lc.search_s(BaseDn,ldap.SCOPE_SUBTREE, 'uid=%s'%(user))
53         if len(searchresult) < 1:
54             sys.stderr.write("No such user: %s\n"%(user))
55             return
56         elif len(searchresult) > 1:
57             sys.stderr.write("More than one hit when getting %s\n"%(user))
58             return
59
60         self.dn, self.attributes = searchresult[0]
61
62
63     def has_mail(self):
64         if 'mailDisableMessage' in self.attributes:
65             return False
66         return True
67
68     # not locked locked,  just reset to something invalid like {crypt}*SSLRESET* is still active
69     def pw_active(self):
70         if self.attributes['userPassword'][0] == '{crypt}*LK*':
71             return False
72         return True
73
74     # not expired
75     def shadow_active(self):
76         if 'shadowExpire' in self.attributes and \
77             int(self.attributes['shadowExpire'][0]) < (time.time() / 3600 / 24):
78             return False
79         return True
80
81     def numkeys(self):
82         if 'keyFingerPrint' in self.attributes:
83             return len(self.attributes['keyFingerPrint'])
84         return 0
85
86     def account_status(self):
87         if 'accountStatus' in self.attributes:
88             return self.attributes['accountStatus'][0]
89         return 'active'
90
91
92     def verbose_status(self):
93         status = []
94         status.append('mail: %s'  %(['disabled', 'active'][ self.has_mail() ]))
95         status.append('pw: %s'    %(['locked', 'active'][ self.pw_active() ]))
96         status.append('shadow: %s'%(['expired', 'active'][ self.shadow_active() ]))
97         status.append('keys: %d'  %( self.numkeys() ))
98         status.append('status: %s'%( self.account_status() ))
99
100         return '(%s)'%(', '.join(status))
101
102     def get_dn(self):
103         return self.dn
104
105 def do_one_user(lc, user, ticket):
106     u = Account(user)
107     if not u.account_status() == 'active':
108         sys.stderr.write('%s: Account is not active, skipping.  (details: %s)\n'%(user, u.verbose_status()))
109         return
110
111     print '%s: Setting to retiring:'%(user)
112     set = {}
113     set['userPassword'] = '{crypt}*LK*'
114     set['shadowLastChange'] = str(int(time.time()/24/60/60))
115     set['shadowExpire'] = '1'
116     set['accountStatus'] = 'retiring %s'%(time.strftime('%Y-%m-%d'))
117     if not ticket is None:
118         set['accountComment'] = "RT#%s"%(ticket)
119
120     rec = []
121     for key in set:
122         print '  %s: %s'%(key, set[key])
123         rec.append( (ldap.MOD_REPLACE, key, set[key]) )
124
125     print '  %s: deleting keyFingerPrint'%(user)
126     rec.append( (ldap.MOD_DELETE, 'keyFingerPrint', None) )
127
128
129     if dry_run:
130         print '(not committing)'
131     else:
132         lc.modify_s(u.get_dn(), rec)
133         print '%s: done.'%(user)
134
135     sys.stdout.flush()
136
137
138 parser = optparse.OptionParser()
139 parser.set_usage("%prog [--admin-user <binduser>] [--no-do] <account> [<account> ...]")
140 parser.add_option("-a", "--admin-user", dest="admin", metavar="admin",
141   help="User to bind as.",
142   default=pwd.getpwuid(os.getuid()).pw_name)
143 parser.add_option("-n", "--no-do", action="store_true",
144   help="Do not actually change anything.")
145 parser.add_option("-r", "--rt-ticket", dest="ticket", metavar="ticket#",
146   help="Ticket number for accountComment.")
147
148 (options, args) = parser.parse_args()
149
150 if options.no_do:
151     dry_run = True
152
153 lc = connect(options.admin)
154 for user in args:
155     do_one_user(lc, user, options.ticket)
156
157
158 # vim:set et:
159 # vim:set ts=4:
160 # vim:set shiftwidth=4: