Example #1
0
    def run(self, rsyncd):
        config = ConfigNode('service.rsyncd', self.configstore).__getstate__()

        if rsyncd.get('port') and is_port_open(rsyncd['port']):
            service_state = self.dispatcher.call_sync(
                'service.query', [('name', '=', 'rsyncd')], {
                    'single': True,
                    'select': 'state'
                })

            if not (service_state == "RUNNING"
                    and rsyncd['port'] == config['port']):
                raise TaskException(errno.EINVAL,
                                    'Provided port is already in use')

        try:
            node = ConfigNode('service.rsyncd', self.configstore)
            node.update(rsyncd)
            self.dispatcher.call_sync('etcd.generation.generate_group',
                                      'rsyncd')
            self.dispatcher.dispatch_event('service.rsyncd.changed', {
                'operation': 'updated',
                'ids': None,
            })
        except RpcException as e:
            raise TaskException(
                errno.ENXIO, 'Cannot reconfigure Rsyncd: {0}'.format(str(e)))
Example #2
0
    def run(self, ssh):
        config = self.dispatcher.call_sync('service.query',
                                           [('name', '=', 'sshd')], {
                                               'single': True,
                                               'select': 'config'
                                           })
        port = ssh.get('port')
        if port and port != config['port'] and is_port_open(port):
            raise TaskException(
                errno.EBUSY,
                'Port number : {0} is already in use'.format(port))

        try:
            node = ConfigNode('service.sshd', self.configstore)
            node.update(ssh)
            self.dispatcher.call_sync('etcd.generation.generate_group', 'sshd')
            self.dispatcher.dispatch_event('service.sshd.changed', {
                'operation': 'updated',
                'ids': None,
            })
        except RpcException as e:
            raise TaskException(errno.ENXIO,
                                'Cannot reconfigure SSH: {0}'.format(str(e)))

        return 'RELOAD'
Example #3
0
def validate_portal_port(listen):
    if listen:
        for host in listen:
            if not not is_port_open(host['port']):
                raise TaskException(
                    errno.EFAULT,
                    'Provided port {} is already in use'.format(host['port']))
Example #4
0
    def run(self, nfs):
        config = self.dispatcher.call_sync('service.query',
                                           [('name', '=', 'nfs')],
                                           {'single': True})['config']
        for n in ('mountd_port', 'rpcstatd_port', 'rpclockd_port'):
            port = nfs.get(n)
            if port and port != config[n] and is_port_open(port, 'inet'):
                raise TaskException(
                    errno.EBUSY,
                    'Port number : {0} is already in use'.format(port))

        try:
            node = ConfigNode('service.nfs', self.configstore)
            node.update(nfs)
            self.dispatcher.call_sync('etcd.generation.generate_group',
                                      'services')
            self.dispatcher.call_sync('etcd.generation.generate_group', 'nfs')
            self.dispatcher.dispatch_event('service.nfs.changed', {
                'operation': 'updated',
                'ids': None,
            })
        except RpcException as e:
            raise TaskException(errno.ENXIO,
                                'Cannot reconfigure NFS: {0}'.format(str(e)))

        return 'RESTART'
Example #5
0
def validate_portal_port(listen):
    if listen:
        for host in listen:
            if not not is_port_open(host['port']):
                raise TaskException(
                    errno.EFAULT,
                    'Provided port {} is already in use'.format(host['port'])
                )
def BruteForce(ParentDomain, verbose=False):
    """ Brute Force Forward DNS Lookups for some of the most common subdomain names. 
		These subdomain prefixes are obtained from the file specified in the argument """

    BruteForcePrefixes = open(str(utils.get_config()["brute_force_prefixes_file"]), "r")
    bruteforce_result_list = []  # Set of the domain names obtained by brute forcing

    for line in BruteForcePrefixes:

        CurrentName = (
            line.replace("\n", "") + "." + ParentDomain
        )  # Append the subdoamin prefix to the parent domain name [e.g. abc + google.com = abc.google.com]
        Display = "Current Name is: " + CurrentName

        if verbose:
            print "-" * len(Display)
            print Display

        try:
            IP = DNS.dnslookup(unicode(CurrentName, "utf-8"), qtype="A")[
                0
            ]  # Do a DNS Lookup for the current host name. #The current name will be a combination of the brute force prefix and the parent domain. E.g. - Sub=abc and Parent=xyz.com. So, current=abc.xyz.com
            bruteforce_result_list.append(CurrentName)
            if verbose:
                print "SUCCESS! IP/CNAME = " + IP
                display_text = (
                    "WebServerStatus = ON" if utils.is_port_open(IP, 80) == True else "WebServerStatus = OFF"
                )  # Test whether the destination IP's WebServer is ON. If it isn't, this domain isn't of any interest to us.
                utils.pretty_print(display_text, len(Display))
            else:
                print CurrentName
                # print " [Brute Force]"

        except DNS.Base.ServerError as e:
            display_text = (
                "\nThe DNS Server is Refusing requests. \nPlease use 8.8.8.8 and try again."
                if "REFUSED" in e.message
                else "Non-Existent Domain"
            )
            if verbose:
                utils.pretty_print(display_text, len(Display))
            continue

        except DNS.Base.TimeoutError:  # Handle the case where there's a DNS timeout
            if verbose:
                utils.pretty_print("Timeout", len(Display))
            continue

        except IndexError:  # This handles those (rare) cases where a valid DNS response is returned with no IP address (e.g. - 67.salesforce.com), because of which the variable index 0 of the array is non-existent and we thereforce cannot assign it to the variable 'IP'.
            if verbose:
                utils.pretty_print("Non-Existent Domain", len(Display))
            continue

    return bruteforce_result_list
Example #7
0
def BruteForce(ParentDomain, verbose=False):
    """ Brute Force Forward DNS Lookups for some of the most common subdomain names. 
		These subdomain prefixes are obtained from the file specified in the argument """

    BruteForcePrefixes = open(
        str(utils.get_config()['brute_force_prefixes_file']), 'r')
    bruteforce_result_list = [
    ]  #Set of the domain names obtained by brute forcing

    for line in BruteForcePrefixes:

        CurrentName = line.replace(
            "\n", ""
        ) + "." + ParentDomain  # Append the subdoamin prefix to the parent domain name [e.g. abc + google.com = abc.google.com]
        Display = "Current Name is: " + CurrentName

        if verbose:
            print '-' * len(Display)
            print Display

        try:
            IP = DNS.dnslookup(
                unicode(CurrentName, "utf-8"), qtype='A'
            )[0]  # Do a DNS Lookup for the current host name. #The current name will be a combination of the brute force prefix and the parent domain. E.g. - Sub=abc and Parent=xyz.com. So, current=abc.xyz.com
            bruteforce_result_list.append(CurrentName)
            if verbose:
                print "SUCCESS! IP/CNAME = " + IP
                display_text = "WebServerStatus = ON" if utils.is_port_open(
                    IP, 80
                ) == True else "WebServerStatus = OFF"  #Test whether the destination IP's WebServer is ON. If it isn't, this domain isn't of any interest to us.
                utils.pretty_print(display_text, len(Display))
            else:
                print CurrentName
                #print " [Brute Force]"

        except DNS.Base.ServerError as e:
            display_text = "\nThe DNS Server is Refusing requests. \nPlease use 8.8.8.8 and try again." if 'REFUSED' in e.message else "Non-Existent Domain"
            if verbose:
                utils.pretty_print(display_text, len(Display))
            continue

        except DNS.Base.TimeoutError:  #Handle the case where there's a DNS timeout
            if verbose:
                utils.pretty_print("Timeout", len(Display))
            continue

        except IndexError:  # This handles those (rare) cases where a valid DNS response is returned with no IP address (e.g. - 67.salesforce.com), because of which the variable index 0 of the array is non-existent and we thereforce cannot assign it to the variable 'IP'.
            if verbose:
                utils.pretty_print("Non-Existent Domain", len(Display))
            continue

    return bruteforce_result_list
def get_SANs_from_cert(Domain):
    '''
	Returns the full list of Subject Alternative Names from an SSL cert. If the server isn't listening on port 443, return None
	'''
    SANs = []

    if utils.is_port_open(Domain, 443) == False:
        return None

    s = socket.socket(socket.AF_INET,
                      socket.SOCK_STREAM)  # Create a regular TCP Stream Socket
    sslsock = ssl.wrap_socket(
        s,
        cert_reqs=ssl.CERT_REQUIRED,
        ssl_version=ssl.PROTOCOL_SSLv23,
        ca_certs='data/ca-bundle.crt')  # Wrap the TCP socket in an SSL Context

    try:
        sslsock.connect(
            (Domain, 443)
        )  # This is the regular socket connect() method but it also does the SSL handshake in this case
    except socket.error as e:
        print e
        return None

    try:
        cert = sslsock.getpeercert()
    except ValueError as ve:
        print "No Cert"
        cert = None

    if cert is not None:
        try:
            SAN_Tuples = cert['subjectAltName']
        except KeyError:
            if verbose:
                print "No SAN"
            return None

        for x, y in SAN_Tuples:
            SANs.append(y)

        return SANs

    elif cert is None:
        return None
Example #9
0
    def run(self, rsyncd):

        if rsyncd.get('port') and is_port_open(rsyncd['port']):
            raise TaskException(errno.EINVAL, 'Provided port is already in use')

        try:
            node = ConfigNode('service.rsyncd', self.configstore)
            node.update(rsyncd)
            self.dispatcher.call_sync('etcd.generation.generate_group', 'rsyncd')
            self.dispatcher.dispatch_event('service.rsyncd.changed', {
                'operation': 'updated',
                'ids': None,
            })
        except RpcException as e:
            raise TaskException(
                errno.ENXIO, 'Cannot reconfigure Rsyncd: {0}'.format(str(e))
            )
Example #10
0
    def run(self, rsyncd):

        if rsyncd.get('port') and is_port_open(rsyncd['port']):
            raise TaskException(errno.EINVAL,
                                'Provided port is already in use')

        try:
            node = ConfigNode('service.rsyncd', self.configstore)
            node.update(rsyncd)
            self.dispatcher.call_sync('etcd.generation.generate_group',
                                      'rsyncd')
            self.dispatcher.dispatch_event('service.rsyncd.changed', {
                'operation': 'updated',
                'ids': None,
            })
        except RpcException as e:
            raise TaskException(
                errno.ENXIO, 'Cannot reconfigure Rsyncd: {0}'.format(str(e)))
Example #11
0
    def run(self, webdav):
        node = ConfigNode('service.webdav', self.configstore).__getstate__()
        if 'password' in webdav:
            webdav['password'] = unpassword(webdav['password'])

        for p in ('http_port', 'https_port'):
            port = webdav.get(p)
            if port and port != node[p] and is_port_open(port):
                raise TaskException(
                    errno.EBUSY,
                    'Port number : {0} is already in use'.format(port))

        node.update(webdav)

        if node['http_port'] == node['https_port']:
            raise TaskException(errno.EINVAL,
                                'HTTP and HTTPS ports cannot be the same')

        if 'HTTPS' in node['protocol'] and not node['certificate']:
            raise TaskException(
                errno.EINVAL,
                'SSL protocol specified without choosing a certificate')

        if node['certificate'] and not self.dispatcher.call_sync(
                'crypto.certificate.query', [('id', '=', node['certificate'])],
            {'single': True}):
            raise TaskException(errno.ENOENT, 'SSL Certificate not found.')

        try:
            node = ConfigNode('service.webdav', self.configstore)
            node.update(webdav)
            self.dispatcher.call_sync('etcd.generation.generate_group',
                                      'services')
            self.dispatcher.call_sync('etcd.generation.generate_group',
                                      'webdav')
            self.dispatcher.dispatch_event('service.webdav.changed', {
                'operation': 'updated',
                'ids': None,
            })
        except RpcException as e:
            raise TaskException(
                errno.ENXIO, 'Cannot reconfigure WebDAV: {0}'.format(str(e)))

        return 'RESTART'
Example #12
0
    def run(self, ssh):
        config = self.dispatcher.call_sync(
            'service.query', [('name', '=', 'sshd')], {'single': True, 'select': 'config'})
        port = ssh.get('port')
        if port and port != config['port'] and is_port_open(port):
            raise TaskException(errno.EBUSY, 'Port number : {0} is already in use'.format(port))

        try:
            node = ConfigNode('service.sshd', self.configstore)
            node.update(ssh)
            self.dispatcher.call_sync('etcd.generation.generate_group', 'sshd')
            self.dispatcher.dispatch_event('service.sshd.changed', {
                'operation': 'updated',
                'ids': None,
            })
        except RpcException as e:
            raise TaskException(
                errno.ENXIO, 'Cannot reconfigure SSH: {0}'.format(str(e))
            )

        return 'RELOAD'
def get_SANs_from_cert(Domain):
	'''
	Returns the full list of Subject Alternative Names from an SSL cert. If the server isn't listening on port 443, return None
	'''
	SANs = []

	if utils.is_port_open(Domain,443) == False:
		return None

	s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)  # Create a regular TCP Stream Socket
	sslsock = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_SSLv23, ca_certs='data/ca-bundle.crt')  # Wrap the TCP socket in an SSL Context
	
	try:
		sslsock.connect((Domain,443))  		# This is the regular socket connect() method but it also does the SSL handshake in this case
	except socket.error as e:
		print e
		return None

	try:
		cert = sslsock.getpeercert()
	except ValueError as ve:
		print "No Cert"
		cert = None

	if cert is not None:
		try:
			SAN_Tuples = cert['subjectAltName']
		except KeyError:
			if verbose:
				print "No SAN"
			return None

		for x,y in SAN_Tuples:
			SANs.append(y)

		return SANs

	elif cert is None:
		return None
Example #14
0
    def run(self, nfs):
        config = self.dispatcher.call_sync('service.query', [('name', '=', 'nfs')], {'single': True})['config']
        for n in ('mountd_port', 'rpcstatd_port', 'rpclockd_port'):
            port = nfs.get(n)
            if port and port != config[n] and is_port_open(port):
                raise TaskException(errno.EBUSY, 'Port number : {0} is already in use'.format(port))

        try:
            node = ConfigNode('service.nfs', self.configstore)
            node.update(nfs)
            self.dispatcher.call_sync('etcd.generation.generate_group', 'services')
            self.dispatcher.call_sync('etcd.generation.generate_group', 'nfs')
            self.dispatcher.dispatch_event('service.nfs.changed', {
                'operation': 'updated',
                'ids': None,
            })
        except RpcException as e:
            raise TaskException(
                errno.ENXIO, 'Cannot reconfigure NFS: {0}'.format(str(e))
            )

        return 'RESTART'
Example #15
0
    def run(self, webdav):
        node = ConfigNode('service.webdav', self.configstore).__getstate__()
        if 'password' in webdav:
            webdav['password'] = unpassword(webdav['password'])

        for p in ('http_port', 'https_port'):
            port = webdav.get(p)
            if port and port != node[p] and is_port_open(port):
                raise TaskException(errno.EBUSY, 'Port number : {0} is already in use'.format(port))

        node.update(webdav)

        if node['http_port'] == node['https_port']:
            raise TaskException(errno.EINVAL, 'HTTP and HTTPS ports cannot be the same')

        if 'HTTPS' in node['protocol'] and not node['certificate']:
            raise TaskException(errno.EINVAL, 'SSL protocol specified without choosing a certificate')

        if node['certificate'] and not self.dispatcher.call_sync(
            'crypto.certificate.query', [('id', '=', node['certificate'])], {'single': True}
        ):
                raise TaskException(errno.ENOENT, 'SSL Certificate not found.')

        try:
            node = ConfigNode('service.webdav', self.configstore)
            node.update(webdav)
            self.dispatcher.call_sync('etcd.generation.generate_group', 'services')
            self.dispatcher.call_sync('etcd.generation.generate_group', 'webdav')
            self.dispatcher.dispatch_event('service.webdav.changed', {
                'operation': 'updated',
                'ids': None,
            })
        except RpcException as e:
            raise TaskException(
                errno.ENXIO, 'Cannot reconfigure WebDAV: {0}'.format(str(e))
            )

        return 'RESTART'
def check_port_accessible(host, port):
    if not utils.is_port_open(port, host=host):
        raise ValueError('RabbitMQ is not listening at {0}:{1}'.format(
            host, port))
Example #17
0
def check_port_accessible(host, port):
    if not utils.is_port_open(port, host=host):
        raise ValueError('RabbitMQ is not listening at {0}:{1}'.format(
            host, port))
Example #18
0
import webview
import sys
import settings
from utils import is_port_open

logger = logging.getLogger(__name__)

# 通过这种方式运行,DEBUG 不能为 True
settings.DEBUG = False
settings.PORT = settings.PRODUCT_PORT

if sys.platform == 'win32':
    # CTF Python 使用 Chrome 66
    webview.gui = 'cef'

while is_port_open('127.0.0.1', settings.PORT):
    logger.info('port %s is unavailable' % settings.PORT)
    settings.PORT += 1


def url_ok(url):
    try:
        return requests.get(url, timeout=3).status_code == 200
    except Exception as e:
        logger.error("Server not started, %s" % e)
        return False


def main():
    logger.info("Starting server")
    from server import run_server