Python library for interacting with LDAP
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

457 lines
18 KiB

import yaml
import sys
import plabsDNS
import TSIGKey
import exceptions
from argparse import ArgumentParser
def print_success(msg):
print(msg)
exit(0)
def print_error(msg):
print(msg)
exit(1)
def print_command_unknwon(command):
print("Unknown command: {}\n". format(command))
def print_usage():
print_error("""Usage: ./plabsdns MENU COMMAND
Available commands:
user User submenu
zone Zone submenu
server Server submenu""")
def main():
with open('./config.yml') as f:
config = yaml.load(f.read(), Loader=yaml.BaseLoader)
pass
args = sys.argv[1:]
if len(args) == 0:
print_usage()
if not args[0] in ('user', 'zone', 'server'):
print_command_unknwon(args[0])
print_usage()
plabs_dns = plabsDNS.PlabsDNS(config)
if args[0] == 'user':
def print_user_usage():
print_error("""Usage: ./plabsdns user COMMAND
Available commands:
add Adds dns attributes to a user
show Prints all plabsDNS relevant information
update Updates a user
delete Removes dns attributes from a user""")
if len(args) < 2:
print_user_usage()
intent = get_intent(args[1])
if not intent:
print_command_unknwon(args[1])
print_user_usage()
elif intent == 'show':
try:
user = plabs_dns.ldap_user_dns_lookup(args[2])
print_success('DN: {}\nTSIG key: {}'
.format(user[0], plabs_dns._get_ldap_attr(user, 'tsigKey')))
except exceptions.PlabsException as e:
print_error(e)
elif intent == 'add':
tsig = None
if len(args) < 3:
print_error("Usage: ./plabsdns user a[dd] USER [TSIG-KEY]")
elif len(args) > 3:
tsig = args[3]
try:
plabs_dns.verify_tsig_key(plabsDNS.KeyType.User, tsig)
except TSIGKey.UnknownAlgorithm:
print_error('Not a valid TSIG-KEY: Unknown Algorithm')
except exceptions.InvalidIdentifier:
print_error('Not a valid TSIG-KEY: Invalid identifier for user')
try:
result = plabs_dns.ldap_user_add_dns_attrs(args[2], tsig)
print_success("DN: {}\nTSIG-Key: {}".format(result['dn'], result['tsigKey']))
except exceptions.PlabsException as e:
print_error('Failure while addition: ' + str(e))
elif intent == 'update':
def print_user_usage():
print_error("""Usage: ./plabsdns user u[pdate] USER COMMAND
Available commands:
tsig [key] Updates the users TSIG key """)
user = args[2]
if len(args) < 4:
print_user_usage()
command = args[3]
if command == 'tsig':
if len(args) < 4:
print_error("""Usage: ./plabsdns user u[pdate] USER tsig [key]
Optional argument:
key Defines the TSIG-Key to be used
If not provided, a key will be generated""")
tsig = None
if len(args) > 4:
tsig = args[4]
try:
plabs_dns.verify_tsig_key(plabsDNS.KeyType.User, tsig)
except TSIGKey.UnknownAlgorithm:
print_error('Not a valid TSIG-KEY: Unknown Algorithm')
except exceptions.InvalidIdentifier:
print_error('Not a valid TSIG-KEY: Invalid identifier for user')
except TSIGKey.TSIGException:
print_error('Malformed TSIG key')
try:
result = plabs_dns.update_tsig_key(plabsDNS.KeyType.User, user, tsig)
print_success("DN: {}\nTSIG-Key: {}".format(result['dn'], result['tsigKey']))
except exceptions.PlabsException as e:
print_error('Update aborted: ' + str(e))
elif intent == 'delete':
if len(args) < 3:
print_error("Usage: ./plabsdns user d[elete] USER")
try:
plabs_dns.ldap_user_remove_dns_attrs(args[2])
print_success("OK")
except exceptions.PlabsException as e:
print_error('Deletion aborted: ' + str(e))
elif args[0] == 'zone':
def print_zone_usage():
print_error("""Usage: ./plabsdns zone COMMAND
Available commands:
list List all zones
show Prints all information about a zone
add Add a zone configuration to LDAP
update Update a zone
delete Remove a zone from LDAP""")
if len(args) < 2:
print_zone_usage()
intent = get_intent(args[1])
if not intent:
print_command_unknwon(args[1])
print_zone_usage()
elif intent == 'list':
parser = ArgumentParser(usage='Usage: ./plabsdns zone l[ist] [-h] [PRIMARY_MASTER]')
parser.add_argument('PRIMARY_MASTER', nargs='?',
help='reduce search for zones to this dns server')
args_parsed = parser.parse_args(args[2:])
try:
result = plabs_dns.get_zones(args_parsed.PRIMARY_MASTER)
if len(result) > 0:
print('Current zones:')
for zone in result:
print('- ' + zone)
else:
print('No zones found')
except exceptions.PlabsException as e:
print_error(e)
elif intent == 'show':
try:
zone = plabs_dns.ldap_zone_lookup(args[2])
print_success('DN: {}\nTSIG key: {}\nZone admin: {}\nPrimary master: {}'
.format(zone[0], plabs_dns._get_ldap_attr(zone, 'tsigKey'),
plabs_dns._get_ldap_attr(zone, 'zoneAdmin'),
plabs_dns._get_ldap_attr(zone, 'primaryMaster')))
except exceptions.PlabsException as e:
print_error(e)
elif intent == 'add':
parser = ArgumentParser(usage='Usage: ./plabsdns zone add [-h] ZONE ADMIN ZONE_MASTER [TSIG-KEY]')
parser.add_argument('ZONE', help='A domain (e.g. example.org)')
parser.add_argument('ADMIN', help='A user identifier. May be a uid or a DN')
parser.add_argument('ZONE_MASTER', help='The name of the primary master. May be a DNS Record or a DN')
parser.add_argument('TSIG_KEY', nargs='?', help='A TSIG key in form of ALOG:x.zone:SECRET')
args_parsed = parser.parse_args(args[2:])
if args_parsed.TSIG_KEY:
try:
plabs_dns.verify_tsig_key(plabsDNS.KeyType.Zone, args_parsed.TSIG_KEY)
except TSIGKey.UnknownAlgorithm:
print_error('Not a valid TSIG-KEY: Unknown Algorithm')
except exceptions.InvalidIdentifier:
print_error('Not a valid TSIG-KEY: Invalid identifier for zone')
try:
pass
result = plabs_dns.add_zone(args_parsed.ZONE, args_parsed.ADMIN,
args_parsed.ZONE_MASTER, args_parsed.TSIG_KEY)
print_success("DN: {}\nTSIG-Key: {}".format(result['dn'], result['tsigKey']))
except exceptions.PlabsException as e:
print_error('Failure while addition: ' + str(e))
elif intent == 'update':
def print_update_usage():
print_error("""Usage: ./plabsdns zone u[pdate] ZONE COMMAND
Available commands:
tsig [key] Updates a zones TSIG key
admin USER Updates the zone admin to the provided value
master SERVER Updates the dns master to the provided value
""")
print(args)
zone_identifier = args[2]
if len(args) < 4:
print_update_usage()
command = args[3]
if command == 'tsig':
if len(args) < 4:
print_error("""Usage: ./plabsdns zone u[pdate] ZONE tsig [key]
Optional argument:
key Defines the TSIG-Key to be used
If not provided, a key will be generated""")
tsig = None
if len(args) > 4:
tsig = args[4]
try:
plabs_dns.verify_tsig_key(plabsDNS.KeyType.Zone, tsig)
except TSIGKey.UnknownAlgorithm:
print_error('Not a valid TSIG-KEY: Unknown Algorithm')
except exceptions.InvalidIdentifier:
print_error('Not a valid TSIG-KEY: Invalid identifier for zone')
except TSIGKey.TSIGException:
print_error('Malformed TSIG key')
try:
result = plabs_dns.update_tsig_key(plabsDNS.KeyType.Zone, zone_identifier, tsig)
print_success("DN: {}\nTSIG-Key: {}".format(result['dn'], result['tsigKey']))
except exceptions.PlabsException as e:
print_error('Update aborted: ' + str(e))
elif command == 'admin':
if len(args) < 5:
print_error("""Usage: ./plabsdns zone u[pdate] ZONE admin USER
Positional argument:
USER A DN or a uid/uidNumber that identifies a user""")
try:
plabs_dns.update_zone_attrib(zone_identifier, {
'zoneAdmin': args[4]
})
print_success('OK')
except exceptions.PlabsException as e:
print_error('Update aborted: ' + str(e))
elif command == 'master':
if len(args) < 5:
print_error("""Usage: ./plabsdns zone u[pdate] ZONE master SERVER
Positional argument:
SERVER A DN or a domain that identifies a server""")
try:
plabs_dns.update_zone_attrib(zone_identifier, {
'primaryMaster': args[4]
})
print_success('OK')
except exceptions.PlabsException as e:
print_error('Update aborted: ' + str(e))
else:
print_update_usage()
elif intent == 'delete':
if len(args) < 3:
print_error("""Usage: ./plabsdns zone d[elete] ZONE
Positional arguments:
ZONE A valid domain name or a valid DN within LDAP""")
try:
plabs_dns.delete_zone(args[2])
print_success("OK")
except exceptions.InvalidIdentifier as e:
print_error('Identifier is not a valid DN nor a valid domain name: ' + str(e))
except exceptions.ZoneNotFound as e:
print_error('Domain does not exist: ' + str(e))
except exceptions.PlabsException as e:
print_error('Deletion aborted: ' + str(e))
elif args[0] == 'server':
def print_server_usage():
print_error("""Usage: ./plabsdns server COMMAND
Available commands:
list List all servers (--with-zones)
add Add a server configuration to LDAP
show Prints all information about a server
update Update a server
delete Remove a server from LDAP""")
if len(args) < 2:
print_server_usage()
intent = get_intent(args[1])
if not intent:
print_command_unknwon(args[1])
print_server_usage()
elif intent == 'list':
parser = ArgumentParser(usage='Usage: ./plabsdns server list [-h] [--with-zones]')
parser.add_argument('--with-zones', dest='with_zones', action='store_true', default=False,
help='Also show domains where a server is master of')
args_parsed = parser.parse_args(args[2:])
try:
result = plabs_dns.get_servers(args_parsed.with_zones)
print('Current Servers:')
print_zones = type(result) == dict
for server in result:
print('- ' + server)
if print_zones:
for zone in result[server]:
print(' - '+zone)
except exceptions.PlabsException as e:
print_error(e)
elif intent == 'show':
try:
server = plabs_dns.ldap_server_lookup(args[2], ('serverAddress', 'trusted'))
print_success('DN: {}\nTSIG key: {}\nAddress: {}\nTrusted: {}'
.format(server[0], plabs_dns._get_ldap_attr(server, 'tsigKey'),
plabs_dns._get_ldap_attr(server, 'serverAddress'),
plabs_dns._get_ldap_attr(server, 'trusted')))
except exceptions.PlabsException as e:
print_error(e)
elif intent == 'add':
parser = ArgumentParser(usage='Usage: ./plabsdns server add [-h] [--trusted] CN ADDRESS [TSIG-KEY]')
parser.add_argument('CN', help='A CN in form of a domain (e.g. ns1.example.org)')
parser.add_argument('ADDRESS', help='An IPv4 address of the server')
parser.add_argument('TSIG_KEY', nargs='?', help='A TSIG key in form of ALOG:x.server:SECRET')
parser.add_argument('--trusted', dest='trusted', action='store_true', default=False,
help='If provided the server is set as trusted')
args_parsed = parser.parse_args(args[2:])
if args_parsed.TSIG_KEY:
print(args_parsed.TSIG_KEY)
try:
plabs_dns.verify_tsig_key(plabsDNS.KeyType.Server, args_parsed.TSIG_KEY)
except TSIGKey.UnknownAlgorithm:
print_error('Not a valid TSIG-KEY: Unknown Algorithm')
except exceptions.InvalidIdentifier:
print_error('Not a valid TSIG-KEY: Invalid identifier for zone')
try:
result = plabs_dns.add_server(args_parsed.CN, args_parsed.ADDRESS,
args_parsed.trusted, args_parsed.TSIG_KEY)
print_success("DN: {}\nTSIG-Key: {}".format(result['dn'], result['tsigKey']))
except exceptions.PlabsException as e:
print_error('Failure while addition: ' + str(e))
elif intent == 'update':
def print_update_usage():
print_error("""Usage: ./plabsdns server u[pdate] SERVER COMMAND
Available commands:
tsig [key] Updates a servers TSIG key
trusted Updates the trusted flag
address ADDRESS Updates the servers address""")
server_identifier = args[2]
if len(args) < 4:
print_update_usage()
command = args[3]
if command == 'tsig':
if len(args) < 4:
print_error("""Usage: ./plabsdns server u[pdate] SERVER tsig [key]
Optional argument:
key Defines the TSIG-Key to be used
If not provided, a key will be generated""")
tsig = None
if len(args) > 4:
tsig = args[4]
try:
plabs_dns.verify_tsig_key(plabsDNS.KeyType.Zone, tsig)
except TSIGKey.UnknownAlgorithm:
print_error('Not a valid TSIG-KEY: Unknown Algorithm')
except exceptions.InvalidIdentifier:
print_error('Not a valid TSIG-KEY: Invalid identifier for zone')
except TSIGKey.TSIGException:
print_error('Malformed TSIG key')
try:
result = plabs_dns.update_tsig_key(plabsDNS.KeyType.Server, server_identifier, tsig)
print_success("DN: {}\nTSIG-Key: {}".format(result['dn'], result['tsigKey']))
except exceptions.PlabsException as e:
print_error('Update aborted: ' + str(e))
elif command == 'trusted':
if len(args) < 5:
print_error("""Usage: ./plabsdns zone u[pdate] SERVER trusted BOOL
Positional argument:
BOOL true/false""")
try:
plabs_dns.update_server_attrib(server_identifier, {
'trusted': args[4]
})
print_success('OK')
except exceptions.PlabsException as e:
print_error('Update aborted: ' + str(e))
elif command == 'address':
if len(args) < 5:
print_error("""Usage: ./plabsdns zone u[pdate] SERVER address ADDRESS
Positional argument:
ADDRESS A valid IPv4 or IPv6 address""")
try:
plabs_dns.update_server_attrib(server_identifier, {
'serverAddress': args[4]
})
print_success('OK')
except exceptions.PlabsException as e:
print_error('Update aborted: ' + str(e))
else:
print_update_usage()
elif intent == 'delete':
if len(args) < 3:
print_error("""Usage: ./plabsdns server d[elete] CN
Positional arguments:
CN A CN or a DN of a server""")
try:
plabs_dns.delete_server(args[2])
print_success("OK")
except exceptions.PlabsException as e:
print_error('Deletion aborted: ' + str(e))
def get_intent(intent: str):
if 'add'.startswith(intent):
return 'add'
elif 'delete'.startswith(intent):
return 'delete'
elif 'update'.startswith(intent):
return 'update'
elif 'list'.startswith(intent):
return 'list'
return intent
if __name__ == '__main__':
main()