Search in sources :

Example 1 with ApiDynamicActionImplementor

use of org.zaproxy.zap.extension.api.ApiDynamicActionImplementor in project zaproxy by zaproxy.

the class FormBasedAuthenticationMethodType method getSetMethodForContextApiAction.

@Override
public ApiDynamicActionImplementor getSetMethodForContextApiAction() {
    return new ApiDynamicActionImplementor(API_METHOD_NAME, new String[] { PARAM_LOGIN_URL }, new String[] { PARAM_LOGIN_REQUEST_DATA }) {

        @Override
        public void handleAction(JSONObject params) throws ApiException {
            Context context = ApiUtils.getContextByParamId(params, AuthenticationAPI.PARAM_CONTEXT_ID);
            String loginUrl = ApiUtils.getNonEmptyStringParam(params, PARAM_LOGIN_URL);
            try {
                new URL(loginUrl);
            } catch (Exception ex) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_LOGIN_URL);
            }
            String postData = "";
            if (params.containsKey(PARAM_LOGIN_REQUEST_DATA)) {
                postData = params.getString(PARAM_LOGIN_REQUEST_DATA);
            }
            // Set the method
            FormBasedAuthenticationMethod method = createAuthenticationMethod(context.getIndex());
            try {
                method.setLoginRequest(loginUrl, postData);
            } catch (Exception e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
            if (!context.getAuthenticationMethod().isSameType(method))
                apiChangedAuthenticationMethodForContext(context.getIndex());
            context.setAuthenticationMethod(method);
        }
    };
}
Also used : ApiDynamicActionImplementor(org.zaproxy.zap.extension.api.ApiDynamicActionImplementor) Context(org.zaproxy.zap.model.Context) PopupMenuItemContext(org.zaproxy.zap.view.popup.PopupMenuItemContext) RecordContext(org.parosproxy.paros.db.RecordContext) JSONObject(net.sf.json.JSONObject) URL(java.net.URL) URIException(org.apache.commons.httpclient.URIException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) ApiException(org.zaproxy.zap.extension.api.ApiException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(org.apache.commons.configuration.ConfigurationException) IOException(java.io.IOException) DatabaseException(org.parosproxy.paros.db.DatabaseException) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 2 with ApiDynamicActionImplementor

use of org.zaproxy.zap.extension.api.ApiDynamicActionImplementor in project zaproxy by zaproxy.

the class UsersAPI method handleApiView.

@Override
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException {
    log.debug("handleApiView " + name + " " + params.toString());
    switch(name) {
        case VIEW_USERS_LIST:
            ApiResponseList usersListResponse = new ApiResponseList(name);
            // Get the users
            List<User> users;
            if (hasContextId(params))
                users = extension.getContextUserAuthManager(getContextId(params)).getUsers();
            else {
                users = new ArrayList<>();
                for (Context c : Model.getSingleton().getSession().getContexts()) users.addAll(extension.getContextUserAuthManager(c.getId()).getUsers());
            }
            // Prepare the response
            for (User user : users) usersListResponse.addItem(buildResponseFromUser(user));
            return usersListResponse;
        case VIEW_GET_USER_BY_ID:
            return buildResponseFromUser(getUser(params));
        case VIEW_GET_AUTH_CREDENTIALS:
            return getUser(params).getAuthenticationCredentials().getApiResponseRepresentation();
        case VIEW_GET_AUTH_CREDENTIALS_CONFIG_PARAMETERS:
            AuthenticationMethodType type = ApiUtils.getContextByParamId(params, PARAM_CONTEXT_ID).getAuthenticationMethod().getType();
            ApiDynamicActionImplementor a = loadedAuthenticationMethodActions.get(type.getUniqueIdentifier());
            return a.buildParamsDescription();
        case VIEW_GET_AUTH_STATE:
            return buildResponseFromAuthState(getUser(params).getAuthenticationState());
        case VIEW_GET_AUTH_SESSION:
            return buildResponseFromAuthSession(getUser(params).getAuthenticatedSession());
        default:
            throw new ApiException(ApiException.Type.BAD_VIEW);
    }
}
Also used : Context(org.zaproxy.zap.model.Context) ApiDynamicActionImplementor(org.zaproxy.zap.extension.api.ApiDynamicActionImplementor) AuthenticationMethodType(org.zaproxy.zap.authentication.AuthenticationMethodType) User(org.zaproxy.zap.users.User) ApiResponseList(org.zaproxy.zap.extension.api.ApiResponseList) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 3 with ApiDynamicActionImplementor

use of org.zaproxy.zap.extension.api.ApiDynamicActionImplementor 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 4 with ApiDynamicActionImplementor

use of org.zaproxy.zap.extension.api.ApiDynamicActionImplementor in project zaproxy by zaproxy.

the class HttpAuthenticationMethodType method getSetMethodForContextApiAction.

@Override
public ApiDynamicActionImplementor getSetMethodForContextApiAction() {
    return new ApiDynamicActionImplementor(API_METHOD_NAME, new String[] { PARAM_HOSTNAME }, new String[] { PARAM_REALM, PARAM_PORT }) {

        @Override
        public void handleAction(JSONObject params) throws ApiException {
            Context context = ApiUtils.getContextByParamId(params, AuthenticationAPI.PARAM_CONTEXT_ID);
            HttpAuthenticationMethod method = createAuthenticationMethod(context.getId());
            method.hostname = ApiUtils.getNonEmptyStringParam(params, PARAM_HOSTNAME);
            try {
                new URI(method.hostname);
            } catch (Exception ex) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_HOSTNAME);
            }
            method.realm = params.optString(PARAM_REALM);
            if (params.containsKey(PARAM_PORT))
                try {
                    String portString = params.getString(PARAM_PORT);
                    method.port = Integer.parseInt(portString);
                } catch (Exception ex) {
                    throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_PORT);
                }
            context.setAuthenticationMethod(method);
        }
    };
}
Also used : ApiDynamicActionImplementor(org.zaproxy.zap.extension.api.ApiDynamicActionImplementor) Context(org.zaproxy.zap.model.Context) RecordContext(org.parosproxy.paros.db.RecordContext) JSONObject(net.sf.json.JSONObject) URI(java.net.URI) ApiException(org.zaproxy.zap.extension.api.ApiException) DatabaseException(org.parosproxy.paros.db.DatabaseException) UnknownHostException(java.net.UnknownHostException) ConfigurationException(org.apache.commons.configuration.ConfigurationException) ApiException(org.zaproxy.zap.extension.api.ApiException)

Example 5 with ApiDynamicActionImplementor

use of org.zaproxy.zap.extension.api.ApiDynamicActionImplementor in project zaproxy by zaproxy.

the class PostBasedAuthenticationMethodType method getSetMethodForContextApiAction.

@Override
public ApiDynamicActionImplementor getSetMethodForContextApiAction() {
    String[] mandatoryParamNames;
    String[] optionalParamNames;
    if (postDataRequired) {
        mandatoryParamNames = new String[] { PARAM_LOGIN_URL, PARAM_LOGIN_REQUEST_DATA };
        optionalParamNames = new String[] { PARAM_LOGIN_PAGE_URL };
    } else {
        mandatoryParamNames = new String[] { PARAM_LOGIN_URL };
        optionalParamNames = new String[] { PARAM_LOGIN_REQUEST_DATA, PARAM_LOGIN_PAGE_URL };
    }
    return new ApiDynamicActionImplementor(apiMethodName, mandatoryParamNames, optionalParamNames) {

        @Override
        public void handleAction(JSONObject params) throws ApiException {
            Context context = ApiUtils.getContextByParamId(params, AuthenticationAPI.PARAM_CONTEXT_ID);
            String loginUrl = ApiUtils.getNonEmptyStringParam(params, PARAM_LOGIN_URL);
            if (!isValidLoginUrl(loginUrl)) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_LOGIN_URL);
            }
            String loginPageUrl = ApiUtils.getOptionalStringParam(params, PARAM_LOGIN_PAGE_URL);
            if (loginPageUrl == null || loginPageUrl.isEmpty()) {
                loginPageUrl = loginUrl;
            } else if (!isValidLoginUrl(loginPageUrl)) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_LOGIN_PAGE_URL);
            }
            String postData = "";
            if (postDataRequired) {
                postData = ApiUtils.getNonEmptyStringParam(params, PARAM_LOGIN_REQUEST_DATA);
            } else if (params.containsKey(PARAM_LOGIN_REQUEST_DATA)) {
                postData = params.getString(PARAM_LOGIN_REQUEST_DATA);
            }
            // Set the method
            PostBasedAuthenticationMethod method = createAuthenticationMethod(context.getId());
            try {
                method.setLoginRequest(loginUrl, postData);
                method.setLoginPageUrl(loginPageUrl);
            } catch (Exception e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
            context.setAuthenticationMethod(method);
        }
    };
}
Also used : ApiDynamicActionImplementor(org.zaproxy.zap.extension.api.ApiDynamicActionImplementor) Context(org.zaproxy.zap.model.Context) PopupMenuItemContext(org.zaproxy.zap.view.popup.PopupMenuItemContext) RecordContext(org.parosproxy.paros.db.RecordContext) JSONObject(net.sf.json.JSONObject) URIException(org.apache.commons.httpclient.URIException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) ApiException(org.zaproxy.zap.extension.api.ApiException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(org.apache.commons.configuration.ConfigurationException) IOException(java.io.IOException) DatabaseException(org.parosproxy.paros.db.DatabaseException) ApiException(org.zaproxy.zap.extension.api.ApiException)

Aggregations

ApiDynamicActionImplementor (org.zaproxy.zap.extension.api.ApiDynamicActionImplementor)13 Context (org.zaproxy.zap.model.Context)13 JSONObject (net.sf.json.JSONObject)12 ApiException (org.zaproxy.zap.extension.api.ApiException)10 RecordContext (org.parosproxy.paros.db.RecordContext)5 User (org.zaproxy.zap.users.User)5 ConfigurationException (org.apache.commons.configuration.ConfigurationException)4 DatabaseException (org.parosproxy.paros.db.DatabaseException)4 IOException (java.io.IOException)3 ExtensionUserManagement (org.zaproxy.zap.extension.users.ExtensionUserManagement)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 HashMap (java.util.HashMap)2 URIException (org.apache.commons.httpclient.URIException)2 HttpMalformedHeaderException (org.parosproxy.paros.network.HttpMalformedHeaderException)2 ScriptWrapper (org.zaproxy.zap.extension.script.ScriptWrapper)2 PopupMenuItemContext (org.zaproxy.zap.view.popup.PopupMenuItemContext)2 URI (java.net.URI)1 URL (java.net.URL)1 UnknownHostException (java.net.UnknownHostException)1 ScriptException (javax.script.ScriptException)1