idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
20,700
private AbstractParamContainerPanel getJSplitPane ( ) { if ( jSplitPane == null ) { jSplitPane = new AbstractParamContainerPanel ( ) ; jSplitPane . setVisible ( true ) ; if ( this . rootName != null ) { jSplitPane . getRootNode ( ) . setUserObject ( rootName ) ; } } return jSplitPane ; }
This method initializes jSplitPane
20,701
public static List < ApiImplementor > getAllImplementors ( ) { List < ApiImplementor > imps = new ArrayList < > ( ) ; ApiImplementor api ; imps . add ( new AlertAPI ( null ) ) ; api = new AntiCsrfAPI ( null ) ; api . addApiOptions ( new AntiCsrfParam ( ) ) ; imps . add ( api ) ; imps . add ( new PassiveScanAPI ( null ) ) ; imps . add ( new SearchAPI ( null ) ) ; api = new AutoUpdateAPI ( null ) ; api . addApiOptions ( new OptionsParamCheckForUpdates ( ) ) ; imps . add ( api ) ; api = new SpiderAPI ( null ) ; api . addApiOptions ( new SpiderParam ( ) ) ; imps . add ( api ) ; api = new CoreAPI ( new ConnectionParam ( ) ) ; imps . add ( api ) ; imps . add ( new ParamsAPI ( null ) ) ; api = new ActiveScanAPI ( null ) ; api . addApiOptions ( new ScannerParam ( ) ) ; imps . add ( api ) ; imps . add ( new ContextAPI ( ) ) ; imps . add ( new HttpSessionsAPI ( null ) ) ; imps . add ( new BreakAPI ( null ) ) ; imps . add ( new AuthenticationAPI ( null ) ) ; imps . add ( new AuthorizationAPI ( ) ) ; imps . add ( new SessionManagementAPI ( null ) ) ; imps . add ( new UsersAPI ( null ) ) ; imps . add ( new ForcedUserAPI ( null ) ) ; imps . add ( new ScriptAPI ( null ) ) ; api = new StatsAPI ( null ) ; api . addApiOptions ( new StatsParam ( ) ) ; imps . add ( api ) ; return imps ; }
Return all of the available ApiImplementors . If you implement a new ApiImplementor then you must add it to this class .
20,702
public String generateForm ( HttpMessage msg ) throws UnsupportedEncodingException { String requestUri = msg . getRequestHeader ( ) . getURI ( ) . toString ( ) ; StringBuilder sb = new StringBuilder ( 300 ) ; sb . append ( "<html>\n" ) ; sb . append ( "<body>\n" ) ; sb . append ( "<h3>" ) ; sb . append ( requestUri ) ; sb . append ( "</h3>" ) ; sb . append ( "<form id=\"f1\" method=\"POST\" action=\"" ) . append ( requestUri ) . append ( "\">\n" ) ; sb . append ( "<table>\n" ) ; TreeSet < HtmlParameter > params = msg . getFormParams ( ) ; Iterator < HtmlParameter > iter = params . iterator ( ) ; while ( iter . hasNext ( ) ) { HtmlParameter htmlParam = iter . next ( ) ; String name = URLDecoder . decode ( htmlParam . getName ( ) , "UTF-8" ) ; String value = URLDecoder . decode ( htmlParam . getValue ( ) , "UTF-8" ) ; sb . append ( "<tr><td>\n" ) ; sb . append ( name ) ; sb . append ( "<td>" ) ; sb . append ( "<input name=\"" ) ; sb . append ( name ) ; sb . append ( "\" value=\"" ) ; sb . append ( value ) ; sb . append ( "\" size=\"100\">" ) ; sb . append ( "</tr>\n" ) ; } sb . append ( "</table>\n" ) ; sb . append ( "<input id=\"submit\" type=\"submit\" value=\"Submit\"/>\n" ) ; sb . append ( "</form>\n" ) ; sb . append ( "</body>\n" ) ; sb . append ( "</html>\n" ) ; return sb . toString ( ) ; }
Generates a HTML form from the given message .
20,703
private void zzScanError ( int errorCode ) { String message ; try { message = ZZ_ERROR_MSG [ errorCode ] ; } catch ( ArrayIndexOutOfBoundsException e ) { message = ZZ_ERROR_MSG [ ZZ_UNKNOWN_ERROR ] ; } throw new Error ( message ) ; }
Reports an error that occured while scanning .
20,704
public void addProxyServer ( ProxyServer proxyServer ) { proxyServers . add ( proxyServer ) ; extensionHooks . values ( ) . forEach ( extHook -> hookProxyServer ( extHook , proxyServer ) ) ; }
Adds the given proxy server to be automatically updated with proxy related listeners .
20,705
public void removeProxyServer ( ProxyServer proxyServer ) { proxyServers . remove ( proxyServer ) ; extensionHooks . values ( ) . forEach ( extHook -> unhookProxyServer ( extHook , proxyServer ) ) ; }
Removes the given proxy server .
20,706
public void startLifeCycle ( Extension ext ) throws DatabaseException , DatabaseUnsupportedException { ext . init ( ) ; ext . databaseOpen ( model . getDb ( ) ) ; ext . initModel ( model ) ; ext . initXML ( model . getSession ( ) , model . getOptionsParam ( ) ) ; ext . initView ( view ) ; ExtensionHook extHook = new ExtensionHook ( model , view ) ; extensionHooks . put ( ext , extHook ) ; try { ext . hook ( extHook ) ; hookContextDataFactories ( ext , extHook ) ; hookApiImplementors ( ext , extHook ) ; if ( view != null ) { hookView ( ext , view , extHook ) ; hookMenu ( view , extHook ) ; } hookOptions ( extHook ) ; hookProxies ( extHook ) ; ext . optionsLoaded ( ) ; ext . postInit ( ) ; } catch ( Exception e ) { logExtensionInitError ( ext , e ) ; } ext . start ( ) ; Proxy proxy = Control . getSingleton ( ) . getProxy ( ) ; hookProxyListeners ( proxy , extHook . getProxyListenerList ( ) ) ; hookOverrideMessageProxyListeners ( proxy , extHook . getOverrideMessageProxyListenerList ( ) ) ; hookPersistentConnectionListeners ( proxy , extHook . getPersistentConnectionListener ( ) ) ; hookConnectRequestProxyListeners ( proxy , extHook . getConnectRequestProxyListeners ( ) ) ; if ( view != null ) { hookSiteMapListeners ( view . getSiteTreePanel ( ) , extHook . getSiteMapListenerList ( ) ) ; } }
Initialize a specific Extension
20,707
public void hookCommandLineListener ( CommandLine cmdLine ) throws Exception { List < CommandLineArgument [ ] > allCommandLineList = new ArrayList < > ( ) ; Map < String , CommandLineListener > extMap = new HashMap < > ( ) ; for ( Map . Entry < Extension , ExtensionHook > entry : extensionHooks . entrySet ( ) ) { ExtensionHook hook = entry . getValue ( ) ; CommandLineArgument [ ] arg = hook . getCommandLineArgument ( ) ; if ( arg . length > 0 ) { allCommandLineList . add ( arg ) ; } Extension extension = entry . getKey ( ) ; if ( extension instanceof CommandLineListener ) { CommandLineListener cli = ( CommandLineListener ) extension ; List < String > exts = cli . getHandledExtensions ( ) ; if ( exts != null ) { for ( String ext : exts ) { extMap . put ( ext , cli ) ; } } } } cmdLine . parse ( allCommandLineList , extMap ) ; }
Hook command line listener with the command line processor
20,708
private void initAllExtension ( double progressFactor ) { double factorPerc = progressFactor / getExtensionCount ( ) ; for ( int i = 0 ; i < getExtensionCount ( ) ; i ++ ) { Extension extension = getExtension ( i ) ; try { extension . init ( ) ; extension . databaseOpen ( Model . getSingleton ( ) . getDb ( ) ) ; if ( view != null ) { view . addSplashScreenLoadingCompletion ( factorPerc ) ; } } catch ( Throwable e ) { logExtensionInitError ( extension , e ) ; } } }
Init all extensions
20,709
private void initModelAllExtension ( Model model , double progressFactor ) { double factorPerc = progressFactor / getExtensionCount ( ) ; for ( int i = 0 ; i < getExtensionCount ( ) ; i ++ ) { Extension extension = getExtension ( i ) ; try { extension . initModel ( model ) ; if ( view != null ) { view . addSplashScreenLoadingCompletion ( factorPerc ) ; } } catch ( Exception e ) { logExtensionInitError ( extension , e ) ; } } }
Init all extensions with the same Model
20,710
private void initViewAllExtension ( final View view , double progressFactor ) { if ( view == null ) { return ; } final double factorPerc = progressFactor / getExtensionCount ( ) ; for ( int i = 0 ; i < getExtensionCount ( ) ; i ++ ) { final Extension extension = getExtension ( i ) ; try { EventQueue . invokeAndWait ( new Runnable ( ) { public void run ( ) { extension . initView ( view ) ; view . addSplashScreenLoadingCompletion ( factorPerc ) ; } } ) ; } catch ( Exception e ) { logExtensionInitError ( extension , e ) ; } } }
Init all extensions with the same View
20,711
public List < String > getUnsavedResources ( ) { List < String > list = new ArrayList < > ( ) ; List < String > l ; for ( int i = 0 ; i < getExtensionCount ( ) ; i ++ ) { l = getExtension ( i ) . getUnsavedResources ( ) ; if ( l != null ) { list . addAll ( l ) ; } } return list ; }
Gets the names of all unsaved resources of all the extensions .
20,712
private int addScriptsFromDir ( File dir , ScriptType type , String targetEngineName ) { int addedScripts = 0 ; File typeDir = new File ( dir , type . getName ( ) ) ; if ( typeDir . exists ( ) ) { for ( File f : typeDir . listFiles ( ) ) { String ext = f . getName ( ) . substring ( f . getName ( ) . lastIndexOf ( "." ) + 1 ) ; String engineName = this . getEngineNameForExtension ( ext ) ; if ( engineName != null && ( targetEngineName == null || engineName . equals ( targetEngineName ) ) ) { try { if ( f . canWrite ( ) ) { String scriptName = this . getUniqueScriptName ( f . getName ( ) , ext ) ; logger . debug ( "Loading script " + scriptName ) ; ScriptWrapper sw = new ScriptWrapper ( scriptName , "" , this . getEngineWrapper ( engineName ) , type , false , f ) ; this . loadScript ( sw ) ; this . addScript ( sw , false ) ; } else { String scriptName = this . getUniqueTemplateName ( f . getName ( ) , ext ) ; logger . debug ( "Loading script " + scriptName ) ; ScriptWrapper sw = new ScriptWrapper ( scriptName , "" , this . getEngineWrapper ( engineName ) , type , false , f ) ; this . loadScript ( sw ) ; this . addTemplate ( sw , false ) ; } addedScripts ++ ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } } else { logger . debug ( "Ignoring " + f . getName ( ) ) ; } } } return addedScripts ; }
Adds the scripts from the given directory of the given script type and optionally for the engine with the given name .
20,713
private static boolean isSavedInDir ( ScriptWrapper scriptWrapper , File directory ) { File file = scriptWrapper . getFile ( ) ; if ( file == null ) { return false ; } return file . getParentFile ( ) . equals ( directory ) ; }
Tells whether or not the given script is saved in the given directory .
20,714
public int getScriptCount ( File dir ) { int scripts = 0 ; for ( ScriptType type : this . getScriptTypes ( ) ) { File locDir = new File ( dir , type . getName ( ) ) ; if ( locDir . exists ( ) ) { for ( File f : locDir . listFiles ( ) ) { String ext = f . getName ( ) . substring ( f . getName ( ) . lastIndexOf ( "." ) + 1 ) ; String engineName = this . getEngineNameForExtension ( ext ) ; if ( engineName != null ) { scripts ++ ; } } } } return scripts ; }
Gets the numbers of scripts for the given directory for the currently registered script engines and types .
20,715
public ScriptWrapper loadScript ( ScriptWrapper script , Charset charset ) throws IOException { if ( script == null ) { throw new IllegalArgumentException ( "Parameter script must not be null." ) ; } if ( charset == null ) { throw new IllegalArgumentException ( "Parameter charset must not be null." ) ; } script . loadScript ( charset ) ; if ( script . getType ( ) == null ) { script . setType ( this . getScriptType ( script . getTypeName ( ) ) ) ; } return script ; }
Loads the script from the file using the given charset .
20,716
public boolean isAllowed ( String classname ) { Objects . requireNonNull ( classname ) ; if ( ! restrictedClassnames . isEmpty ( ) ) { for ( String restrictedClassname : restrictedClassnames ) { if ( classname . startsWith ( restrictedClassname ) ) { return false ; } } } if ( ! allowedClassnames . isEmpty ( ) ) { for ( String allowedClassname : allowedClassnames ) { if ( classname . startsWith ( allowedClassname ) ) { return true ; } } return false ; } return true ; }
Tells whether or not the given classname is allowed thus can be loaded .
20,717
private String getEscapedValue ( String value ) { if ( value != null ) { try { return URLEncoder . encode ( value , "UTF-8" ) ; } catch ( UnsupportedEncodingException ex ) { } } return "" ; }
Encode the parameter value for a correct URL introduction
20,718
public static String entityEncode ( String text ) { String result = text ; if ( result == null ) { return result ; } return StringEscapeUtils . escapeXml10 ( XMLStringUtil . escapeControlChrs ( result ) ) ; }
Encode entity for HTML or XML output .
20,719
static void init ( boolean includeAddOns ) { loadedPlugins = new ArrayList < > ( CoreFunctionality . getBuiltInActiveScanRules ( ) ) ; if ( includeAddOns ) { loadedPlugins . addAll ( ExtensionFactory . getAddOnLoader ( ) . getActiveScanRules ( ) ) ; } Collections . sort ( loadedPlugins , riskComparator ) ; mapLoadedPlugins = new HashMap < > ( ) ; for ( Plugin plugin : loadedPlugins ) { checkPluginId ( plugin ) ; mapLoadedPlugins . put ( plugin . getId ( ) , plugin ) ; } }
Helper method to ease tests .
20,720
private Plugin probeNextPlugin ( ) { Plugin plugin = null ; int i = 0 ; while ( i < listPending . size ( ) ) { plugin = listPending . get ( i ) ; if ( isAllDependencyCompleted ( plugin ) ) { return plugin ; } i ++ ; } return null ; }
Get next test ready to be run . Null = none . Test dependendent on others will not be obtained .
20,721
synchronized Plugin nextPlugin ( ) { if ( ! init ) { this . reset ( ) ; } Plugin plugin = probeNextPlugin ( ) ; if ( plugin == null ) { return null ; } listPending . remove ( plugin ) ; plugin . setTimeStarted ( ) ; listRunning . add ( plugin ) ; return plugin ; }
Get next plugin ready to be run without any dependency outstanding .
20,722
private void saveToContext ( Context context , boolean updateSiteStructure ) { ParameterParser urlParamParser = context . getUrlParamParser ( ) ; ParameterParser formParamParser = context . getPostParamParser ( ) ; List < String > structParams = new ArrayList < String > ( ) ; List < StructuralNodeModifier > ddns = new ArrayList < StructuralNodeModifier > ( ) ; for ( StructuralNodeModifier snm : this . ddnTableModel . getElements ( ) ) { if ( snm . getType ( ) . equals ( StructuralNodeModifier . Type . StructuralParameter ) ) { structParams . add ( snm . getName ( ) ) ; } else { ddns . add ( snm ) ; } } if ( urlParamParser instanceof StandardParameterParser ) { StandardParameterParser urlStdParamParser = ( StandardParameterParser ) urlParamParser ; urlStdParamParser . setKeyValuePairSeparators ( this . getUrlKvPairSeparators ( ) . getText ( ) ) ; urlStdParamParser . setKeyValueSeparators ( this . getUrlKeyValueSeparators ( ) . getText ( ) ) ; urlStdParamParser . setStructuralParameters ( structParams ) ; context . setUrlParamParser ( urlStdParamParser ) ; urlStdParamParser . setContext ( context ) ; } if ( formParamParser instanceof StandardParameterParser ) { StandardParameterParser formStdParamParser = ( StandardParameterParser ) formParamParser ; formStdParamParser . setKeyValuePairSeparators ( this . getPostKvPairSeparators ( ) . getText ( ) ) ; formStdParamParser . setKeyValueSeparators ( this . getPostKeyValueSeparators ( ) . getText ( ) ) ; context . setPostParamParser ( formStdParamParser ) ; formStdParamParser . setContext ( context ) ; } context . setDataDrivenNodes ( ddns ) ; if ( updateSiteStructure ) { context . restructureSiteTree ( ) ; } }
Save the data from this panel to the provided context .
20,723
protected ExtensionHttpSessions getExtensionHttpSessions ( ) { if ( extensionHttpSessions == null ) { extensionHttpSessions = Control . getSingleton ( ) . getExtensionLoader ( ) . getExtension ( ExtensionHttpSessions . class ) ; } return extensionHttpSessions ; }
Gets the ExtensionHttpSessions if it s enabled
20,724
private void runScan ( ) { spiderDone = 0 ; Date start = new Date ( ) ; log . info ( "Starting spidering scan on " + site + " at " + start ) ; startSpider ( ) ; this . isAlive = true ; }
Runs the scan .
20,725
private void startSpider ( ) { spider = new Spider ( id , extension , spiderParams , extension . getModel ( ) . getOptionsParam ( ) . getConnectionParam ( ) , extension . getModel ( ) , this . scanContext ) ; spider . addSpiderListener ( this ) ; for ( SpiderListener l : pendingSpiderListeners ) { spider . addSpiderListener ( l ) ; } List < String > excludeList = new ArrayList < > ( ) ; excludeList . addAll ( extension . getExcludeList ( ) ) ; excludeList . addAll ( extension . getModel ( ) . getSession ( ) . getExcludeFromSpiderRegexs ( ) ) ; excludeList . addAll ( extension . getModel ( ) . getSession ( ) . getGlobalExcludeURLRegexs ( ) ) ; spider . setExcludeList ( excludeList ) ; addSeeds ( ) ; spider . setScanAsUser ( scanUser ) ; if ( this . customSpiderParsers != null ) { for ( SpiderParser sp : this . customSpiderParsers ) { spider . addCustomParser ( sp ) ; } } if ( this . customFetchFilters != null ) { for ( FetchFilter ff : this . customFetchFilters ) { spider . addFetchFilter ( ff ) ; } } if ( this . customParseFilters != null ) { for ( ParseFilter pf : this . customParseFilters ) { spider . addParseFilter ( pf ) ; } } spider . start ( ) ; }
Start spider .
20,726
private void addSeed ( SiteNode node ) { try { if ( ! node . isRoot ( ) && node . getHistoryReference ( ) != null ) { HttpMessage msg = node . getHistoryReference ( ) . getHttpMessage ( ) ; if ( ! msg . getResponseHeader ( ) . isImage ( ) ) { spider . addSeed ( msg ) ; } } } catch ( Exception e ) { log . error ( "Error while adding seed for Spider scan: " + e . getMessage ( ) , e ) ; } }
Adds the given node as seed if the corresponding message is not an image .
20,727
private void addMessageToSitesTree ( final HistoryReference historyReference , final HttpMessage message ) { if ( View . isInitialised ( ) && ! EventQueue . isDispatchThread ( ) ) { EventQueue . invokeLater ( new Runnable ( ) { public void run ( ) { addMessageToSitesTree ( historyReference , message ) ; } } ) ; return ; } StructuralNode node = SessionStructure . addPath ( Model . getSingleton ( ) . getSession ( ) , historyReference , message , true ) ; if ( node != null ) { try { addUriToAddedNodesModel ( SessionStructure . getNodeName ( message ) , message . getRequestHeader ( ) . getMethod ( ) , "" ) ; } catch ( URIException e ) { log . error ( "Error while adding node to added nodes model: " + e . getMessage ( ) , e ) ; } } }
Adds the given message to the sites tree .
20,728
public void addSpiderListener ( SpiderListener listener ) { if ( spider != null ) { this . spider . addSpiderListener ( listener ) ; } else { this . pendingSpiderListeners . add ( listener ) ; } }
Adds a new spider listener .
20,729
private PopupContextMenuItemFactory getPopupFlagLoggedInIndicatorMenu ( ) { if ( this . popupFlagLoggedInIndicatorMenuFactory == null ) { popupFlagLoggedInIndicatorMenuFactory = new PopupContextMenuItemFactory ( "dd - " + Constant . messages . getString ( "context.flag.popup" ) ) { private static final long serialVersionUID = 2453839120088204122L ; public ExtensionPopupMenuItem getContextMenu ( Context context , String parentMenu ) { return new PopupFlagLoggedInIndicatorMenu ( context ) ; } } ; } return this . popupFlagLoggedInIndicatorMenuFactory ; }
Gets the popup menu for flagging the Logged in pattern .
20,730
private PopupContextMenuItemFactory getPopupFlagLoggedOutIndicatorMenu ( ) { if ( this . popupFlagLoggedOutIndicatorMenuFactory == null ) { popupFlagLoggedOutIndicatorMenuFactory = new PopupContextMenuItemFactory ( "dd - " + Constant . messages . getString ( "context.flag.popup" ) ) { private static final long serialVersionUID = 2453839120088204123L ; public ExtensionPopupMenuItem getContextMenu ( Context context , String parentMenu ) { return new PopupFlagLoggedOutIndicatorMenu ( context ) ; } } ; } return this . popupFlagLoggedOutIndicatorMenuFactory ; }
Gets the popup menu for flagging the Logged out pattern .
20,731
private void loadAuthenticationMethodTypes ( ExtensionHook hook ) { this . authenticationMethodTypes = new ArrayList < > ( ) ; this . authenticationMethodTypes . add ( new FormBasedAuthenticationMethodType ( ) ) ; this . authenticationMethodTypes . add ( new HttpAuthenticationMethodType ( ) ) ; this . authenticationMethodTypes . add ( new ManualAuthenticationMethodType ( ) ) ; this . authenticationMethodTypes . add ( new ScriptBasedAuthenticationMethodType ( ) ) ; this . authenticationMethodTypes . add ( new JsonBasedAuthenticationMethodType ( ) ) ; for ( AuthenticationMethodType a : authenticationMethodTypes ) { a . hook ( hook ) ; } if ( log . isInfoEnabled ( ) ) { log . info ( "Loaded authentication method types: " + authenticationMethodTypes ) ; } }
Loads the authentication method types and hooks them up .
20,732
public AuthenticationMethodType getAuthenticationMethodTypeForIdentifier ( int id ) { for ( AuthenticationMethodType t : getAuthenticationMethodTypes ( ) ) if ( t . getUniqueIdentifier ( ) == id ) return t ; return null ; }
Gets the authentication method type for a given identifier .
20,733
public URI getLoginRequestURIForContext ( Context ctx ) { if ( ! ( ctx . getAuthenticationMethod ( ) instanceof FormBasedAuthenticationMethod ) ) return null ; FormBasedAuthenticationMethod method = ( FormBasedAuthenticationMethod ) ctx . getAuthenticationMethod ( ) ; try { return new URI ( method . getLoginRequestURL ( ) , false ) ; } catch ( URIException | NullPointerException e ) { e . printStackTrace ( ) ; return null ; } }
Gets the URI for the login request that corresponds to a given context if any .
20,734
public static String getLocalDisplayName ( String locale ) { String desc = "" + locale ; if ( locale != null ) { String [ ] langArray = locale . split ( "_" ) ; Locale loc = null ; if ( langArray . length == 1 ) { loc = new Locale ( langArray [ 0 ] ) ; } else if ( langArray . length == 2 ) { loc = new Locale ( langArray [ 0 ] , langArray [ 1 ] ) ; } else if ( langArray . length == 3 ) { loc = new Locale ( langArray [ 0 ] , langArray [ 1 ] , langArray [ 2 ] ) ; } if ( loc != null ) { desc = loc . getDisplayLanguage ( loc ) ; } } return desc ; }
Gets the name of the language of and for the given locale .
20,735
public void setScanFuzzerMessages ( boolean scanFuzzerMessages ) { this . scanFuzzerMessages = scanFuzzerMessages ; getConfig ( ) . setProperty ( SCAN_FUZZER_MESSAGES_KEY , scanFuzzerMessages ) ; setFuzzerOptin ( scanFuzzerMessages ) ; }
Sets whether or not the passive scan should be performed on traffic from the fuzzer .
20,736
public void addHttpSession ( HttpSession session ) { synchronized ( this . sessions ) { this . sessions . add ( session ) ; } this . model . addHttpSession ( session ) ; }
Adds a new http session to this site .
20,737
public void removeHttpSession ( HttpSession session ) { if ( session == activeSession ) { activeSession = null ; } synchronized ( this . sessions ) { this . sessions . remove ( session ) ; } this . model . removeHttpSession ( session ) ; session . invalidate ( ) ; }
Removes an existing session .
20,738
public void setActiveSession ( HttpSession activeSession ) { if ( log . isInfoEnabled ( ) ) { log . info ( "Setting new active session for site '" + site + "': " + activeSession ) ; } if ( activeSession == null ) { throw new IllegalArgumentException ( "When settting an active session, a non-null session has to be provided." ) ; } if ( this . activeSession == activeSession ) { return ; } if ( this . activeSession != null ) { this . activeSession . setActive ( false ) ; if ( this . activeSession . getTokenValuesCount ( ) == 0 ) { this . removeHttpSession ( this . activeSession ) ; } else { model . fireHttpSessionUpdated ( this . activeSession ) ; } } this . activeSession = activeSession ; activeSession . setActive ( true ) ; model . fireHttpSessionUpdated ( activeSession ) ; }
Sets the active session .
20,739
public void unsetActiveSession ( ) { if ( log . isInfoEnabled ( ) ) { log . info ( "Setting no active session for site '" + site + "'." ) ; } if ( this . activeSession != null ) { this . activeSession . setActive ( false ) ; if ( this . activeSession . getTokenValuesCount ( ) == 0 ) { this . removeHttpSession ( this . activeSession ) ; } else { model . fireHttpSessionUpdated ( this . activeSession ) ; } this . activeSession = null ; } }
Unset any active session for this site .
20,740
public void processHttpRequestMessage ( HttpMessage message ) { HttpSessionTokensSet siteTokensSet = extension . getHttpSessionTokensSet ( getSite ( ) ) ; if ( siteTokensSet == null ) { log . debug ( "No session tokens for: " + this . getSite ( ) ) ; return ; } List < HttpCookie > requestCookies = message . getRequestHeader ( ) . getHttpCookies ( ) ; HttpSession session = getMatchingHttpSession ( requestCookies , siteTokensSet ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Matching session for request message (for site " + getSite ( ) + "): " + session ) ; } if ( activeSession != null && activeSession != session ) { CookieBasedSessionManagementHelper . processMessageToMatchSession ( message , requestCookies , activeSession ) ; } else { if ( activeSession == session ) { log . debug ( "Session of request message is the same as the active session, so no request changes needed." ) ; } else { log . debug ( "No active session is selected." ) ; } message . setHttpSession ( session ) ; } }
Process the http request message before being sent .
20,741
private HttpSession getMatchingHttpSession ( List < HttpCookie > cookies , final HttpSessionTokensSet siteTokens ) { Collection < HttpSession > sessionsCopy ; synchronized ( sessions ) { sessionsCopy = new ArrayList < > ( sessions ) ; } return CookieBasedSessionManagementHelper . getMatchingHttpSession ( sessionsCopy , cookies , siteTokens ) ; }
Gets the matching http session for a particular message containing a list of cookies .
20,742
protected void cleanupSessionToken ( String token ) { if ( sessions . isEmpty ( ) ) { return ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Removing duplicates and cleaning up sessions for site - token: " + site + " - " + token ) ; } synchronized ( this . sessions ) { HttpSessionTokensSet siteTokensSet = extension . getHttpSessionTokensSet ( site ) ; if ( siteTokensSet == null ) { log . info ( "No more session tokens. Removing all sessions..." ) ; for ( HttpSession session : this . sessions ) { session . invalidate ( ) ; } this . sessions . clear ( ) ; this . activeSession = null ; this . model . removeAllElements ( ) ; return ; } Map < String , HttpSession > uniqueSession = new HashMap < > ( sessions . size ( ) ) ; List < HttpSession > toDelete = new LinkedList < > ( ) ; for ( HttpSession session : this . sessions ) { session . removeToken ( token ) ; if ( session . getTokenValuesCount ( ) == 0 && ! session . isActive ( ) ) { toDelete . add ( session ) ; continue ; } else { model . fireHttpSessionUpdated ( session ) ; } if ( uniqueSession . containsKey ( session . getTokenValuesString ( ) ) ) { HttpSession prevSession = uniqueSession . get ( session . getTokenValuesString ( ) ) ; if ( session . isActive ( ) ) { toDelete . add ( prevSession ) ; session . setMessagesMatched ( session . getMessagesMatched ( ) + prevSession . getMessagesMatched ( ) ) ; } else { toDelete . add ( session ) ; prevSession . setMessagesMatched ( session . getMessagesMatched ( ) + prevSession . getMessagesMatched ( ) ) ; } } else { uniqueSession . put ( session . getTokenValuesString ( ) , session ) ; } } if ( log . isInfoEnabled ( ) ) { log . info ( "Removing duplicate or empty sessions: " + toDelete ) ; } Iterator < HttpSession > it = toDelete . iterator ( ) ; while ( it . hasNext ( ) ) { HttpSession ses = it . next ( ) ; ses . invalidate ( ) ; sessions . remove ( ses ) ; model . removeHttpSession ( ses ) ; } } }
Cleans up the sessions eliminating the given session token .
20,743
public boolean renameHttpSession ( String oldName , String newName ) { if ( newName == null || newName . isEmpty ( ) ) { log . warn ( "Trying to rename session from " + oldName + " illegal name: " + newName ) ; return false ; } HttpSession session = getHttpSession ( oldName ) ; if ( session == null ) { return false ; } if ( getHttpSession ( newName ) != null ) { log . warn ( "Trying to rename session from " + oldName + " to already existing: " + newName ) ; return false ; } session . setName ( newName ) ; this . model . fireHttpSessionUpdated ( session ) ; return true ; }
Renames a http session making sure the new name is unique for the site .
20,744
private static int indexOf ( final String s , final char searchChar , final int beginIndex , final int endIndex ) { for ( int i = beginIndex ; i < endIndex ; i ++ ) { if ( s . charAt ( i ) == searchChar ) { return i ; } } return - 1 ; }
Returns the index within the specified string of the first occurrence of the specified search character .
20,745
void setExtensionsState ( Map < String , Boolean > extensionsState ) { if ( extensionsState == null ) { throw new IllegalArgumentException ( "Parameter extensionsState must not be null." ) ; } ( ( HierarchicalConfiguration ) getConfig ( ) ) . clearTree ( ALL_EXTENSIONS_KEY ) ; int enabledCount = 0 ; for ( Iterator < Map . Entry < String , Boolean > > it = extensionsState . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Map . Entry < String , Boolean > entry = it . next ( ) ; if ( entry . getKey ( ) == null || entry . getValue ( ) == null ) { continue ; } if ( ! entry . getValue ( ) ) { String elementBaseKey = ALL_EXTENSIONS_KEY + "(" + enabledCount + ")." ; getConfig ( ) . setProperty ( elementBaseKey + EXTENSION_NAME_KEY , entry . getKey ( ) ) ; getConfig ( ) . setProperty ( elementBaseKey + EXTENSION_ENABLED_KEY , Boolean . FALSE ) ; enabledCount ++ ; } } this . extensionsState = Collections . unmodifiableMap ( extensionsState ) ; }
Sets the extensions state to be saved in the configuration file .
20,746
public void centerFrame ( ) { final Dimension screenSize = Toolkit . getDefaultToolkit ( ) . getScreenSize ( ) ; final Dimension frameSize = this . getSize ( ) ; if ( frameSize . height > screenSize . height ) { frameSize . height = screenSize . height ; } if ( frameSize . width > screenSize . width ) { frameSize . width = screenSize . width ; } this . setLocation ( ( screenSize . width - frameSize . width ) / 2 , ( screenSize . height - frameSize . height ) / 2 ) ; }
Centre this frame .
20,747
private SimpleWindowState restoreWindowState ( ) { SimpleWindowState laststate = null ; final String statestr = preferences . get ( prefnzPrefix + PREF_WINDOW_STATE , null ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( "Restoring preference " + PREF_WINDOW_STATE + "=" + statestr ) ; if ( statestr != null ) { SimpleWindowState state = null ; try { state = SimpleWindowState . valueOf ( statestr ) ; } catch ( final IllegalArgumentException e ) { state = null ; } if ( state != null ) { switch ( state ) { case ICONFIED : this . setExtendedState ( Frame . ICONIFIED ) ; break ; case NORMAL : this . setExtendedState ( Frame . NORMAL ) ; break ; case MAXIMIZED : this . setExtendedState ( Frame . MAXIMIZED_BOTH ) ; break ; default : logger . error ( "Invalid window state (nothing will changed): " + statestr ) ; } } laststate = state ; } return laststate ; }
Loads and sets the last window state of the frame . Additionally the last state will be returned .
20,748
private void saveWindowSize ( Dimension size ) { if ( size != null ) { if ( getExtendedState ( ) == Frame . NORMAL ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Saving preference " + PREF_WINDOW_SIZE + "=" + size . width + "," + size . height ) ; this . preferences . put ( prefnzPrefix + PREF_WINDOW_SIZE , size . width + "," + size . height ) ; } else { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Preference " + PREF_WINDOW_SIZE + " not saved, cause window state is not 'normal'." ) ; } } }
Saves the size of this frame but only if window state is normal . If window state is iconfied or maximized the size is not saved!
20,749
private Dimension restoreWindowSize ( ) { Dimension result = null ; final String sizestr = preferences . get ( prefnzPrefix + PREF_WINDOW_SIZE , null ) ; if ( sizestr != null ) { int width = 0 ; int height = 0 ; final String [ ] sizes = sizestr . split ( "[,]" ) ; try { width = Integer . parseInt ( sizes [ 0 ] . trim ( ) ) ; height = Integer . parseInt ( sizes [ 1 ] . trim ( ) ) ; } catch ( final Exception e ) { } if ( width > 0 && height > 0 ) { result = new Dimension ( width , height ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( "Restoring preference " + PREF_WINDOW_SIZE + "=" + result . width + "," + result . height ) ; this . setSize ( result ) ; } } return result ; }
Loads and set the saved size preferences for this frame .
20,750
private void saveWindowLocation ( Point point ) { if ( point != null ) { if ( getExtendedState ( ) == Frame . NORMAL ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Saving preference " + PREF_WINDOW_POSITION + "=" + point . x + "," + point . y ) ; this . preferences . put ( prefnzPrefix + PREF_WINDOW_POSITION , point . x + "," + point . y ) ; } else { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Preference " + PREF_WINDOW_POSITION + " not saved, cause window state is not 'normal'." ) ; } } }
Saves the location of this frame but only if window state is normal . If window state is iconfied or maximized the location is not saved!
20,751
private Point restoreWindowLocation ( ) { Point result = null ; final String sizestr = preferences . get ( prefnzPrefix + PREF_WINDOW_POSITION , null ) ; if ( sizestr != null ) { int x = 0 ; int y = 0 ; final String [ ] sizes = sizestr . split ( "[,]" ) ; try { x = Integer . parseInt ( sizes [ 0 ] . trim ( ) ) ; y = Integer . parseInt ( sizes [ 1 ] . trim ( ) ) ; } catch ( final Exception e ) { } if ( x > 0 && y > 0 ) { result = new Point ( x , y ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( "Restoring preference " + PREF_WINDOW_POSITION + "=" + result . x + "," + result . y ) ; this . setLocation ( result ) ; } } return result ; }
Loads and set the saved position preferences for this frame .
20,752
public boolean includesAny ( Tech ... techs ) { if ( techs == null || techs . length == 0 ) { return false ; } for ( Tech tech : techs ) { if ( includes ( tech ) ) { return true ; } } return false ; }
Tells whether or not any of the given technologies is included .
20,753
public void print ( ) { System . out . println ( "TechSet: " + this . hashCode ( ) ) ; for ( Tech tech : includeTech ) { System . out . println ( "\tInclude: " + tech ) ; } for ( Tech tech : excludeTech ) { System . out . println ( "\tExclude: " + tech ) ; } }
Useful for debuging ; )
20,754
public ImageIcon getIcon ( ) { if ( confidence == Alert . CONFIDENCE_FALSE_POSITIVE ) { return DisplayUtils . getScaledIcon ( Constant . OK_FLAG_IMAGE_URL ) ; } switch ( risk ) { case Alert . RISK_INFO : return DisplayUtils . getScaledIcon ( Constant . INFO_FLAG_IMAGE_URL ) ; case Alert . RISK_LOW : return DisplayUtils . getScaledIcon ( Constant . LOW_FLAG_IMAGE_URL ) ; case Alert . RISK_MEDIUM : return DisplayUtils . getScaledIcon ( Constant . MED_FLAG_IMAGE_URL ) ; case Alert . RISK_HIGH : return DisplayUtils . getScaledIcon ( Constant . HIGH_FLAG_IMAGE_URL ) ; } return null ; }
Gets the correctly scaled icon for this alert .
20,755
private boolean notifyListenerRequestSend ( HttpMessage httpMessage ) { ProxyListener listener = null ; List < ProxyListener > listenerList = parentServer . getListenerList ( ) ; for ( int i = 0 ; i < listenerList . size ( ) ; i ++ ) { listener = listenerList . get ( i ) ; try { if ( ! listener . onHttpRequestSend ( httpMessage ) ) { return false ; } } catch ( Exception e ) { log . error ( "An error occurred while notifying listener:" , e ) ; } } return true ; }
Go through each observers to process a request in each observers . The method can be modified in each observers .
20,756
public void setIncludeInContextRegexs ( List < String > includeRegexs ) { validateRegexs ( includeRegexs ) ; if ( includeInRegexs . size ( ) == includeRegexs . size ( ) ) { boolean changed = false ; for ( int i = 0 ; i < includeInRegexs . size ( ) ; i ++ ) { if ( ! includeInRegexs . get ( i ) . equals ( includeRegexs . get ( i ) ) ) { changed = true ; break ; } } if ( ! changed ) { return ; } } includeInRegexs . clear ( ) ; includeInPatterns . clear ( ) ; for ( String url : includeRegexs ) { url = url . trim ( ) ; if ( url . length ( ) > 0 ) { Pattern p = Pattern . compile ( url , Pattern . CASE_INSENSITIVE ) ; includeInRegexs . add ( url ) ; includeInPatterns . add ( p ) ; } } }
Sets the regular expressions used to include a URL in context .
20,757
public void setExcludeFromContextRegexs ( List < String > excludeRegexs ) { validateRegexs ( excludeRegexs ) ; if ( excludeFromRegexs . size ( ) == excludeRegexs . size ( ) ) { boolean changed = false ; for ( int i = 0 ; i < excludeFromRegexs . size ( ) ; i ++ ) { if ( ! excludeFromRegexs . get ( i ) . equals ( excludeRegexs . get ( i ) ) ) { changed = true ; break ; } } if ( ! changed ) { return ; } } excludeFromRegexs . clear ( ) ; excludeFromPatterns . clear ( ) ; for ( String url : excludeRegexs ) { url = url . trim ( ) ; if ( url . length ( ) > 0 ) { Pattern p = Pattern . compile ( url , Pattern . CASE_INSENSITIVE ) ; excludeFromPatterns . add ( p ) ; excludeFromRegexs . add ( url ) ; } } }
Sets the regular expressions used to exclude a URL from the context .
20,758
public void setName ( String name ) { if ( name == null || name . isEmpty ( ) ) { throw new IllegalContextNameException ( IllegalContextNameException . Reason . EMPTY_NAME , "The context name must not be null nor empty." ) ; } this . name = name ; }
Sets the name of the context .
20,759
private List < SiteNode > getChildren ( SiteNode siteNode ) { int childCount = siteNode . getChildCount ( ) ; if ( childCount == 0 ) { return Collections . emptyList ( ) ; } List < SiteNode > children = new ArrayList < > ( childCount ) ; for ( int i = 0 ; i < childCount ; i ++ ) { children . add ( ( SiteNode ) siteNode . getChildAt ( i ) ) ; } return children ; }
Gets the child nodes of the given site node .
20,760
public Context duplicate ( ) { Context newContext = new Context ( session , getIndex ( ) ) ; newContext . description = this . description ; newContext . name = this . name ; newContext . includeInRegexs = new ArrayList < > ( this . includeInRegexs ) ; newContext . includeInPatterns = new ArrayList < > ( this . includeInPatterns ) ; newContext . excludeFromRegexs = new ArrayList < > ( this . excludeFromRegexs ) ; newContext . excludeFromPatterns = new ArrayList < > ( this . excludeFromPatterns ) ; newContext . inScope = this . inScope ; newContext . techSet = new TechSet ( this . techSet ) ; newContext . authenticationMethod = this . authenticationMethod . clone ( ) ; newContext . sessionManagementMethod = this . sessionManagementMethod . clone ( ) ; newContext . urlParamParser = this . urlParamParser . clone ( ) ; newContext . postParamParser = this . postParamParser . clone ( ) ; newContext . authorizationDetectionMethod = this . authorizationDetectionMethod . clone ( ) ; newContext . dataDrivenNodes = this . getDataDrivenNodes ( ) ; return newContext ; }
Creates a copy of the Context . The copy is deep with the exception of the TechSet .
20,761
private ZapMenuItem getMenuToolsFilter ( ) { if ( menuToolsFilter == null ) { menuToolsFilter = new ZapMenuItem ( "menu.tools.filter" ) ; menuToolsFilter . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent e ) { FilterDialog dialog = new FilterDialog ( getView ( ) . getMainFrame ( ) ) ; dialog . setAllFilters ( filterFactory . getAllFilter ( ) ) ; dialog . showDialog ( false ) ; boolean startThread = false ; for ( Filter filter : filterFactory . getAllFilter ( ) ) { if ( filter . isEnabled ( ) ) { startThread = true ; break ; } } if ( startThread ) { if ( timerFilterThread == null ) { timerFilterThread = new TimerFilterThread ( filterFactory . getAllFilter ( ) ) ; timerFilterThread . start ( ) ; } } else if ( timerFilterThread != null ) { timerFilterThread . setStopped ( ) ; timerFilterThread = null ; } } } ) ; } return menuToolsFilter ; }
This method initializes menuToolsFilter
20,762
public void destroy ( ) { if ( timerFilterThread != null ) { timerFilterThread . setStopped ( ) ; timerFilterThread = null ; } Filter filter = null ; for ( int i = 0 ; i < filterFactory . getAllFilter ( ) . size ( ) ; i ++ ) { filter = filterFactory . getAllFilter ( ) . get ( i ) ; try { filter . destroy ( ) ; } catch ( Exception e ) { } } }
Destroy every filter during extension destroy .
20,763
static boolean canBeLoaded ( Map < Class < ? extends Extension > , Extension > extensions , Extension extension ) { return canBeLoaded ( extensions , extension , new ArrayList < > ( ) ) ; }
Relax visibility to ease the tests .
20,764
private javax . swing . JPanel getPanelCommand ( ) { if ( panelCommand == null ) { panelCommand = new javax . swing . JPanel ( ) ; panelCommand . setLayout ( new java . awt . GridBagLayout ( ) ) ; panelCommand . setName ( Constant . messages . getString ( "httpsessions.panel.title" ) ) ; GridBagConstraints toolbarGridBag = new GridBagConstraints ( ) ; GridBagConstraints workPaneGridBag = new GridBagConstraints ( ) ; toolbarGridBag . gridx = 0 ; toolbarGridBag . gridy = 0 ; toolbarGridBag . weightx = 1.0d ; toolbarGridBag . insets = new java . awt . Insets ( 2 , 2 , 2 , 2 ) ; toolbarGridBag . anchor = java . awt . GridBagConstraints . NORTHWEST ; toolbarGridBag . fill = java . awt . GridBagConstraints . HORIZONTAL ; workPaneGridBag . gridx = 0 ; workPaneGridBag . gridy = 1 ; workPaneGridBag . weightx = 1.0 ; workPaneGridBag . weighty = 1.0 ; workPaneGridBag . insets = new java . awt . Insets ( 0 , 0 , 0 , 0 ) ; workPaneGridBag . anchor = java . awt . GridBagConstraints . NORTHWEST ; workPaneGridBag . fill = java . awt . GridBagConstraints . BOTH ; panelCommand . add ( this . getPanelToolbar ( ) , toolbarGridBag ) ; panelCommand . add ( getWorkPane ( ) , workPaneGridBag ) ; } return panelCommand ; }
This method initializes the main panel .
20,765
private JButton getNewSessionButton ( ) { if ( newSessionButton == null ) { newSessionButton = new JButton ( ) ; newSessionButton . setText ( Constant . messages . getString ( "httpsessions.toolbar.newsession.label" ) ) ; newSessionButton . setIcon ( DisplayUtils . getScaledIcon ( new ImageIcon ( HttpSessionsPanel . class . getResource ( "/resource/icon/16/103.png" ) ) ) ) ; newSessionButton . setToolTipText ( Constant . messages . getString ( "httpsessions.toolbar.newsession.tooltip" ) ) ; newSessionButton . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { HttpSessionsSite site = getCurrentHttpSessionSite ( ) ; if ( site != null ) { site . createEmptySession ( ) ; } } } ) ; } return newSessionButton ; }
Gets the new session button .
20,766
private javax . swing . JToolBar getPanelToolbar ( ) { if ( panelToolbar == null ) { panelToolbar = new javax . swing . JToolBar ( ) ; panelToolbar . setLayout ( new java . awt . GridBagLayout ( ) ) ; panelToolbar . setEnabled ( true ) ; panelToolbar . setFloatable ( false ) ; panelToolbar . setRollover ( true ) ; panelToolbar . setPreferredSize ( new java . awt . Dimension ( 800 , 30 ) ) ; panelToolbar . setName ( "HttpSessionToolbar" ) ; GridBagConstraints labelGridBag = new GridBagConstraints ( ) ; GridBagConstraints siteSelectGridBag = new GridBagConstraints ( ) ; GridBagConstraints newSessionGridBag = new GridBagConstraints ( ) ; GridBagConstraints emptyGridBag = new GridBagConstraints ( ) ; GridBagConstraints optionsGridBag = new GridBagConstraints ( ) ; GridBagConstraints exportButtonGbc = new GridBagConstraints ( ) ; labelGridBag . gridx = 0 ; labelGridBag . gridy = 0 ; labelGridBag . insets = new java . awt . Insets ( 0 , 0 , 0 , 0 ) ; labelGridBag . anchor = java . awt . GridBagConstraints . WEST ; siteSelectGridBag . gridx = 1 ; siteSelectGridBag . gridy = 0 ; siteSelectGridBag . insets = new java . awt . Insets ( 0 , 0 , 0 , 0 ) ; siteSelectGridBag . anchor = java . awt . GridBagConstraints . WEST ; newSessionGridBag . gridx = 2 ; newSessionGridBag . gridy = 0 ; newSessionGridBag . insets = new java . awt . Insets ( 0 , 0 , 0 , 0 ) ; newSessionGridBag . anchor = java . awt . GridBagConstraints . WEST ; exportButtonGbc . gridx = 3 ; exportButtonGbc . gridy = 0 ; exportButtonGbc . insets = new java . awt . Insets ( 0 , 0 , 0 , 0 ) ; exportButtonGbc . anchor = java . awt . GridBagConstraints . WEST ; emptyGridBag . gridx = 4 ; emptyGridBag . gridy = 0 ; emptyGridBag . weightx = 1.0 ; emptyGridBag . weighty = 1.0 ; emptyGridBag . insets = new java . awt . Insets ( 0 , 0 , 0 , 0 ) ; emptyGridBag . anchor = java . awt . GridBagConstraints . WEST ; emptyGridBag . fill = java . awt . GridBagConstraints . HORIZONTAL ; optionsGridBag . gridx = 5 ; optionsGridBag . gridy = 0 ; optionsGridBag . insets = new java . awt . Insets ( 0 , 0 , 0 , 0 ) ; optionsGridBag . anchor = java . awt . GridBagConstraints . EAST ; JLabel label = new JLabel ( Constant . messages . getString ( "httpsessions.toolbar.site.label" ) ) ; panelToolbar . add ( label , labelGridBag ) ; panelToolbar . add ( getSiteSelect ( ) , siteSelectGridBag ) ; panelToolbar . add ( getNewSessionButton ( ) , newSessionGridBag ) ; panelToolbar . add ( getExportButton ( ) , exportButtonGbc ) ; panelToolbar . add ( getOptionsButton ( ) , optionsGridBag ) ; panelToolbar . add ( new JLabel ( ) , emptyGridBag ) ; } return panelToolbar ; }
Gets the panel s toolbar .
20,767
private JScrollPane getWorkPane ( ) { if ( jScrollPane == null ) { jScrollPane = new JScrollPane ( ) ; jScrollPane . setViewportView ( getHttpSessionsTable ( ) ) ; } return jScrollPane ; }
Gets the work pane where data is shown .
20,768
private void setSessionsTableColumnSizes ( ) { sessionsTable . getColumnModel ( ) . getColumn ( 0 ) . setMinWidth ( 60 ) ; sessionsTable . getColumnModel ( ) . getColumn ( 0 ) . setPreferredWidth ( 60 ) ; sessionsTable . getColumnModel ( ) . getColumn ( 1 ) . setMinWidth ( 120 ) ; sessionsTable . getColumnModel ( ) . getColumn ( 1 ) . setPreferredWidth ( 200 ) ; sessionsTable . getColumnModel ( ) . getColumn ( 3 ) . setMinWidth ( 100 ) ; sessionsTable . getColumnModel ( ) . getColumn ( 3 ) . setPreferredWidth ( 150 ) ; }
Sets the sessions table column sizes .
20,769
private JXTable getHttpSessionsTable ( ) { if ( sessionsTable == null ) { sessionsTable = new JXTable ( sessionsModel ) ; sessionsTable . setColumnSelectionAllowed ( false ) ; sessionsTable . setCellSelectionEnabled ( false ) ; sessionsTable . setRowSelectionAllowed ( true ) ; sessionsTable . setAutoCreateRowSorter ( true ) ; sessionsTable . setColumnControlVisible ( true ) ; sessionsTable . setAutoCreateColumnsFromModel ( false ) ; sessionsTable . getColumnExt ( 0 ) . setCellRenderer ( new DefaultTableRenderer ( new MappedValue ( StringValues . EMPTY , IconValues . NONE ) , JLabel . CENTER ) ) ; sessionsTable . getColumnExt ( 0 ) . setHighlighters ( new ActiveSessionIconHighlighter ( 0 ) ) ; this . setSessionsTableColumnSizes ( ) ; sessionsTable . setName ( PANEL_NAME ) ; sessionsTable . setDoubleBuffered ( true ) ; sessionsTable . setSelectionMode ( javax . swing . ListSelectionModel . SINGLE_SELECTION ) ; sessionsTable . addMouseListener ( new java . awt . event . MouseAdapter ( ) { public void mousePressed ( java . awt . event . MouseEvent e ) { showPopupMenuIfTriggered ( e ) ; } public void mouseReleased ( java . awt . event . MouseEvent e ) { showPopupMenuIfTriggered ( e ) ; } private void showPopupMenuIfTriggered ( java . awt . event . MouseEvent e ) { if ( e . isPopupTrigger ( ) ) { int row = sessionsTable . rowAtPoint ( e . getPoint ( ) ) ; if ( row < 0 || ! sessionsTable . getSelectionModel ( ) . isSelectedIndex ( row ) ) { sessionsTable . getSelectionModel ( ) . clearSelection ( ) ; if ( row >= 0 ) { sessionsTable . getSelectionModel ( ) . setSelectionInterval ( row , row ) ; } } View . getSingleton ( ) . getPopupMenu ( ) . show ( e . getComponent ( ) , e . getX ( ) , e . getY ( ) ) ; } } } ) ; } return sessionsTable ; }
Gets the http sessions table .
20,770
private JComboBox < String > getSiteSelect ( ) { if ( siteSelect == null ) { siteSelect = new JComboBox < > ( siteModel ) ; siteSelect . addItem ( Constant . messages . getString ( "httpsessions.toolbar.site.select" ) ) ; siteSelect . setSelectedIndex ( 0 ) ; siteSelect . addItemListener ( new ItemListener ( ) { public void itemStateChanged ( ItemEvent e ) { if ( ItemEvent . SELECTED == e . getStateChange ( ) ) { if ( siteSelect . getSelectedIndex ( ) > 0 ) { siteSelected ( ( String ) e . getItem ( ) ) ; } else if ( siteModel . getSize ( ) > 1 ) { siteModel . setSelectedItem ( siteModel . getElementAt ( 1 ) ) ; } } } } ) ; } return siteSelect ; }
Gets the site select ComboBox .
20,771
private void siteSelected ( String site ) { if ( ! site . equals ( currentSite ) ) { this . sessionsModel = extension . getHttpSessionsSite ( site ) . getModel ( ) ; this . getHttpSessionsTable ( ) . setModel ( this . sessionsModel ) ; this . setSessionsTableColumnSizes ( ) ; currentSite = site ; } }
A new Site was selected .
20,772
public void nodeSelected ( SiteNode node ) { if ( node != null ) { siteModel . setSelectedItem ( ScanPanel . cleanSiteName ( node , true ) ) ; } }
Node selected .
20,773
public void reset ( ) { currentSite = null ; siteModel . removeAllElements ( ) ; siteModel . addElement ( Constant . messages . getString ( "httpsessions.toolbar.site.select" ) ) ; sessionsModel = new HttpSessionsTableModel ( null ) ; getHttpSessionsTable ( ) . setModel ( sessionsModel ) ; }
Reset the panel .
20,774
public HttpSession getSelectedSession ( ) { final int selectedRow = this . sessionsTable . getSelectedRow ( ) ; if ( selectedRow == - 1 ) { return null ; } final int rowIndex = sessionsTable . convertRowIndexToModel ( selectedRow ) ; return this . sessionsModel . getHttpSessionAt ( rowIndex ) ; }
Gets the selected http session .
20,775
public void setEnabled ( boolean enabled ) { if ( this . enabled != enabled ) { this . enabled = enabled ; setProperty ( "enabled" , Boolean . toString ( enabled ) ) ; if ( enabled && getAlertThreshold ( ) == AlertThreshold . OFF ) { setAlertThreshold ( AlertThreshold . DEFAULT ) ; } } }
Enable this test
20,776
public int compareTo ( Object obj ) { int result = - 1 ; if ( obj instanceof AbstractPlugin ) { AbstractPlugin test = ( AbstractPlugin ) obj ; if ( getId ( ) < test . getId ( ) ) { result = - 1 ; } else if ( getId ( ) > test . getId ( ) ) { result = 1 ; } else { result = 0 ; } } return result ; }
Compare if 2 plugin is the same .
20,777
protected boolean matchHeaderPattern ( HttpMessage msg , String header , Pattern pattern ) { if ( msg . getResponseHeader ( ) . isEmpty ( ) ) { return false ; } String val = msg . getResponseHeader ( ) . getHeader ( header ) ; if ( val == null ) { return false ; } Matcher matcher = pattern . matcher ( val ) ; return matcher . find ( ) ; }
Check if the given pattern can be found in the header .
20,778
protected boolean matchBodyPattern ( HttpMessage msg , Pattern pattern , StringBuilder sb ) { Matcher matcher = pattern . matcher ( msg . getResponseBody ( ) . toString ( ) ) ; boolean result = matcher . find ( ) ; if ( result ) { if ( sb != null ) { sb . append ( matcher . group ( ) ) ; } } return result ; }
Check if the given pattern can be found in the msg body . If the supplied StringBuilder is not null append the result to the StringBuilder .
20,779
public void setHost ( String host ) throws IllegalStateException { if ( host == null ) { throw new IllegalArgumentException ( "host parameter is null" ) ; } assertNotOpen ( ) ; hostName = host ; }
Sets the host to connect to .
20,780
protected boolean isStale ( ) throws IOException { boolean isStale = true ; if ( isOpen ) { isStale = false ; try { if ( inputStream . available ( ) <= 0 ) { try { socket . setSoTimeout ( 1 ) ; inputStream . mark ( 1 ) ; int byteRead = inputStream . read ( ) ; if ( byteRead == - 1 ) { isStale = true ; } else { inputStream . reset ( ) ; } } finally { socket . setSoTimeout ( this . params . getSoTimeout ( ) ) ; } } } catch ( InterruptedIOException e ) { if ( ! ExceptionUtil . isSocketTimeoutException ( e ) ) { throw e ; } } catch ( IOException e ) { LOG . debug ( "An error occurred while reading from the socket, is appears to be stale" , e ) ; isStale = true ; } } return isStale ; }
Determines whether this connection is stale which is to say that either it is no longer open or an attempt to read the connection would fail .
20,781
public void tunnelCreated ( ) throws IllegalStateException , IOException { LOG . trace ( "enter HttpConnection.tunnelCreated()" ) ; if ( ! isTunnelRequired ( ) ) { throw new IllegalStateException ( "Connection must be secure " + "and proxied or a tunnel requested to use this feature" ) ; } if ( usingSecureSocket ) { throw new IllegalStateException ( "Already using a secure socket" ) ; } if ( isSecure ( ) ) { SecureProtocolSocketFactory socketFactory = ( SecureProtocolSocketFactory ) protocolInUse . getSocketFactory ( ) ; socket = socketFactory . createSocket ( socket , hostName , portNumber , true ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Secure tunnel to " + this . hostName + ":" + this . portNumber ) ; } int sndBufSize = this . params . getSendBufferSize ( ) ; if ( sndBufSize >= 0 ) { socket . setSendBufferSize ( sndBufSize ) ; } int rcvBufSize = this . params . getReceiveBufferSize ( ) ; if ( rcvBufSize >= 0 ) { socket . setReceiveBufferSize ( rcvBufSize ) ; } int outbuffersize = socket . getSendBufferSize ( ) ; if ( outbuffersize > 2048 ) { outbuffersize = 2048 ; } int inbuffersize = socket . getReceiveBufferSize ( ) ; if ( inbuffersize > 2048 ) { inbuffersize = 2048 ; } inputStream = new BufferedInputStream ( socket . getInputStream ( ) , inbuffersize ) ; outputStream = new BufferedOutputStream ( socket . getOutputStream ( ) , outbuffersize ) ; usingSecureSocket = true ; tunnelEstablished = true ; }
Instructs the proxy to establish a secure tunnel to the host . The socket will be switched to the secure socket . Subsequent communication is done via the secure socket . The method can only be called once on a proxied secure connection .
20,782
public boolean isResponseAvailable ( int timeout ) throws IOException { LOG . trace ( "enter HttpConnection.isResponseAvailable(int)" ) ; if ( ! this . isOpen ) { return false ; } boolean result = false ; if ( this . inputStream . available ( ) > 0 ) { result = true ; } else { try { this . socket . setSoTimeout ( timeout ) ; inputStream . mark ( 1 ) ; int byteRead = inputStream . read ( ) ; if ( byteRead != - 1 ) { inputStream . reset ( ) ; LOG . debug ( "Input data available" ) ; result = true ; } else { LOG . debug ( "Input data not available" ) ; } } catch ( InterruptedIOException e ) { if ( ! ExceptionUtil . isSocketTimeoutException ( e ) ) { throw e ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Input data not available after " + timeout + " ms" ) ; } } finally { try { socket . setSoTimeout ( this . params . getSoTimeout ( ) ) ; } catch ( IOException ioe ) { LOG . debug ( "An error ocurred while resetting soTimeout, we will assume that" + " no response is available." , ioe ) ; result = false ; } } } return result ; }
Tests if input data becomes available within the given period time in milliseconds .
20,783
public void write ( byte [ ] data ) throws IOException , IllegalStateException { LOG . trace ( "enter HttpConnection.write(byte[])" ) ; this . write ( data , 0 , data . length ) ; }
Writes the specified bytes to the output stream .
20,784
public void releaseConnection ( ) { LOG . trace ( "enter HttpConnection.releaseConnection()" ) ; if ( locked ) { LOG . debug ( "Connection is locked. Call to releaseConnection() ignored." ) ; } else if ( httpConnectionManager != null ) { LOG . debug ( "Releasing connection back to connection manager." ) ; httpConnectionManager . releaseConnection ( this ) ; } else { LOG . warn ( "HttpConnectionManager is null. Connection cannot be released." ) ; } }
Releases the connection . If the connection is locked or does not have a connection manager associated with it this method has no effect . Note that it is completely safe to call this method multiple times .
20,785
protected void closeSocketAndStreams ( ) { LOG . trace ( "enter HttpConnection.closeSockedAndStreams()" ) ; isOpen = false ; lastResponseInputStream = null ; if ( null != outputStream ) { OutputStream temp = outputStream ; outputStream = null ; try { temp . close ( ) ; } catch ( Exception ex ) { LOG . debug ( "Exception caught when closing output" , ex ) ; } } if ( null != inputStream ) { InputStream temp = inputStream ; inputStream = null ; try { temp . close ( ) ; } catch ( Exception ex ) { LOG . debug ( "Exception caught when closing input" , ex ) ; } } if ( null != socket ) { Socket temp = socket ; socket = null ; try { temp . close ( ) ; } catch ( Exception ex ) { LOG . debug ( "Exception caught when closing socket" , ex ) ; } } tunnelEstablished = false ; usingSecureSocket = false ; }
Closes everything out .
20,786
private KeyPair createKeyPair ( ) throws NoSuchAlgorithmException { final KeyPairGenerator keyGen = KeyPairGenerator . getInstance ( "RSA" ) ; final SecureRandom random = SecureRandom . getInstance ( "SHA1PRNG" ) ; random . setSeed ( Long . toString ( System . currentTimeMillis ( ) ) . getBytes ( ) ) ; keyGen . initialize ( 2048 , random ) ; final KeyPair keypair = keyGen . generateKeyPair ( ) ; return keypair ; }
Generates a 2048 bit RSA key pair using SHA1PRNG .
20,787
public void cleanExpiredCallbacks ( ) { long now = System . currentTimeMillis ( ) ; synchronized ( regCallbacks ) { Iterator < Map . Entry < String , RegisteredCallback > > it = regCallbacks . entrySet ( ) . iterator ( ) ; Map . Entry < String , RegisteredCallback > entry ; while ( it . hasNext ( ) ) { entry = it . next ( ) ; if ( now - entry . getValue ( ) . getTimestamp ( ) > CALLBACK_EXPIRE_TIME ) { it . remove ( ) ; } } } }
Expire callbacks cleaning method . When called it remove from the received callbacks list all the sent challenge which haven t received any answer till now according to an expiring constraint . Currently the cleaning is done for every new inserting and every received callback but it can be done also with a scheduled cleaning thread if the number of items is memory and time consuming ... Maybe to be understood in the future .
20,788
public String getCallbackUrl ( String challenge ) { return "http://" + Model . getSingleton ( ) . getOptionsParam ( ) . getProxyParam ( ) . getProxyIp ( ) + ":" + Model . getSingleton ( ) . getOptionsParam ( ) . getProxyParam ( ) . getProxyPort ( ) + "/" + getPrefix ( ) + "/" + challenge ; }
Gets the ZAP API URL to a challenge endpoint .
20,789
public HttpMessage handleShortcut ( HttpMessage msg ) throws ApiException { try { String path = msg . getRequestHeader ( ) . getURI ( ) . getPath ( ) ; String challenge = path . substring ( path . indexOf ( getPrefix ( ) ) + getPrefix ( ) . length ( ) + 1 ) ; if ( challenge . charAt ( challenge . length ( ) - 1 ) == '/' ) { challenge = challenge . substring ( 0 , challenge . length ( ) - 1 ) ; } RegisteredCallback rcback = regCallbacks . get ( challenge ) ; String response ; if ( rcback != null ) { rcback . getPlugin ( ) . notifyCallback ( challenge , rcback . getAttackMessage ( ) ) ; response = API_RESPONSE_OK ; regCallbacks . remove ( challenge ) ; } else { response = API_RESPONSE_KO ; cleanExpiredCallbacks ( ) ; } msg . setResponseHeader ( API . getDefaultResponseHeader ( "text/html" , response . length ( ) ) ) ; msg . getResponseHeader ( ) . setHeader ( "Access-Control-Allow-Origin" , "*" ) ; msg . setResponseBody ( response ) ; } catch ( URIException | HttpMalformedHeaderException e ) { logger . warn ( e . getMessage ( ) , e ) ; } return msg ; }
Handles the given message which might contain a challenge request .
20,790
public void registerCallback ( String challenge , ChallengeCallbackPlugin plugin , HttpMessage attack ) { cleanExpiredCallbacks ( ) ; regCallbacks . put ( challenge , new RegisteredCallback ( plugin , attack ) ) ; }
Registers a new ZAP API challenge .
20,791
public void setConfirmDropMessage ( boolean confirmDrop ) { if ( confirmDropMessage != confirmDrop ) { this . confirmDropMessage = confirmDrop ; getConfig ( ) . setProperty ( PARAM_CONFIRM_DROP_MESSAGE_KEY , confirmDrop ) ; } }
Sets whether the user should confirm the drop of the trapped message .
20,792
protected void notifyListenersDatabaseOpen ( Collection < DatabaseListener > listeners , DatabaseServer databaseServer ) throws DatabaseException { for ( DatabaseListener databaseListener : listeners ) { try { databaseListener . databaseOpen ( databaseServer ) ; } catch ( DatabaseUnsupportedException e ) { logger . error ( e . getMessage ( ) , e ) ; } } }
Notifies the given listeners that the given database server was opened .
20,793
public Component getTableCellRendererComponent ( JTable table , Object value , boolean isSelected , boolean hasFocus , int rowIndex , int vColIndex ) { if ( isSelected ) { } if ( hasFocus ) { } JComponent result = label ; if ( ! value . toString ( ) . equals ( "" ) ) { result = button ; ( ( JButton ) button ) . setText ( value . toString ( ) ) ; } return result ; }
using this renderer needs to be rendered .
20,794
public boolean isPermittedAddress ( String addr ) { if ( addr == null || addr . isEmpty ( ) ) { return false ; } for ( DomainMatcher permAddr : permittedAddressesEnabled ) { if ( permAddr . matches ( addr ) ) { return true ; } } return false ; }
Tells whether or not the given client address is allowed to access the API .
20,795
public void setPermittedAddresses ( List < DomainMatcher > addrs ) { if ( addrs == null || addrs . isEmpty ( ) ) { ( ( HierarchicalConfiguration ) getConfig ( ) ) . clearTree ( ADDRESS_KEY ) ; this . permittedAddresses = Collections . emptyList ( ) ; this . permittedAddressesEnabled = Collections . emptyList ( ) ; return ; } this . permittedAddresses = new ArrayList < > ( addrs ) ; ( ( HierarchicalConfiguration ) getConfig ( ) ) . clearTree ( ADDRESS_KEY ) ; int size = addrs . size ( ) ; ArrayList < DomainMatcher > enabledAddrs = new ArrayList < > ( size ) ; for ( int i = 0 ; i < size ; ++ i ) { String elementBaseKey = ADDRESS_KEY + "(" + i + ")." ; DomainMatcher addr = addrs . get ( i ) ; getConfig ( ) . setProperty ( elementBaseKey + ADDRESS_VALUE_KEY , addr . getValue ( ) ) ; getConfig ( ) . setProperty ( elementBaseKey + ADDRESS_REGEX_KEY , addr . isRegex ( ) ) ; getConfig ( ) . setProperty ( elementBaseKey + ADDRESS_ENABLED_KEY , addr . isEnabled ( ) ) ; if ( addr . isEnabled ( ) ) { enabledAddrs . add ( addr ) ; } } enabledAddrs . trimToSize ( ) ; this . permittedAddressesEnabled = enabledAddrs ; }
Sets the client addresses that will be allowed to access the API .
20,796
protected void pauseScan ( Context context ) { log . debug ( "Access Control pause on Context: " + context ) ; threadManager . getScannerThread ( context . getIndex ( ) ) . pauseScan ( ) ; }
Method called when the pause button is pressed . Base implementation forward the calls to the Scanner Thread that corresponds to the provided Context and obtained via the Thread Manager specified in the constructor .
20,797
protected void resumeScan ( Context context ) { log . debug ( "Access Control resume on Context: " + context ) ; threadManager . getScannerThread ( context . getIndex ( ) ) . resumeScan ( ) ; }
Method called when the resume button is pressed . Base implementation forward the calls to the Scanner Thread that corresponds to the provided Context and obtained via the Thread Manager specified in the constructor .
20,798
protected void stopScan ( Context context ) { log . debug ( "Access Control stop on Context: " + context ) ; threadManager . getScannerThread ( context . getIndex ( ) ) . stopScan ( ) ; }
Method called when the stop button is pressed . Base implementation forward the calls to the Scanner Thread that corresponds to the provided Context and obtained via the Thread Manager specified in the constructor .
20,799
private JTree getTreeParam ( ) { if ( treeParam == null ) { treeParam = new JTree ( ) ; treeParam . setModel ( getTreeModel ( ) ) ; treeParam . setShowsRootHandles ( true ) ; treeParam . setRootVisible ( true ) ; treeParam . addTreeSelectionListener ( new javax . swing . event . TreeSelectionListener ( ) { public void valueChanged ( javax . swing . event . TreeSelectionEvent e ) { DefaultMutableTreeNode node = ( DefaultMutableTreeNode ) getTreeParam ( ) . getLastSelectedPathComponent ( ) ; if ( node == null ) { return ; } String name = ( String ) node . getUserObject ( ) ; showParamPanel ( name ) ; } } ) ; DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer ( ) ; renderer . setLeafIcon ( null ) ; renderer . setOpenIcon ( null ) ; renderer . setClosedIcon ( null ) ; treeParam . setCellRenderer ( renderer ) ; treeParam . setRowHeight ( DisplayUtils . getScaledSize ( 18 ) ) ; treeParam . addMouseListener ( new MouseAdapter ( ) { public void mousePressed ( MouseEvent e ) { TreePath path = treeParam . getClosestPathForLocation ( e . getX ( ) , e . getY ( ) ) ; if ( path != null && ! treeParam . isPathSelected ( path ) ) { treeParam . setSelectionPath ( path ) ; } } } ) ; } return treeParam ; }
This method initializes treeParam