def regexSearch(self):
        response = self._requestResponse.getResponse()
        offset = []

        # array explicitly needed as list item for applyMarkers
        offsetArray = array('i', [0, 0])

        issues = []

        for i in range(0, self._regexLength):
            offset = []
            try:
                compiledRegex = re.compile(self._regexes[i], re.DOTALL)
            except:
                raise RuntimeException('Failed to compile regular expression.')
            try:
                matched = compiledRegex.finditer(
                    self._helpers.bytesToString(response))
            except:
                raise RuntimeException('Regular expression search failed.')

            # find offsets for all matches
            for match in matched:
                offset = []
                span = match.span()
                offsetArray[0] = span[0]
                offsetArray[1] = span[1]
                offset.append(offsetArray)

                # replace issue detail with regex match
                detail = self._issueDetailsDict[self._regexes[i]]
                detail = detail.replace("$val$", str(match.group()))

                # create temp ScanIssue and add to ScanIssue list
                try:
                    tempIssue = ScanIssue(
                        self._requestResponse.getHttpService(),
                        self._helpers.analyzeRequest(
                            self._requestResponse).getUrl(), [
                                self._callbacks.applyMarkers(
                                    self._requestResponse, None, offset)
                            ], self._issueName, False,
                        detail + self._references[i])
                except:
                    raise RuntimeException('Failed to create issue.')
                try:
                    issues.append(tempIssue)
                except:
                    raise RuntimeException('Failed to append issue.')

        return issues
    def doPassiveScan(self, baseRequestResponse):
        try:
            scanObject = DoScan(baseRequestResponse, self._callbacks)
        except:
            raise RuntimeException('Failed to create scanObject.')
        try:
            scanResult = scanObject.regexSearch()
        except:
            raise RuntimeException('Failed to call scanObject.regexSearch.')

        if (len(scanResult) > 0):
            return scanResult
        else:
            return None
Пример #3
0
def _makeRobot():
    global _robot
    if _robot == None:
        _robot = LegoRobot()
    else:
        if _robot.getGameGrid().isDisposed():
            raise RuntimeException("Java frame disposed")
Пример #4
0
    def wsdlScan(self, invocation):

        # Check initial message for proper request/response and set variables - Burp will not return valid info otherwise
        try:
            invMessage = invocation.getSelectedMessages()
            message = invMessage[0]
            originalHttpService = message.getHttpService()
            self.originalMsgProtocol = originalHttpService.getProtocol()
            self.originalMsgHost = originalHttpService.getHost()
            self.originalMsgPort = originalHttpService.getPort()
            self.originalMsgUrl = self.originalMsgProtocol + '://' + self.originalMsgHost
            print 'Valid request and response found.  Scanning %s for wsdl files.\n' % self.originalMsgHost
        except:
            e = sys.exc_info()[0]
            print "Error: Please start the scan from a request with a valid response.\n"
            raise RuntimeException(e)

        # Get site map of the host selected by the user
        self.siteMap = self._callbacks.getSiteMap(self.originalMsgUrl)

        self.wsdlKeywordList = [
            'xmlns:soap', 'xmlns:wsoap', 'xmlns:wsdl', '<wsdl:', '<soap:'
        ]

        self.detectedUrlList = []
        self.fuzzedWsdlList = []
        self.foundWsdlList = []

        # Loop through each message, check for a valid 200 response, and send the message to checkMessage function
        for siteMapMessage in self.siteMap:
            if siteMapMessage.getRequest():
                if 'Connection: close' not in self._helpers.bytesToString(
                        siteMapMessage.getRequest()) and str(
                            self._helpers.analyzeResponse(
                                siteMapMessage.getResponse()).getStatusCode()
                        ) == '200':
                    self.checkMessage(siteMapMessage)

        if self.foundWsdlList:
            print '%s wsdl file(s) found.\n' % len(self.foundWsdlList)
            for foundWsdl in self.foundWsdlList:
                print '\t' + foundWsdl + '\n'
        else:
            print 'No wsdl files found.\n'

        try:
            # There are two methods of fuzzing for wsdl files, using python's urllib2 module or Burp API
            self.fuzzUrls()
            #self.fuzzUrlsAPI()
        except:
            e = sys.exc_info()[0]
            print "Error: %s" % e

        if self.fuzzedWsdlList:
            print '%s wsdl file(s) fuzzed.\n' % len(self.fuzzedWsdlList)
            for fuzzedWsdl in self.fuzzedWsdlList:
                print '\t' + fuzzedWsdl + '\n'
        else:
            print 'No wsdl files fuzzed.\n'
Пример #5
0
    def builderPhase2(self):
        Ganymede.debug("LDAPBuilderTask builderPhase2 running")

        build_script = System.getProperty("ganymede.biulder.scriptlocation")
        if not build_script:
            raise RuntimeException(
                "Unable to determine builder script location")
        else:
            build_script = PathComplete.completePath(
                build_script) + "ldapbuilder"

        if not os.path.is_file(build_script):
            raise RuntimeException(
                build_script +
                " doesn't exist, not running external LDAP build script")

        os.system(build_script)

        Ganymede.debug("LDAPBuilderTask builderPhase2 complete")
        return 1
Пример #6
0
    def builderPhase1(self):
        Ganymede.debug("LDAPBuilderTask builderPhase1 running")

        self.dnsdomain = System.getProperty("ganymede.gash.dnsdomain")
        if not self.dnsdomain:
            raise RuntimeException(
                "LDAPBuilder not able to determine dns domain name")

        self.output_path = System.getProperty("ganymede.builder.output")
        if not self.output_path:
            raise RuntimeException(
                "LDAPBuilder not able to determine output directory")
        else:
            self.output_path = PathComplete.completePath(self.output_path)

        self.build_users_and_groups()
        self.build_netgroups()

        Ganymede.debug("LDAPBuilderTask builderPhase1 complete")
        return 1
Пример #7
0
    def registerExtenderCallbacks(self, callbacks):
        callbacks.setExtensionName("hello world extension")

        stdout = PrintWriter(callbacks.getStdout(), True)
        stderr = PrintWriter(callbacks.getStderr(), True)

        stdout.println("hello world")
        stderr.println("hello error")

        callbacks.issueAlert("hello alert")

        raise RuntimeException("hello exception")
Пример #8
0
    def registerExtenderCallbacks(self, callbacks):
        # set our extension name
        callbacks.setExtensionName("Hello world extension")

        # obtain our output and error streams
        stdout = PrintWriter(callbacks.getStdout(), True)
        stderr = PrintWriter(callbacks.getStderr(), True)

        # write a message to our output stream
        stdout.println("Hello output")

        # write a message to our error stream
        stderr.println("Hello errors")

        # write a message to the Burp alerts tab
        callbacks.issueAlert("Hello alerts")

        # throw an exception that will appear in our error stream
        raise RuntimeException("Hello exception")
Пример #9
0
    def processPayload(self, currentPayload, originalPayload, baseValue):
        dataParameter = self._helpers.bytesToString(
                         self._helpers.urlDecode(baseValue)
                       )

        # utf-8 encode
        header,payload,signature = [unicode(s).encode('utf-8') for s in dataParameter.split(".",3)]
        decoded_header = self._helpers.bytesToString(
                            self._helpers.base64Decode(header + "=" * (-len(header) % 4))
                        )
        decoded_payload = self._helpers.bytesToString(
                            self._helpers.base64Decode(payload+"=" * (-len(payload) % 4))
                        )

        # Decode header and payload, preserving order if they are JSON objects

        # Decode header
        try:
            header_dict = json.loads(decoded_header, object_pairs_hook=OrderedDict)
        except ValueError:
            raise RuntimeException("[JWT FuzzHelper] Error: ValueError. Failed to decode header!")
        except Exception as e:
            self._stderr.println("[ERROR] Encountered an unknown error when decoding header:\n{}\nCarrying on...".format(e))

        # Decode payload
        # Payload does not have to be a JSON object.
        #   Ref: https://github.com/auth0/node-jsonwebtoken#usage
        payload_is_string = False
        try:
            payload_dict = json.loads(decoded_payload, object_pairs_hook=OrderedDict)
        except ValueError:
            payload_is_string = True
            payload_dict = decoded_payload
        except Exception as e:
            self._stderr.println("[ERROR] Encountered an unknown error when decoding payload:\n{}\nCarrying on...".format(e))

        target = header_dict if self._fuzzoptions["target"] == "Header" else payload_dict
        selector = self._fuzzoptions["selector"]

        # If using Object Identifier-Index then retrieve the 
        # value specified by the selector, 
        # if this value does not exist, assume the user
        # wants to add the value that would have been specified
        # by the selector to the desired JWT segment (this behavior will 
        # be noted in the help docs)

        intruderPayload = self._helpers.bytesToString(currentPayload)
        if not self._fuzzoptions["regex"]:
            if selector != [""]:
                try:
                    value = self.getValue(target, selector)
                except Exception:
                    target = self.buildDict(target, selector)

            if not self._isNone(selector) and selector != [""]:
                target = self.setValue(target, selector, intruderPayload)
        
        # Simple match-replace for regex
        if self._fuzzoptions["regex"]:
            target_string = target if payload_is_string else json.dumps(target)
            target_string = re.sub(selector, intruderPayload, target_string)
            target = target_string if payload_is_string else json.loads(target_string, object_pairs_hook=OrderedDict)
            if self._fuzzoptions["target"] == "Payload":
                payload_dict = target
            else:
                header_dict = target
                

        algorithm = self._fuzzoptions["algorithm"]
        if self._fuzzoptions["signature"]: 
            # pyjwt requires lowercase 'none'. If user wants to try
            # "none", "NonE", "nOnE", etc... they should use .alg
            # as selector, delete sig from intruder and use those
            # permutations as their fuzz list (outlined in help docs)
            # and keep "Generate Signature" as False
            algorithm = "none" if algorithm.lower() == "none" else algorithm
            header_dict["alg"] = algorithm

        header = json.dumps(header_dict, separators=(",",":"))
        payload = payload_dict if payload_is_string else json.dumps(payload_dict, separators=(",",":"))
        header = self._helpers.base64Encode(header).strip("=")
        payload = self._helpers.base64Encode(payload).strip("=")

        contents = header + "." + payload
        
        key = self._fuzzoptions["key"]

        if len(self._fuzzoptions["key_cmd"]) > 0:
            # we provide 'contents' value as an only argument to key-generating command
            # it is expected that the command will print only the signature
            signature = check_output([self._fuzzoptions["key_cmd"], contents])
            modified_jwt = contents + "." + signature
        elif self._fuzzoptions["signature"]:
            # pyjwt throws error when using a public key in symmetric alg (for good reason of course),
            # must do natively to support algorithmic sub attacks
            if algorithm.startswith("HS"):
                if algorithm == "HS256":
                    hmac_algorithm = hashlib.sha256
                elif algorithm == "HS384":
                    hmac_algorithm = hashlib.sha384
                else:
                    hmac_algorithm = hashlib.sha512
            
                signature = self._helpers.base64Encode(
                            hmac.new(
                                    key, contents, hmac_algorithm
                                ).digest()
                    ).strip("=")

                modified_jwt = contents + "." +signature

            # JWT can't sign non-JSON payloads. WTF. This block is for non-JSON payloads.
            elif algorithm.startswith("RS") and payload_is_string:
                if algorithm == "RS256":
                    rsa_algorithm = "SHA-256"
                elif algorithm == "RS384":
                    rsa_algorithm = "SHA-384"
                else:
                    rsa_algorithm = "SHA-512"
                privkey = rsa.PrivateKey.load_pkcs1(key)
                signature = rsa.sign(contents,privkey,rsa_algorithm)
                signature = base64.b64encode(signature).encode('utf-8').replace("=", "")
                modified_jwt = contents + "." + signature
            else:
                # Use pyjwt when using asymmetric alg
                if algorithm == "none":
                    key = ""
                modified_jwt = jwt.encode(payload_dict,key,algorithm=algorithm,headers=header_dict)
        else:
            modified_jwt = contents + "." + signature

        return self._helpers.stringToBytes(modified_jwt)
Пример #10
0
 def __init__( self, msg ):
   self.msg = msg
   RuntimeException.__init__( self, msg )
Пример #11
0
 def toString(self):
     raise RuntimeException('failure in toString')
Пример #12
0
 def toString(self):
     raise RuntimeException(self.error)
Пример #13
0
            self.originalMsgUrl = self.originalMsgProtocol + '://' + self.originalMsgHost
            
            domain = str(self.originalMsgHost)
            ext = tldextract.extract(domain)
            domain1 = ext.domain+'.'+ext.suffix
            
            siteMap = self.callbacks.getSiteMap('')
            lastURL = ''
            print '\n Enumerating %s subdomains.\n' % domain1            
            if siteMap:
              for item in siteMap:
                try:
                  request = item.getRequest()
                  if request:
                    service = item.getHttpService().toString()
                    if service != lastURL:
                      if domain1 in service:
                        print ' [+] %s' %service
                        lastURL = service

                except Exception, e:
                  print 'Error while getting subdomain'
                  continue
            else:
              print 'The Target Site Tree is Empty'

        except:
            e = sys.exc_info()[0]
            print "Something went wrong\n"
            raise RuntimeException(e)
Пример #14
0
 def runtime_exception(self):
     raise RuntimeException("re")