Esempio n. 1
0
def main():
    uidnum = sys.argv[1]
    print("#Generating rules for user ID %s" % uidnum)

    # declare a new iptables ruleset
    ipt = libnfldap.IPTables()

    # insert sane default at the top of the ruleset
    ipt.insertSaneDefaults()

    # declare a new ipset ruleset
    ips = libnfldap.IPset()

    # find a user in ldap
    ldap = libnfldap.LDAP(LDAP_URL, LDAP_BIND_DN, LDAP_BIND_PASSWD)
    userdn, userid = ldap.getUserByNumber('o=com,dc=mozilla', uidnum)

    # create a custom chain and sets for the user
    ipt.newFilterChain(userid)
    r = "-A FORWARD -m owner --uid-owner " + uidnum + " -m state --state NEW -j " + userid
    ipt.appendFilterRule(r)
    ips.newHashNet(userid)

    # find groups of an ldap user
    acls = ldap.getACLs('ou=groups,dc=mozilla',
                        "(&(member=" + userdn + ")(cn=vpn_*))")

    # iterate through the ACLs
    print("#====== ACL details ======")
    for group, dests in acls.iteritems():
        for dest, desc in dests.iteritems():
            print("%s has access to %s aka '%s'" % (userid, dest, desc))
            if libnfldap.is_cidr(dest):
                ips.addCIDRToHashNet(userid, dest)
            else:
                ipt.appendFilterRule("-A " + userid + " -d " + dest +
                                     " -j ACCEPT")

    # set a default drop policy at the end of the ruleset
    ipt.appendDefaultDrop()

    # template and print the iptables rules
    print("#====== IPTABLES RULES ======\n")
    print("%s\n\n" % ipt.template())

    # template and print the ipset rules
    print("#====== IPSET RULES ======\n")
    print("%s" % ips.template())
Esempio n. 2
0
def main():
    ipt = libnfldap.IPTables()
    ldap = libnfldap.LDAP(LDAP_URL, LDAP_BIND_DN, LDAP_BIND_PASSWD)
    ipset = libnfldap.IPset()

    # find all vpn groups and create chains
    acls = ldap.getACLs('ou=groups,dc=mozilla', "(cn=vpn_*)")
    for group, dests in acls.iteritems():
        ipt.newFilterChain(group)
        for dest, desc in dests.iteritems():
            if libnfldap.is_cidr(dest):
                ipt.acceptIP(group, dest, desc)
            else:
                ip = dest.split(":", 1)[0]
                ports = dest.split(":", 1)[1]
                if len(ports) > 0:
                    ipt.acceptIPPortProto(group, ip, ports, "tcp", desc)
                    ipt.acceptIPPortProto(group, ip, ports, "udp", desc)
                else:
                    ipt.acceptIP(group, ip, desc)

    # get a list of all LDAP users
    query = '(&(objectClass=mozComPerson)(objectClass=posixAccount))'
    res = ldap.query('dc=mozilla', query, ['uid', 'uidNumber'])
    users = {}

    # get users from the system, the find the corresponding ldap record
    for p in pwd.getpwall():
        if p.pw_uid > 500:
            # iterate over the ldap records
            for dn, attr in res:
                uid = attr['uid'][0]
                uidNumber = attr['uidNumber'][0]
                if uidNumber == str(p.pw_uid) and uid == p.pw_name:
                    # store the user
                    users[uidNumber] = {'dn': dn, 'uid': uid}

    ## iterate over the users and create the rules
    for uidNumber, attr in users.iteritems():
        dn = attr['dn']
        uid = attr['uid']
        # create a custom chain for the user
        ipt.newFilterChain(uid)
        # add rules to forward this user's packets to the custom chain
        r = "-A OUTPUT -m owner --uid-owner " + uidNumber + " -m state --state NEW -j " + uid
        ipt.appendFilterRule(r)

        # find groups memberships of the user
        acls = ldap.getACLs('ou=groups,dc=mozilla',
                            "(&(member=" + dn + ")(cn=vpn_*))")

        # iterate through the ACLs and send the user to the group chains
        for group, dests in acls.iteritems():
            ipt.appendFilterRule("-A " + uid + " -j " + group)

        # add a DROP at the end of the user rules
        ipt.appendFilterRule("-A " + uid + " -j DROP")

    # set a default drop policy at the end of the ruleset
    ipt.insertSaneDefaults()
    #ipt.appendDefaultDrop()

    # template and print the iptables rules
    tmpfd, tmppath = mkstemp()
    f = open(tmppath, 'w')
    f.write(ipt.template())
    f.close()
    os.close(tmpfd)
    print("IPTables rules written in %s" % tmppath)
Esempio n. 3
0
def main():
    ipt = libnfldap.IPTables()
    ldap = libnfldap.LDAP(config.LDAP_URL, config.LDAP_BIND_DN,
                          config.LDAP_BIND_PASSWD)
    ipset = libnfldap.IPset()

    gen_start_time = time.time()

    # find all vpn groups and create chains
    acls = ldap.getACLs('ou=groups,dc=mozilla', "(cn=vpn_*)")
    for group, dests in acls.iteritems():
        ipt.newFilterChain(group)
        for dest, desc in dests.iteritems():
            if libnfldap.is_cidr(dest):
                ipt.acceptIP(group, dest, desc)
            else:
                ip = dest.split(":", 1)[0]
                ports = dest.split(":", 1)[1]
                if len(ports) > 0:
                    ipt.acceptIPPortProto(group, ip, ports, "tcp", desc)
                    ipt.acceptIPPortProto(group, ip, ports, "udp", desc)
                else:
                    ipt.acceptIP(group, ip, desc)

    # get a list of all LDAP users
    query = '(&(objectClass=mozComPerson)(objectClass=posixAccount))'
    res = ldap.query('dc=mozilla', query, ['uid', 'uidNumber'])
    users = {}

    # get users from the system, the find the corresponding ldap record
    for p in pwd.getpwall():
        if p.pw_uid > 500:
            # iterate over the ldap records
            for dn, attr in res:
                uid = attr['uid'][0]
                uidNumber = attr['uidNumber'][0]
                if uidNumber == str(p.pw_uid) and uid == p.pw_name:
                    # store the user
                    users[uidNumber] = {'dn': dn, 'uid': uid}

    ## iterate over the users and create the rules
    for uidNumber, attr in users.iteritems():
        dn = attr['dn']
        uid = attr['uid']
        # create a custom chain for the user
        ipt.newFilterChain(uid)
        # add rules to forward this user's packets to the custom chain
        r = "-A OUTPUT -m owner --uid-owner " + uidNumber + " -m state --state NEW -j " + uid
        ipt.appendFilterRule(r)

        # find groups memberships of the user
        acls = ldap.getACLs('ou=groups,dc=mozilla',
                            "(&(member=" + dn + ")(cn=vpn_*))")

        # iterate through the ACLs and send the user to the group chains
        for group, dests in acls.iteritems():
            ipt.appendFilterRule("-A " + uid + " -j " + group)

        # add a DROP at the end of the user rules
        ipt.appendFilterRule("-A " + uid + " -j DROP")

    # set a default drop policy at the end of the ruleset
    ipt.insertSaneDefaults()
    ipt.appendFilterRule(
        "-A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT")
    ipt.appendFilterRule(
        "-A INPUT -p tcp --dport 5666 -m state --state NEW -j ACCEPT")
    ipt.appendFilterRule(
        "-A OUTPUT -m owner --uid-owner 0 -m state --state NEW -j ACCEPT")
    ipt.appendDefaultDrop()

    # template and print the iptables rules
    tmpfd, tmppath = mkstemp()
    f = open(tmppath, 'w')
    f.write(ipt.template())
    f.close()
    os.close(tmpfd)

    gen_time = time.time() - gen_start_time
    load_start_time = time.time()
    # run iptables-restore
    command = "/sbin/iptables-restore %s" % (tmppath)
    status = os.system(command)
    load_time = time.time() - load_start_time
    if status == -1:
        mozmsg.send(summary="failed to load iptables rules from" + tmppath,
                    severity='ERROR',
                    details={
                        'generation_time': gen_time,
                        'loading_time': load_time
                    })

    else:
        mozmsg.send(summary="iptables rules reloaded successfully.",
                    details={
                        'generation_time': gen_time,
                        'loading_time': load_time
                    })
    os.remove(tmppath)
Esempio n. 4
0
def main():
	# declare a new iptables ruleset
	ipt = libnfldap.IPTables()

	# insert sane default at the top of the ruleset
	ipt.insertSaneDefaults()

	# declare a new ipset ruleset
	ipset = libnfldap.IPset()

	# find all LDAP users
	ldap = libnfldap.LDAP(LDAP_URL, LDAP_BIND_DN, LDAP_BIND_PASSWD)
	users = {}
	# the query lists all users by default. If you want to narrow down the search to
	# a single user, call the script with a single argument, such as:
	#	$ python example_allusers.py '(uid=jvehent)'
	customf = ''
	if len(sys.argv) > 1:
		customf = sys.argv[1]
	query = '(&(objectClass=mozComPerson)(objectClass=posixAccount)' + customf + ')'
	res = ldap.query('dc=mozilla', query, ['cn', 'uid', 'uidNumber'])

	# iterate over the users and create the rules
	for dn, attr in res:
		cn = attr['cn'][0],
		uid = attr['uid'][0]
		uidNumber = attr['uidNumber'][0]

		# create a custom chain and sets for the user
		ipt.newFilterChain(uid)
		ipset.newHashNet(uid)
		# add rules to forward this user's packets to the custom chain and the ipset
		r = "-A FORWARD -m owner --uid-owner " +  uidNumber + " -m state --state NEW -j " + uid
		ipt.appendFilterRule(r)
		#r = "-A " + uid + " -m set --match-set '" + uid + "' dst -m state --state NEW -j ACCEPT"
		#ipt.appendFilterRule(r)

		# find ACLs of a given user
		acls = ldap.getACLs('ou=groups,dc=mozilla',
							"(&(member="+dn+")(cn=vpn_*))")

		# iterate through the ACLs and create iptables or ipset rules
		for group,dests in acls.iteritems():
			for dest,desc in dests.iteritems():
				# if the destination is a CIDR (IP or subnet), add it to ipset
				if libnfldap.is_cidr(dest):
					#ipset.addCIDRToHashNet(uid, dest)
					ipt.acceptIP(uid, dest, desc)
				else:
					# if the destination has ports, add one rule per port
					ip = dest.split(":", 1)[0]
					ports = dest.split(":", 1)[1]
					if len(ports) > 0:
						ipt.acceptIPPortProto(uid, ip, ports, "tcp", desc)
						ipt.acceptIPPortProto(uid, ip, ports, "udp", desc)
					else:
						ipt.acceptIP(uid, ip, desc)

		# add a DROP at the end of the user rules
		ipt.appendFilterRule("-A " + uid + " -j DROP")

	# set a default drop policy at the end of the ruleset
	#ipt.appendDefaultDrop()

	# template and print the iptables rules
	tmpfd, tmppath = mkstemp()
	f = open(tmppath, 'w')
	f.write(ipt.template())
	f.close()
	os.close(tmpfd)
	print("IPTables rules written in %s" % tmppath)

	# template and print the ipset rules
	tmpfd, tmppath = mkstemp()
	f = open(tmppath, 'w')
	f.write(ipset.template())
	f.close()
	os.close(tmpfd)
	print("IPSet rules written in %s" % tmppath)
Esempio n. 5
0
def main():
    cfg_path = [
        'get_user_routes.conf', '/usr/local/etc/get_user_routes.conf',
        '/etc/get_user_routes.conf'
    ]
    config = None

    for cfg in cfg_path:
        if os.path.isfile(cfg):
            try:
                config = imp.load_source('config', cfg)
            except:
                pass

    if config == None:
        print("Failed to load config")
        sys.exit(1)

    try:
        username = sys.argv[1]
    except IndexError:
        print("Need one argument, email-username")
        sys.exit(1)

    # if the user is connecting from an office, we need to know, so that we can filter out local destinations
    try:
        if sys.argv[2] == "--office":
            from_office = 1
        else:
            from_office = 0
    except IndexError:
        from_office = 0

    # currently using libnfldap, since it has a function to get all the ACLs for a group
    ldap = libnfldap.LDAP(config.LDAP_URL, config.LDAP_BIND_DN,
                          config.LDAP_BIND_PASSWD)

    filterk = '(mail=' + username + ')'
    query = filterk
    res = ldap.query('dc=mozilla', query, ['mail'])
    dn = res[0][0]

    # find all vpn groups user is in and return IP attributes
    acls = ldap.getACLs('ou=groups,dc=mozilla',
                        "(&(member=" + dn + ")(cn=vpn_*))")
    ips = []
    for group, dests in acls.iteritems():
        for dest, desc in dests.iteritems():
            # strip off port information
            ip = dest.split(":")[0]
            # if address is already in cidr format, add it, else assume single host IP and add /32
            # this is in order to keep a consistent format for all addresses before we process
            if ip.find('/') != -1:
                ips.append(ip)
            else:
                ips.append(ip + '/32')

    #Now that we have a list of all possible addresses that a user may access, we need to check
    # if any aren't already covered by the default list of routes from the config.
    notfoundlist = []
    for address in ips:
        for route in config.ROUTES:
            if IPNetwork(address) in IPNetwork(route):
                break
        else:
            notfoundlist.append(address)

    # merge user-specific routes with routes from the config, only unique. Sorted for human readability
    all_routes = sorted(
        set(config.ROUTES + notfoundlist + config.OFFICE_ROUTES))

    # check that there are no overlapping routes, remove office routes if connecting from an office
    if from_office == 1:
        squashed_routes = remove_office_routes(squash_routes(all_routes),
                                               config.OFFICE_ROUTES)
    else:
        squashed_routes = squash_routes(all_routes)

    #Finally, we need to output all the routes in a nice list that bash will be able to iterate over
    for address in squashed_routes:
        ip, mask = cidr_to_netmask(address)
        # For one entry per line, remove the trailing comma
        print("{ip} {mask}").format(ip=ip, mask=mask)