Exemplo n.º 1
0
def registration():
    form = SignupForm()
    if form.validate_on_submit():
        client = ClientMeta(os.environ.get("LDAP_SERVER"), verify_ssl=False)
        client.login(os.environ.get("LDAP_ADMIN"),
                     os.environ.get("LDAP_PASSWORD"))
        full_name = f"{form.first_name.data} {form.last_name.data}"
        client.user_add(a_uid=form.username.data,
                        o_givenname=form.first_name.data,
                        o_sn=form.last_name.data,
                        o_cn=full_name,
                        o_userpassword=form.password.data,
                        o_preferredlanguage="EN")
        if form.invite_code.data == INVITE_CODE_ENV:
            client.group_add_member(USER_GROUP_ENV, o_user=form.username.data)
        elif form.invite_code.data == ELEVATED_INVITE_CODE_ENV:
            client.group_add_member(ELEVATED_USER_GROUP_ENV,
                                    o_user=form.username.data)

        if os.environ.get("SLACK_ENABLED") == "true":
            try:
                data = {
                    "email": form.email.data,
                    "token": os.environ.get("SLACK_API_TOKEN"),
                    "set_active": "true"
                }
                requests.post(
                    f"https://{os.environ.get('SLACK_WORKSPACE')}.slack.com/api/users.admin.invite",
                    data=data)
            except Exception as e:
                logger.error(
                    f"Challenges sending slack invite to {form.email.data} - {e}"
                )
        return redirect("/success")
    return render_template("register.html", form=form)
def ipa_connect(ipa_user, ipa_password, ipa_hostname):
    """
        Connect and login to FreeIPA system with a secured
        SSL connection.
    """
    client = ClientMeta(ipa_hostname, verify_ssl='/etc/ipa/ca.crt')
    client.login(ipa_user, ipa_password)
    return client
Exemplo n.º 3
0
def client(domain, login, password):
    try:
        Log.info("Подключение к ldap")
        client = ClientMeta(domain, verify_ssl=False)
        client.login(login, password)
        return client
    except FreeipaExceptions.FreeIPAError as e:
        Log.exception(e)
        sys.exit(1)
Exemplo n.º 4
0
 def clean_email(self):
     email = self.data.get("email")
     if email.endswith("@cnstrong.cn"):
         user = email.split("@")[0]
         client = ClientMeta(host=IPA_AUTH_SERVER, verify_ssl=False)
         client.login(IPA_AUTH_USER, IPA_AUTH_PWD)
         account = client.user_find(user)
         if account:
             print("account is:", account)
         else:
             print("No user: "******"no right mail:", email)
         raise forms.ValidationError('非公司邮箱')
     return email
class Ipa:

    def __init__(self, logger, domain, login, password):
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        self.logger = logger
        try:
            self.client = ClientMeta(domain, verify_ssl=False)
            self.client.login(login, password)
        except FreeipaExceptions.FreeIPAError as e:
            self.logger.log.exception(e)

    def check_group_exist(self, group):
        result = False
        group = self.client.group_find(o_cn=group)
        if group['count'] > 0:
            result = True
        return result
Exemplo n.º 6
0
def reset_ldap_pwd(user):
    user = user
    client = ClientMeta(host=IPA_AUTH_SERVER, verify_ssl=False)
    client.login(IPA_AUTH_USER, IPA_AUTH_PWD)
    password = client.user_mod(user, o_random=True)['result']['randompassword']
    if password:
        days = timedelta(days=1)
        expire_time = datetime.now() + days
        str_expire = expire_time.strftime('%Y%m%d%H%M%S') + 'Z'
        change_expire = client.user_mod(user,
                                        o_krbpasswordexpiration=str_expire)
        if change_expire:
            return password
        else:
            print("Change krbpasswordexpiration failed.")
            return 0
    else:
        print("Set password failed.")
        return 0
Exemplo n.º 7
0
def change_ldap_pwd(user, current_password, password):
    user = user
    client = ClientMeta(host=IPA_AUTH_SERVER, verify_ssl=False)
    client.login(IPA_AUTH_USER, IPA_AUTH_PWD)
    change_pwd = client.passwd(a_principal=user,
                               a_current_password=current_password,
                               a_password=password)
    if change_pwd:
        days = timedelta(days=180)
        expire_time = datetime.now() + days
        str_expire = expire_time.strftime('%Y%m%d%H%M%S') + 'Z'
        change_expire = client.user_mod(user,
                                        o_krbpasswordexpiration=str_expire)
        if change_expire:
            return 1
        else:
            raise exception_class(message, code)
            # return 0
    else:
        print("Change password failed.")
        return 0
Exemplo n.º 8
0
 def connect(self):
     client = ClientMeta(self.ipaInstance, verify_ssl=False)
     client.login(self.username, self.password)
     return client
Exemplo n.º 9
0
from python_freeipa import ClientMeta

CommonTestPassword = '******'

client = ClientMeta('ipa.demo1.freeipa.org')
client.login('admin', CommonTestPassword)

Userlist = ['alice', 'bob', 'dave', 'frank']

# Reset, Add Users, and Set Manager
for user in UserList:
    client.user_del(user, o_continue=True)
    client.user_add(user, user.capitalize(), 'TestUser', user.capitalize() + ' TestUser', o_preferredlanguage='EN', o_userpassword=CommonTestPassword)
    alice_mgr = client.user_add_manager(user, o_user="******")
    client.group_add_member("employees", o_user=user)

# Create New Groups
client.group_add('team1')
client.group_add('team2')
# Add to Existing Group

team1=['alice','bob','manager']
team2=['dave','frank','manager']

for user in Team1:
    client.group_add_member("team1", o_user=user)

for user in Team2:
    client.group_add_member("team2", o_user=user)

Exemplo n.º 10
0
def client(domain, login, password):
    client = ClientMeta(domain, verify_ssl=False)
    client.login(login, password)
    return client
Exemplo n.º 11
0
import os

from flask_wtf import FlaskForm
from python_freeipa import ClientMeta
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Email, ValidationError

INVITE_CODE_ENV = os.environ.get("INVITE_CODE", "")
ELEVATED_INVITE_CODE_ENV = os.environ.get("ELEVATED_INVITE_CODE", "")

client = ClientMeta(os.environ.get("LDAP_SERVER"), verify_ssl=False)
client.login(os.environ.get("LDAP_ADMIN"), os.environ.get("LDAP_PASSWORD"))


class SignupForm(FlaskForm):
    email = StringField("Email", validators=[DataRequired(), Email()])
    password = PasswordField("Password", validators=[DataRequired()])
    first_name = StringField("First name", validators=[DataRequired()])
    username = StringField("Username", validators=[DataRequired()])
    last_name = StringField("Last name", validators=[DataRequired()])
    if INVITE_CODE_ENV:
        invite_code = StringField("Invite code", validators=[DataRequired()])

    def validate_username(self, username):
        user = client.user_find(username.data)
        if user["count"] is not 0:
            raise ValidationError(
                f"Username {username.data} already exists, please use another."
            )

    def validate_invite_code(self, invite_code):
Exemplo n.º 12
0
def main():
    # get rid of unverified HTTPS connection warnings
    urllib3.disable_warnings()
    # get login credentials as global vars
    client = ClientMeta("ipaserver.example.com", verify_ssl=False)
    client.login("api-user","somepwd")
        

    def listToString(s): # convert list to string
        # initialize an empty string
        str1 = ""
        # traverse in the string
        for ele in s:
            str1 += ele + ","
        
        return str1


    def getUsers(client): # Get all IDM users
        # use the freeipa module user_find method and store in userlist list
        userlist = client.user_find()
        # get sub category result
        userresult = userlist.get("result")
        # Create empty list
        listOfUsers = []
        # pad the empty list with a header line
        listOfUsers.append(['USER NAME', 'FULL NAME', 'GROUPS'])
        # loop through each line in list
        for row in userresult:
            # declare empty list where we inserts 3 elements of all user elements
            user = []
            user.append(row.get('uid')[0])
            user.append(row.get('cn')[0])
            user.append(listToString(row.get('memberof_group')))
            # add user list to bigger list of all users
            listOfUsers.append(user)
        
        return listOfUsers


    def getUserGroups(client): # Get all user groups
        #grouplist = client.group_find(posix=True)
        grouplist = client.group_find()
        groupresult = grouplist.get("result")
        # Create empty list
        listOfGroups = []
        listOfGroups.append(['GROUP NAME', 'GROUP MEMBERSHIP', 'SUDORULE', 'HBACRULE'])
        for row in groupresult:
            group = []
            group.append(row.get('cn')[0])
            group.append(row.get('memberof_group'))
        #    group.append(row.get('memberofindirect_sudorule'))
            group.append(row.get('memberof_sudorule'))
            group.append(row.get('memberof_hbacrule'))
            listOfGroups.append(group)
        
        return listOfGroups

        
    def getHostGroups(client): # Get all host groups
        hostgrouplist = client.hostgroup_find()
        hostgroupresult = hostgrouplist.get("result")
        # Create empty list
        listOfHostGroups = []
        listOfHostGroups.append(['HOSTGROUP NAME', 'HBACRULE MEMBERSHIP', 'HOSTS'])
        for row in hostgroupresult:
            hostgroup = []
            hostgroup.append(row.get('cn')[0])
            hostgroup.append(row.get('memberof_hbacrule'))
            hostgroup.append(row.get('member_host'))
            listOfHostGroups.append(hostgroup)
        
        return listOfHostGroups


    def getHbacRules(client): # get all HBAC rules
        hbacrulelist = client.hbacrule_find()
        hbacruleresult = hbacrulelist.get("result")
        # Create empty list
        listOfHbacRules = []
        listOfHbacRules.append(['HBACRULE NAME', 'MEMBER USER', 'TYPE OF ACCESS', 'MEMBER GROUP'])
        for row in hbacruleresult:
            hbacrule = []
            hbacrule.append(row.get('cn')[0])
            hbacrule.append(row.get('memberuser_user'))
            hbacrule.append(row.get('accessruletype'))
            hbacrule.append(row.get('memberuser_group'))
            listOfHbacRules.append(hbacrule)

        return listOfHbacRules


    def getSudoRules(client): # get all Sudo rules
        sudorulelist = client.sudorule_find()
        sudoruleresult = sudorulelist.get("result")
        # Create empty list
        listOfSudoRules = []
        listOfSudoRules.append(['SUDORULE NAME', 'RUN AS', 'MEMBER HOST', 'MEMBER USERGROUP', 'MEMBER HOSTGROUP', 'CMD CATEGORY'])
        for row in sudoruleresult:
            sudorule = []
            sudorule.append(row.get('cn')[0])
            sudorule.append(row.get('ipasudorunasextuser'))
            sudorule.append(row.get('memberhost'))
            sudorule.append(row.get('memberuser_group'))
            sudorule.append(row.get('memberhost_hostgroup'))
            sudorule.append(row.get('cmdcategory'))
            listOfSudoRules.append(sudorule)
        
        return listOfSudoRules


    def getSudoCmds(client): # get all Sudo commands
        sudocmdlist = client.sudocmd_find()
        sudocmdresult = sudocmdlist.get("result")
        # Create empty list
        listOfSudoCmds = []
        listOfSudoCmds.append(['SUDOCMD NAME', 'DESCRIPTION'])

        for row in sudocmdresult:
            sudocmd = []
            sudocmd.append(row.get('sudocmd')[0])
            sudocmd.append(row.get('description'))
            listOfSudoCmds.append(sudocmd)

        return listOfSudoCmds


    def getSudoCmdGroups(client): # get all Sudo command groups
        sudocmdgrouplist = client.sudocmdgroup_find()
        sudocmdresult = sudocmdgrouplist.get("result")
        # Create empty list
        listOfSudoCmdGroups = []
        listOfSudoCmdGroups.append(['SUDOCMDGROUP NAME', 'SUDO CMD'])
        for row in sudocmdresult:
            sudocmdgroup = []
            sudocmdgroup.append(row.get('cn'))
            sudocmdgroup.append(row.get('member_sudocmd'))
            listOfSudoCmdGroups.append(sudocmdgroup)

        return listOfSudoCmdGroups


    def dataToExcel(listOfUsers, listOfGroups, listOfHostGroups, listOfHbacRules, listOfSudoRules, listOfSudoCmds, listOfSudoCmdGroups):
        # create empty workbook
        wb = Workbook()
        # change name of worksheet
        ws1 = wb.active
        ws1.title = "users_sheet"
        print("users")
        # loop through list
        for row in listOfUsers:
            try: # check for nestled lists
                if(isinstance(row, str)): # add row if string
                    ws1.append(row)
                elif(isinstance(row, list)): # convert nestled lists to strings
                    row = listToString(row)
                    ws1.append(row)

            except Exception as e: 
                print(e)
                print(row)

        print("usergroup")
        ws2 = wb.create_sheet("usergroup_sheet", 0)
        ws2 = wb.active
        for row in listOfGroups:
            try:
                ws2.append(row)
            except Exception as e: 
                print(e)
                print(row)

        print("hostgroups")    
        ws3 = wb.create_sheet("hostgroups_sheet", 0)
        ws3 = wb.active
        for row in listOfHostGroups:
            try:
                ws3.append(row)
            except Exception as e: 
                print(e)
                print(row)

        print("HBACrules")
        ws4 = wb.create_sheet("hbacrules_sheet", 0)
        ws4 = wb.active
        for row in listOfHbacRules:
            try:
                ws4.append(row)
            except Exception as e: 
                print(e)
                print(row)

        print("sudorules")
        ws5 = wb.create_sheet("sudorules_sheet", 0)
        ws5 = wb.active
        for row in listOfSudoRules:
            try:
                ws5.append(row)
            except Exception as e: 
                print(e)
                print(row)

        print("sudocmds")
        ws6 = wb.create_sheet("sudocmds_sheet", 0)
        ws6 = wb.active
        for row in listOfSudoCmds:
            try:
                ws6.append(row)
            except Exception as e:
                print(e)
                print(row)

        print("sudocmdgroups")
        ws7 = wb.create_sheet("sudocmdgroups_sheet", 0)
        ws7 = wb.active
        for row in listOfSudoCmdGroups:
            try:
                ws7.append(row)
            except Exception as e: 
                print(e)
                print(row)

        print("saving file...")
        wb.save(filename = 'userAccessReview.xlsx')


    # Method Loader
    listOfUsers = getUsers(client)
    listOfGroups = getUserGroups(client)
    listOfHostGroups = getHostGroups(client)
    listOfHbacRules = getHbacRules(client)
    listOfSudoRules = getSudoRules(client)
    listOfSudoCmds = getSudoCmds(client)
    listOfSudoCmdGroups = getSudoCmdGroups(client)
    dataToExcel(listOfUsers, listOfGroups, listOfHostGroups, listOfHbacRules, listOfSudoRules, listOfSudoCmds, listOfSudoCmdGroups)
def main(argv):
    """
  Main function for starting methods
  """
    user = None
    servers = None
    extuser1 = None
    extuser2 = None
    removeRole = False

    # get login credentials
    client = ClientMeta("segotl6204.idm.it.hclgss.com")
    client.login("admin", "idmhcl123")

    if sys.argv[1] == '--remove':
        removeRole = True

    if not removeRole:
        try:
            opts, args = getopt.getopt(argv, "hu:s:", ["user="******"servers="])
            for opt, arg in opts:

                if opt == '-h':
                    print(
                        'emergencyAccess.py -u username -s server1.example.com,server2.example.com'
                    )
                    sys.exit(3)
                elif opt in ("-u", "--user"):
                    user = arg
                    # testing regular expressions to identify AD account
                    # search for @sds.hclgss.com or similar
                    if re.search("\@[a-z]{3,9}\.[a-z]{3,9}\.[a-z]{3,9}", user):
                        extuser1 = user
                        # search for SDS\ or similar with raw to include backslash
                    elif re.search(r"[A-Z]{3,5}\\", user):
                        extuser2 = user

                    #if extuser1: print "extuser1: " + extuser1
                    #if extuser2: print "extuser2: " + extuser2

                    if extuser1:  # split on @, return left side
                        tmpfriendlyUserName = extuser1.split("@", 1)
                        friendlyUserName = tmpfriendlyUserName[0]
                        extuser = extuser1
                    elif extuser2:  # split on \, return right side
                        tmpfriendlyUserName = extuser2.split("\\", 1)
                        friendlyUserName = tmpfriendlyUserName[1]
                        extuser = extuser2

                elif opt in ("-s", "--servers"):
                    servers = arg
                    if ',' in servers:
                        # split string to tuple, separate on comma 2 handle multiple servers
                        res = tuple(servers.split(","))
                        servers = res

        except getopt.GetoptError:
            print(
                'emergencyAccess.py -u username -s server1.example.com,server2.example.com'
            )
            sys.exit(2)

    # get date, format 20210101
    now = datetime.now()  # current date and time
    todaysdate = now.strftime("%Y%m%d")

    def groupadd(friendlyUserName):  # Add user group
        posixgroup_cn = "unix_emerg_" + friendlyUserName + "_" + todaysdate + "_user"
        externalgroup_cn = "unix_emerg_" + friendlyUserName + "_" + todaysdate + "_user_ad"
        client.group_add(posixgroup_cn)
        client.group_add(externalgroup_cn, external=True)
        client.group_add_member(posixgroup_cn, group=externalgroup_cn)
        client.group_add_member(externalgroup_cn, ipaexternalmember=extuser)
        return posixgroup_cn

    def sudoruleadd(user, servers, posixgroup_cn):  # add sudorule
        # define common name
        emerg_sudoruleadd_cn = "unix_emerg_" + friendlyUserName + "_" + todaysdate + "_high_rule"
        # show rule if it exists (skip procedure not yet created)
        #    print client.sudorule_show(emerg_sudoruleadd_cn)
        # add rule
        client.sudorule_add(emerg_sudoruleadd_cn,
                            "temporary emergency root access for " + user,
                            o_cmdcategory='all',
                            o_ipasudorunasusercategory='all')
        # add host(s) to rule
        client.sudorule_add_host(emerg_sudoruleadd_cn, host=servers)
        # add local IDM user to rule
        if not extuser:
            client.sudorule_add_user(emerg_sudoruleadd_cn, user=user)
        # Or add user group for AD user
        elif extuser:
            client.sudorule_add_user(emerg_sudoruleadd_cn, group=posixgroup_cn)

    def hbacruleadd(user, servers, posixgroup_cn):  # add HBAC rule
        # define common name
        emerg_hbacruleadd_cn = "allow_unix_emerg_" + friendlyUserName + "_" + todaysdate + "_high_hbac"
        # define description
        hbac_descr = "temporary access for user ${user} to server(s): ${servers}"
        # add rule
        client.hbacrule_add(emerg_hbacruleadd_cn)
        # add hosts to rule
        client.hbacrule_add_host(emerg_hbacruleadd_cn,
                                 host=servers,
                                 all='True')
        # add local IDM user to rule
        if not extuser:
            client.hbacrule_add_user(emerg_hbacruleadd_cn,
                                     user=user,
                                     all='True')
            # Or add group for AD user
        elif extuser:
            client.hbacrule_add_user(emerg_hbacruleadd_cn,
                                     group=posixgroup_cn,
                                     all='True')

    def removeold():  # Remove all emergency groups/rules older than 3 days
        all_emerg_groups = client.group_find("emerg")
        all_emerg_sudorules = client.sudorule_find("emerg")
        all_emerg_hbacrules = client.hbacrule_find("emerg")
        right_now_3_days_ago = datetime.today() - timedelta(days=3)

        try:
            # if groups found called emerg something
            if all_emerg_groups:
                #print all_emerg_groups['result'][1]['cn']
                # loop through the group names
                for usergroup in all_emerg_groups['result'][1]['cn']:
                    # extract date from group name
                    getTheDate = dparser.parse(usergroup, fuzzy=True)
                    #print getTheDate
                    # is date older than 3 days: then action
                    if getTheDate < right_now_3_days_ago:
                        print "user group is older than 3 days"
                        # add group name to list
                        groupRemovalList.append(usergroup)
                        # loop through list and delete group
                        for group in groupRemovalList:
                            client.group_del(group)
                print

            if all_emerg_sudorules:  # if sudorules found called emerg something
                #print all_emerg_sudorules['result'][0]['cn']
                # loop through the sudorule names
                for sudorule in all_emerg_sudorules['result'][0]['cn']:
                    # extract date from sudorule name
                    getTheDate = dparser.parse(sudorule, fuzzy=True)
                    #print getTheDate
                    # is date older than 3 days: then action
                    if getTheDate < right_now_3_days_ago:
                        print "sudo rule is older than 3 days"
                        # add sudorule name to list
                        sudoruleRemovalList.append(sudorule)
                        # loop through list and delete sudorule
                        for sudorule in sudoruleRemovalList:
                            client.sudorule_del(sudorule)
                print

            if all_emerg_hbacrules:  # if hbacrules found called emerg something
                #print all_emerg_hbacrules['result'][0]['cn']
                # loop through the hbacrule names
                for hbacrule in all_emerg_hbacrules['result'][0]['cn']:
                    # extract date from hbacrule name
                    getTheDate = dparser.parse(hbacrule, fuzzy=True)
                    #print getTheDate
                    # is date older than 3 days: then action
                    if getTheDate < right_now_3_days_ago:
                        print "hbac rule is older than 3 days"
                        # add hbacrule name to list
                        hbacruleRemovalList.append(hbacrule)
                        # loop through list and delete hbacrule
                        for hbacrule in hbacruleRemovalList:
                            client.hbacrule_del(hbacrule)
                print
        except NameError:  # if one or more was not found
            print "some or no group/rules were not found..."

    # Call methods
    if not removeRole:
        if friendlyUserName:
            posixgroup_cn = groupadd(friendlyUserName)
        sudoruleadd(user, servers, posixgroup_cn)
        hbacruleadd(user, servers, posixgroup_cn)
    elif removeRole:
        removeold()
Exemplo n.º 14
0
# https://python-freeipa.readthedocs.io/en/latest/
#
# How-to install python-freeipa and csv:
# pip install python-freeipa python-csv
#
#
# Import the freeipa library
from python_freeipa import ClientMeta
# pretty print to parse to human-readable output
import pprint
# prepare outfile for excel import
import csv

# get login credentials
client = ClientMeta("idmreplica1.idm.example.com")
client.login("api-reader", "somepassword")


# Function to convert list to string
def listToString(s):
    # initialize an empty string
    str1 = ""
    # traverse in the string
    for ele in s:
        str1 += ele + ","
    # return string
    return str1


# Get all IDM users
# use the freeipa module user_find method and store in userlist list