Search in sources :

Example 11 with Context

use of org.zaproxy.zap.model.Context in project zaproxy by zaproxy.

the class UsersAPI method handleApiAction.

@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
    log.debug("handleApiAction " + name + " " + params.toString());
    User user;
    Context context;
    switch(name) {
        case ACTION_NEW_USER:
            context = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID);
            String userName = ApiUtils.getNonEmptyStringParam(params, PARAM_USER_NAME);
            user = new User(context.getId(), userName);
            user.setAuthenticationCredentials(context.getAuthenticationMethod().createAuthenticationCredentials());
            extension.getContextUserAuthManager(context.getId()).addUser(user);
            context.save();
            return new ApiResponseElement(PARAM_USER_ID, String.valueOf(user.getId()));
        case ACTION_REMOVE_USER:
            context = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID);
            int userId = ApiUtils.getIntParam(params, PARAM_USER_ID);
            boolean deleted = extension.getContextUserAuthManager(context.getId()).removeUserById(userId);
            if (deleted) {
                context.save();
                return ApiResponseElement.OK;
            } else
                return ApiResponseElement.FAIL;
        case ACTION_SET_ENABLED:
            boolean enabled = false;
            try {
                enabled = params.getBoolean(PARAM_ENABLED);
            } catch (JSONException e) {
                throw new ApiException(Type.ILLEGAL_PARAMETER, PARAM_ENABLED + " - should be boolean");
            }
            user = getUser(params);
            user.setEnabled(enabled);
            user.getContext().save();
            return ApiResponseElement.OK;
        case ACTION_SET_NAME:
            String nameSN = params.getString(PARAM_USER_NAME);
            if (nameSN == null || nameSN.isEmpty())
                throw new ApiException(Type.MISSING_PARAMETER, PARAM_USER_NAME);
            user = getUser(params);
            user.setName(nameSN);
            user.getContext().save();
            return ApiResponseElement.OK;
        case ACTION_SET_AUTH_CREDENTIALS:
            // Prepare the params
            JSONObject actionParams;
            if (params.has(PARAM_CREDENTIALS_CONFIG_PARAMS))
                actionParams = API.getParams(params.getString(PARAM_CREDENTIALS_CONFIG_PARAMS));
            else
                actionParams = new JSONObject();
            context = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID);
            actionParams.put(PARAM_CONTEXT_ID, context.getId());
            actionParams.put(PARAM_USER_ID, getUserId(params));
            // Run the method
            ApiDynamicActionImplementor a = loadedAuthenticationMethodActions.get(context.getAuthenticationMethod().getType().getUniqueIdentifier());
            a.handleAction(actionParams);
            context.save();
            return ApiResponseElement.OK;
        case ACTION_AUTHENTICATE_AS_USER:
            user = getUser(params);
            int hId1 = user.getAuthenticationState().getLastAuthRequestHistoryId();
            user.authenticate();
            int hId2 = user.getAuthenticationState().getLastAuthRequestHistoryId();
            if (hId2 > hId1) {
                // Not all authentication methods result in an authentication request.
                // In theory we could get a different one if other reqs are being made, but this
                // is probably as safe as we can make it right now
                ExtensionHistory extHistory = Control.getSingleton().getExtensionLoader().getExtension(ExtensionHistory.class);
                if (extHistory != null) {
                    HistoryReference href = extHistory.getHistoryReference(hId2);
                    try {
                        HttpMessage authMsg = href.getHttpMessage();
                        ApiResponseSet<String> responseSet = ApiResponseConversionUtils.httpMessageToSet(hId2, authMsg);
                        responseSet.put("authSuccessful", Boolean.toString(user.getContext().getAuthenticationMethod().evaluateAuthRequest(authMsg, user.getAuthenticationState())));
                        return responseSet;
                    } catch (Exception e) {
                        log.error("Failed to read auth request from db " + hId2, e);
                        throw new ApiException(Type.INTERNAL_ERROR, e);
                    }
                }
            }
            return ApiResponseElement.OK;
        case ACTION_POLL_AS_USER:
            user = getUser(params);
            try {
                HttpMessage msg = user.getContext().getAuthenticationMethod().pollAsUser(user);
                int href = -1;
                if (msg.getHistoryRef() != null) {
                    href = msg.getHistoryRef().getHistoryId();
                }
                ApiResponseSet<String> responseSet = ApiResponseConversionUtils.httpMessageToSet(href, msg);
                responseSet.put("pollSuccessful", Boolean.toString(user.getContext().getAuthenticationMethod().evaluateAuthRequest(msg, user.getAuthenticationState())));
                return responseSet;
            } catch (IllegalArgumentException e) {
                throw new ApiException(Type.ILLEGAL_PARAMETER, PARAM_CONTEXT_ID);
            } catch (IOException e) {
                throw new ApiException(Type.INTERNAL_ERROR, e);
            }
        case ACTION_SET_AUTH_STATE:
            user = getUser(params);
            AuthenticationState state = user.getAuthenticationState();
            String lastPollResultStr = this.getParam(params, PARAM_LAST_POLL_RESULT, "");
            if (StringUtils.isNotBlank(lastPollResultStr)) {
                try {
                    state.setLastPollResult(Boolean.parseBoolean(lastPollResultStr));
                } catch (Exception e) {
                    throw new ApiException(Type.ILLEGAL_PARAMETER, PARAM_LAST_POLL_RESULT);
                }
            }
            String lastPollTimeStr = this.getParam(params, PARAM_LAST_POLL_TIME_IN_MS, "");
            if (StringUtils.isNotBlank(lastPollTimeStr)) {
                try {
                    long lastPollTime;
                    if (lastPollTimeStr.equals(TIME_NOW)) {
                        lastPollTime = System.currentTimeMillis();
                    } else {
                        lastPollTime = Long.parseLong(lastPollTimeStr);
                    }
                    state.setLastPollTime(lastPollTime);
                } catch (Exception e) {
                    throw new ApiException(Type.ILLEGAL_PARAMETER, PARAM_LAST_POLL_TIME_IN_MS);
                }
            }
            int reqsSinceLastPoll = this.getParam(params, PARAM_REQUESTS_SINCE_LAST_POLL, -1);
            if (reqsSinceLastPoll >= 0) {
                state.setRequestsSincePoll(reqsSinceLastPoll);
            }
            return ApiResponseElement.OK;
        case ACTION_SET_COOKIE:
            user = getUser(params);
            if (user.getAuthenticatedSession() == null) {
                user.setAuthenticatedSession(user.getContext().getSessionManagementMethod().createEmptyWebSession());
            }
            String cookiePath = this.getParam(params, PARAM_COOKIE_PATH, "");
            if (cookiePath.isEmpty()) {
                cookiePath = null;
            }
            user.getAuthenticatedSession().getHttpState().addCookie(new Cookie(params.getString(PARAM_COOKIE_DOMAIN), params.getString(PARAM_COOKIE_NAME), params.getString(PARAM_COOKIE_VALUE), cookiePath, // Setting this to a valid date means it never gets
            null, // returned :/
            this.getParam(params, PARAM_COOKIE_SECURE, false)));
            return ApiResponseElement.OK;
        default:
            throw new ApiException(Type.BAD_ACTION);
    }
}
Also used : Context(org.zaproxy.zap.model.Context) ApiDynamicActionImplementor(org.zaproxy.zap.extension.api.ApiDynamicActionImplementor) Cookie(org.apache.commons.httpclient.Cookie) User(org.zaproxy.zap.users.User) ExtensionHistory(org.parosproxy.paros.extension.history.ExtensionHistory) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) JSONException(net.sf.json.JSONException) ApiException(org.zaproxy.zap.extension.api.ApiException) IOException(java.io.IOException) AuthenticationState(org.zaproxy.zap.users.AuthenticationState) HistoryReference(org.parosproxy.paros.model.HistoryReference) JSONObject(net.sf.json.JSONObject) ApiResponseElement(org.zaproxy.zap.extension.api.ApiResponseElement) HttpMessage(org.parosproxy.paros.network.HttpMessage) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 12 with Context

use of org.zaproxy.zap.model.Context in project zaproxy by zaproxy.

the class ExtensionStdMenus method getPopupContextTreeMenuDelete.

private PopupContextTreeMenu getPopupContextTreeMenuDelete() {
    if (popupContextTreeMenuDelete == null) {
        popupContextTreeMenuDelete = new PopupContextTreeMenu();
        popupContextTreeMenuDelete.setAction(new DeleteContextAction() {

            private static final long serialVersionUID = 1L;

            @Override
            protected List<Context> getContexts() {
                List<Context> contexts = new ArrayList<>();
                for (Integer id : popupContextTreeMenuDelete.getContextIds()) {
                    contexts.add(Model.getSingleton().getSession().getContext(id));
                }
                return contexts;
            }

            @Override
            protected Context getContext() {
                return Model.getSingleton().getSession().getContext(popupContextTreeMenuDelete.getContextId());
            }
        });
        popupContextTreeMenuDelete.setText(Constant.messages.getString("context.delete.popup"));
    }
    return popupContextTreeMenuDelete;
}
Also used : Context(org.zaproxy.zap.model.Context) ArrayList(java.util.ArrayList) List(java.util.List) DeleteContextAction(org.zaproxy.zap.view.DeleteContextAction)

Example 13 with Context

use of org.zaproxy.zap.model.Context in project zaproxy by zaproxy.

the class ExtensionSessionManagementUnitTest method shouldImportContextWithCookieSessionMgmtType.

@Test
void shouldImportContextWithCookieSessionMgmtType() throws ConfigurationException {
    // Given
    Context context = mock(Context.class);
    Configuration config = new ZapXmlConfiguration();
    int sessMgmtTypeId = 0;
    config.addProperty(ExtensionSessionManagement.CONTEXT_CONFIG_SESSION_TYPE, sessMgmtTypeId);
    // When
    extSessMgmt.importContextData(context, config);
    // Then
    verify(context).setSessionManagementMethod(any(CookieBasedSessionManagementMethod.class));
}
Also used : Context(org.zaproxy.zap.model.Context) Configuration(org.apache.commons.configuration.Configuration) ZapXmlConfiguration(org.zaproxy.zap.utils.ZapXmlConfiguration) CookieBasedSessionManagementMethod(org.zaproxy.zap.session.CookieBasedSessionManagementMethodType.CookieBasedSessionManagementMethod) ZapXmlConfiguration(org.zaproxy.zap.utils.ZapXmlConfiguration) Test(org.junit.jupiter.api.Test) WithConfigsTest(org.zaproxy.zap.WithConfigsTest)

Example 14 with Context

use of org.zaproxy.zap.model.Context in project zaproxy by zaproxy.

the class ExtensionSessionManagementUnitTest method shouldImportContextWithNoSessionMgmtType.

@Test
void shouldImportContextWithNoSessionMgmtType() throws ConfigurationException {
    // Given
    Context context = mock(Context.class);
    Configuration config = new ZapXmlConfiguration();
    // When
    extSessMgmt.importContextData(context, config);
    // Then
    verify(context, times(0)).setSessionManagementMethod(any());
}
Also used : Context(org.zaproxy.zap.model.Context) Configuration(org.apache.commons.configuration.Configuration) ZapXmlConfiguration(org.zaproxy.zap.utils.ZapXmlConfiguration) ZapXmlConfiguration(org.zaproxy.zap.utils.ZapXmlConfiguration) Test(org.junit.jupiter.api.Test) WithConfigsTest(org.zaproxy.zap.WithConfigsTest)

Example 15 with Context

use of org.zaproxy.zap.model.Context in project zaproxy by zaproxy.

the class ContextAuthenticationPanel method saveContextData.

@Override
public void saveContextData(Session session) throws Exception {
    saveMethod();
    Context context = session.getContext(getContextId());
    // reflected in the UI
    if (context.getAuthenticationMethod() != null)
        if (!shownMethodType.isTypeForMethod(context.getAuthenticationMethod()))
            context.getAuthenticationMethod().onMethodDiscarded();
    context.setAuthenticationMethod(selectedAuthenticationMethod);
    // Notify the newly saved method that it's being persisted so the changes can be
    // reflected in the UI
    selectedAuthenticationMethod.onMethodPersisted();
}
Also used : Context(org.zaproxy.zap.model.Context)

Aggregations

Context (org.zaproxy.zap.model.Context)89 ApiException (org.zaproxy.zap.extension.api.ApiException)22 Test (org.junit.jupiter.api.Test)21 ZapXmlConfiguration (org.zaproxy.zap.utils.ZapXmlConfiguration)17 WithConfigsTest (org.zaproxy.zap.WithConfigsTest)16 User (org.zaproxy.zap.users.User)15 JSONObject (net.sf.json.JSONObject)14 Configuration (org.apache.commons.configuration.Configuration)14 Session (org.parosproxy.paros.model.Session)14 ApiDynamicActionImplementor (org.zaproxy.zap.extension.api.ApiDynamicActionImplementor)13 RecordContext (org.parosproxy.paros.db.RecordContext)12 DatabaseException (org.parosproxy.paros.db.DatabaseException)10 ConfigurationException (org.apache.commons.configuration.ConfigurationException)9 HttpMessage (org.parosproxy.paros.network.HttpMessage)9 ExtensionUserManagement (org.zaproxy.zap.extension.users.ExtensionUserManagement)9 ArrayList (java.util.ArrayList)8 JMenuItem (javax.swing.JMenuItem)7 ExtensionPopupMenuItem (org.parosproxy.paros.extension.ExtensionPopupMenuItem)7 SiteNode (org.parosproxy.paros.model.SiteNode)7 IOException (java.io.IOException)6