reset-my-password.py 4.84 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#!/usr/bin/python

import ldap
import ldap.filter
import string
import smtplib
import sys
import os
import ldap.modlist as modlist
from email.MIMEText import MIMEText

LDAP_GROUP_BASE='cn=groups,cn=accounts,dc=gnome,dc=org'
LDAP_USER_BASE='cn=users,cn=accounts,dc=gnome,dc=org'


file = open('/home/admin/secret/freeipa','r')
lines = file.readlines()

for line in lines:
        if line.find("ldap_password") > -1:
                dirty_password = line.split()
                ldap_password = str(dirty_password)

24
                sanitize_file=["ldap_password", "\"", ":"]
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
                for i in range(len(sanitize_file)):
                        ldap_password = ldap_password.replace(sanitize_file[i],"")
file.close()


try:
    l = ldap.open('localhost')
    l.simple_bind("cn=Directory Manager", ldap_password)
except ldap.LDAPError, e:
        print >>sys.stderr, e
        sys.exit(1)


def _parse_members_from_group(group):

    filter = ldap.filter.filter_format('(&(objectClass=posixgroup)(cn=%s))', (group, ))
    results = l.search_s(LDAP_GROUP_BASE, ldap.SCOPE_SUBTREE, filter, ('memberUid', ))

    members = set()
    for entry in results:
        id = entry[0]
        attr = entry[1]

        members.update(attr['memberUid'])


    return members


def _get_attributes_from_ldap(userid, attr):
    filter = ldap.filter.filter_format('(uid=%s)', (userid, ))
    results = l.search_s(LDAP_USER_BASE, ldap.SCOPE_SUBTREE, filter, ('uid', attr, ))

    for entry in results:
        username = entry[1]['uid']
        attribute = entry[1][attr]

        userslist = dict(zip(username, attribute))

        return userslist


def gen_passwd(length=10, chars=string.letters + string.digits):
    urandom = open("/dev/urandom")
    # ensure even distribution of randomly selected characters
    m = 255 - 255 % len(chars)

    buf = ''
    pos = 0
    pwd = ''
    while len(pwd) < length:
        if pos == len(buf):
            buf = urandom.read(length * 2)
            pos = 0
        v = ord(buf[pos])
        pos += 1

        if v > m:
            continue
        pwd += chars[v % len(chars)]

    urandom.close()

    return pwd


def check_existing_password(userid):
    accountsteam =  _parse_members_from_group('accounts')
    sysadminteam =  _parse_members_from_group('sysadmin')

    if _get_attributes_from_ldap(userid, 'uid') == None:
       print 'The specified UID does not exist, please get in contact with the GNOME Accounts Team to know more'
       sys.exit(1)

    if userid in (accountsteam or sysadminteam):
       print 'You are not allowed to reset your password, please contact the GNOME Sysadmin Team to know why'
       sys.exit(1)

    try:
        userpassword = _get_attributes_from_ldap(userid, 'userPassword')
    except KeyError:
        add_new_password(userid)
    else:
        update_existing_password(userid)


def update_existing_password(userid):
    dn = 'uid=%s,%s' % (userid, LDAP_USER_BASE)

    getattr_userpassword = _get_attributes_from_ldap(userid, 'userPassword')
    getattr_name = _get_attributes_from_ldap(userid, 'cn')
    getattr_mail = _get_attributes_from_ldap(userid, 'mail')
    old_password = getattr_userpassword[userid]

    password = {'userPassword': '%s' % (old_password)}
    newpassword = {'userPassword': gen_passwd(length=20)}

    ldif = modlist.modifyModlist(password, newpassword)
    l.modify_s(dn, ldif)


    send_password_to_user(getattr_name[userid], getattr_mail[userid], newpassword['userPassword'])


def add_new_password(userid):
    dn = 'uid=%s,%s' % (userid, LDAP_USER_BASE)

    getattr_name = _get_attributes_from_ldap(userid, 'cn')
    getattr_mail = _get_attributes_from_ldap(userid, 'mail')

    nopassword = {'userPassword': ''}
    newpassword = {'userPassword': gen_passwd(length=20)}

    ldif = modlist.modifyModlist(nopassword, newpassword)
    l.modify_s(dn, ldif)


    send_password_to_user(getattr_name[userid], getattr_mail[userid], newpassword['userPassword'])


def send_password_to_user(name, email, password):
    form_letter = """
Hello %s, your password has been reset successfully and is available here:

Andrea Veri's avatar
Andrea Veri committed
149
%s
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

Please login at https://account.gnome.org and update your password as soon as possible!

With cordiality,

the GNOME Accounts Team""" % (name, password)

    try:
        msg = MIMEText(form_letter)
        msg['Subject'] = "Your GNOME password has been reset"
        msg['From']    = "noreply@gnome.org"
        msg['To']      = "%s" % (email)
        msg['Reply-To']  = "accounts@gnome.org"
        server = smtplib.SMTP("localhost")
        server.sendmail(msg['From'], msg['To'], msg.as_string())
        server.quit()
        print "Successfully sent your password to the registered email address being %s" % (email)
    except smtplib.SMTPException:
        print "ERROR: I wasn't able to send the email correctly, please check /var/log/maillog!"

Andrea Veri's avatar
Andrea Veri committed
170
my_userid = os.getenv('SUDO_USER')
171
check_existing_password(my_userid)