/* (non-Javadoc)
@see com.att.authz.certman.mapper.Mapper#toReq(com.att.authz.env.AuthzTrans, java.lang.Object)
516048
@Override
	public Result<CertReq> toReq(AuthzTrans trans, BaseRequest req) {
		CertificateRequest in;
		try {
			in = (CertificateRequest)req;
		} catch(ClassCastException e) {
			return Result.err(Result.ERR_BadData,"Request is not a CertificateRequest");
		}

		CertReq out = new CertReq();
		Validator v = new Validator();
		if(v.isNull("CertRequest", req)
			.nullOrBlank("MechID", out.mechid=in.getMechid())
			.nullBlankMin("FQDNs", out.fqdns=in.getFqdns(),1)
			.err()) {
			return Result.err(Result.ERR_BadData, v.errs());
		}
		out.emails = in.getEmail();
		out.sponsor=in.getSponsor();
		out.start = in.getStart();
		out.end = in.getEnd();
		return Result.ok(out);
	}
549651
private boolean validateAssertion(final HttpServletRequest request, final String serviceTicketId, final Assertion assertion, final Service service) {
        for (val spec : serviceValidateConfigurationContext.getValidationSpecifications()) {
            spec.reset();
            val binder = new ServletRequestDataBinder(spec, "validationSpecification");
            initBinder(request, binder);
            binder.bind(request);
            if (!spec.isSatisfiedBy(assertion, request)) {
                LOGGER.warn("Service ticket [{}] does not satisfy validation specification.", serviceTicketId);
                return false;
            }
        }
        enforceTicketValidationAuthorizationFor(request, service, assertion);
        return true;
    }
117021
@Override
    public void check(Certificate cert) throws CertPathValidatorException {
        check(cert, java.util.Collections.<String>emptySet());
    }
358006
public PqAuth doAuth(ConnectionInfo[] infos) {
        TransportRate rate = new TransportRate(infos);
        for (int i = 0; i < AUTH_ATTEMPT_COUNT; i++) {
            ConnectionType connectionType = rate.tryConnection();
            try {
                context = new PlainTcpConnection(connectionType.getHost(), connectionType.getPort());
                rate.onConnectionSuccess(connectionType.getId());
            } catch (IOException e) {
                Logger.e(TAG, e);
                rate.onConnectionFailure(connectionType.getId());
                continue;
            }

            try {
                return authAttempt();
            } catch (IOException e) {
                Logger.e(TAG, e);
            } finally {
                if (context != null) {
                    context.destroy();
                    context = null;
                }
            }

            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                return null;
            }
        }
        return null;
    }
349668
public static RevocationStatus check(X509Certificate cert,
                                         X509Certificate issuerCert,
                                         URI responderURI,
                                         X509Certificate responderCert,
                                         Date date, List<Extension> extensions)
        throws IOException, CertPathValidatorException
    {
        CertId certId = null;
        try {
            X509CertImpl certImpl = X509CertImpl.toImpl(cert);
            certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
        } catch (CertificateException | IOException e) {
            throw new CertPathValidatorException
                ("Exception while encoding OCSPRequest", e);
        }
        OCSPResponse ocspResponse = check(Collections.singletonList(certId),
            responderURI, issuerCert, responderCert, date, extensions);
        return (RevocationStatus) ocspResponse.getSingleResponse(certId);
    }
1081161
public static Endpoint determineEndpointForRequest(final RequestAbstractType authnRequest,
                                                       final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
                                                       final String binding) {
        var endpoint = (Endpoint) null;
        if (authnRequest instanceof LogoutRequest) {
            endpoint = adaptor.getSingleLogoutService(binding);
        } else {
            val endpointReq = getAssertionConsumerServiceFromRequest(authnRequest, binding);
            endpoint = endpointReq == null
                ? adaptor.getAssertionConsumerService(binding)
                : endpointReq;
        }

        if (endpoint == null || StringUtils.isBlank(endpoint.getBinding())) {
            throw new SamlException("Assertion consumer service does not define a binding");
        }
        val location = StringUtils.isBlank(endpoint.getResponseLocation()) ? endpoint.getLocation() : endpoint.getResponseLocation();
        if (StringUtils.isBlank(location)) {
            throw new SamlException("Assertion consumer service does not define a target location");
        }
        return endpoint;
    }
234415
public void checkServerTrusted( X509Certificate[] chain, String authType )
            throws CertificateException
    {
        X509Certificate certificate = chain[0];

        String cert = fingerprint( certificate );

        if ( this.fingerprint == null )
        {
            try
            {
                saveTrustedHost( cert );
            }
            catch ( IOException e )
            {
                throw new CertificateException( format(
                        "Failed to save the server ID and the certificate received from the server to file %s.\n" +
                        "Server ID: %s\nReceived cert:\n%s",
                        knownHosts.getAbsolutePath(), serverId, X509CertToString( cert ) ), e );
            }
        }
        else
        {
            if ( !this.fingerprint.equals( cert ) )
            {
                throw new CertificateException( format(
                        "Unable to connect to neo4j at `%s`, because the certificate the server uses has changed. " +
                        "This is a security feature to protect against man-in-the-middle attacks.\n" +
                        "If you trust the certificate the server uses now, simply remove the line that starts with " +
                        "`%s` " +
                        "in the file `%s`.\n" +
                        "The old certificate saved in file is:\n%sThe New certificate received is:\n%s",
                        serverId, serverId, knownHosts.getAbsolutePath(),
                        X509CertToString( this.fingerprint ), X509CertToString( cert ) ) );
            }
        }
    }
757808
private void handleCertificateAuthenticator(X509Certificate[] certChain,
                                                CertificateAuthenticator certAuthen) throws Exception {
        String type = certAuthen.getType();
        if (type == null)
            type = AccessIdUtil.TYPE_USER;
        String realm = certAuthen.getRealm();
        if (realm == null)
            realm = "defaultRealm";
        authenticatedId = certAuthen.getUsername();
        username = authenticatedId;
        String accessId = AccessIdUtil.createAccessId(type, realm, authenticatedId);
        addCredentials(accessId);
    }
1306804
public static void putPasswordResetSecurityQuestionsEnabled(final RequestContext requestContext, final boolean value) {
        val flowScope = requestContext.getFlowScope();
        flowScope.put("questionsEnabled", value);
    }
1278313
public static void timeSensitiveInit(Env env, AuthAPI authzAPI, AuthzFacade facade, final DirectAAFUserPass directAAFUserPass) throws Exception {
		/**
		 * Basic Auth, quick Validation
		 * 
		 * Responds OK or NotAuthorized
		 */
		authzAPI.route(env, HttpMethods.GET, "/authn/basicAuth", new Code(facade,"Is given BasicAuth valid?",true) {
			@Override
			public void handle(
					AuthzTrans trans, 
					HttpServletRequest req,
					HttpServletResponse resp) throws Exception {

				Principal p = trans.getUserPrincipal();
				if (p instanceof BasicPrincipal) {
					// the idea is that if call is made with this credential, and it's a BasicPrincipal, it's ok
					// otherwise, it wouldn't have gotten here.
					resp.setStatus(HttpStatus.OK_200);
				} else if (p instanceof X509Principal) {
					// have to check Basic Auth here, because it might be CSP.
					String ba = req.getHeader("Authorization");
					if(ba.startsWith("Basic ")) {
						String decoded = Symm.base64noSplit.decode(ba.substring(6));
						int colon = decoded.indexOf(':');
						if(directAAFUserPass.validate(
								decoded.substring(0,colon), 
								CredVal.Type.PASSWORD , 
								decoded.substring(colon+1).getBytes())) {
							
							resp.setStatus(HttpStatus.OK_200);
						} else {
							resp.setStatus(HttpStatus.FORBIDDEN_403);
						}
					}
				} else if(p == null) {
					trans.error().log("Transaction not Authenticated... no Principal");
					resp.setStatus(HttpStatus.FORBIDDEN_403);
				} else {
					trans.checkpoint("Basic Auth Check Failed: This wasn't a Basic Auth Trans");
					// For Auth Security questions, we don't give any info to client on why failed
					resp.setStatus(HttpStatus.FORBIDDEN_403);
				}
			}
		},"text/plain");
		
		/** 
		 *  returns whether a given Credential is valid
		 */
		authzAPI.route(POST, "/authn/validate", API.CRED_REQ, new Code(facade,"Is given Credential valid?",true) {
			@Override
			public void handle(
					AuthzTrans trans, 
					HttpServletRequest req,
					HttpServletResponse resp) throws Exception {
				
				Result<Date> r = context.doesCredentialMatch(trans, req, resp);
				if(r.isOK()) {
						resp.setStatus(HttpStatus.OK_200);
				} else {
						// For Security, we don't give any info out on why failed, other than forbidden
						resp.setStatus(HttpStatus.FORBIDDEN_403);
				}
			}
		});  

		/** 
		 *  returns whether a given Credential is valid
		 */
		authzAPI.route(GET, "/authn/cert/id/:id", API.CERTS, new Code(facade,"Get Cert Info by ID",true) {
			@Override
			public void handle(
					AuthzTrans trans, 
					HttpServletRequest req,
					HttpServletResponse resp) throws Exception {
				
				Result<Void> r = context.getCertInfoByID(trans, req, resp, pathParam(req,":id") );
				if(r.isOK()) {
						resp.setStatus(HttpStatus.OK_200); 
				} else {
						// For Security, we don't give any info out on why failed, other than forbidden
						resp.setStatus(HttpStatus.FORBIDDEN_403);
				}
			}
		});  




	}
1284478
public void doFilter( ServletRequest request,
                ServletResponse response,
                FilterChain chain ) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        NtlmPasswordAuthentication ntlm;

        if ((ntlm = negotiate( req, resp, false )) == null) {
            return;
        }

        chain.doFilter( new NtlmHttpServletRequest( req, ntlm ), response );
    }
1316453
@Override
	public Result<Void> requestNS(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, NsType type) {
		TimeTaken tt = trans.start(CREATE_NS, Env.SUB|Env.ALWAYS);
		try {
			REQUEST request;
			try {
				Data<REQUEST> rd = nsRequestDF.newData().load(req.getInputStream());
				if(Question.willSpecialLog(trans, trans.user())) {
					Question.logEncryptTrace(trans,rd.asString());
				}
				request = rd.asObject();
			} catch(APIException e) {
				trans.error().log("Invalid Input",IN,CREATE_NS);
				return Result.err(Status.ERR_BadData,"Invalid Input");
			}
			
			Result<Void> rp = service.createNS(trans,request,type);
			switch(rp.status) {
				case OK: 
					setContentType(resp,nsRequestDF.getOutType());
					return Result.ok();
				default:
					return Result.err(rp);
			}
		} catch (Exception e) {
			trans.error().log(e,IN,CREATE_NS);
			return Result.err(e);
		} finally {
			tt.done();
		}
	}
1115930
private void assertValidSSLConfig() {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        boolean sslEnabled = (((Boolean) props.get(SSL_ENABLED)) == null) ? false : (Boolean) props.get(SSL_ENABLED);
        boolean sslRefExists = ((props.get(SSL_REF)) == null) ? false : true;

        if (sslRefExists && !sslEnabled) {
            if (trace && tc.isDebugEnabled()) {
                // sslRef property set in the server.xml but sslEnabled not set to true.
                Tr.error(tc, "CWKKD0024.ssl.sslref.no.ssl", MONGO, id);
            }
            throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0024.ssl.sslref.no.ssl", MONGO, id));
        }

        if (sslEnabled) {
            // we should have the ssl-1.0 feature selected
            if (sslHelper == null) {
                throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0015.ssl.feature.missing", MONGO, id));
            }

            if (useCertAuth) {

                if (!sslEnabled) {
                    // SSL not enabled, so shouldn't be using certificate authentication
                    throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0019.ssl.certificate.no.ssl", MONGO, id));
                }
                if (props.get(USER) != null || props.get(PASSWORD) != null) {
                    // shouldn't be using userid and pasword with certificate authentication
                    throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0018.ssl.user.pswd.certificate", MONGO, id));
                }
            }
        }
    }
974590
public RespondToAuthChallengeResult withChallengeParameters(java.util.Map<String, String> challengeParameters) {
        setChallengeParameters(challengeParameters);
        return this;
    }
1345742
@Override
    public boolean isAtomServiceURI(final AtomRequest areq) {
        final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
        if (pathInfo.length == 0) {
            return true;
        }
        return false;
    }
1127618
@Override
	public void error(AuthzTrans trans, HttpServletResponse response, Result<?> result) {
		error(trans, response, result.status,
				result.details==null?"":result.details.trim(),
				result.variables==null?new String[0]:result.variables);
	}
1283818
public static void init(final AuthAPI authzAPI, AuthzFacade facade) throws Exception {

		/**
		 * Clear Cache Segment
		 */
		authzAPI.route(DELETE,"/mgmt/cache/:area/:segments",API.VOID,new Code(facade,"Clear Cache by Segment", true) {
			@Override
			public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
				Result<Void> r = context.cacheClear(trans, pathParam(req,"area"), pathParam(req,"segments"));
				switch(r.status) {
					case OK:
						trans.checkpoint(SUCCESS,Trans.ALWAYS);
						resp.setStatus(HttpStatus.OK_200); 
						break;
					default:
						context.error(trans,resp,r);
				}
			}
		});
		
		/**
		 * Clear Cache
		 */
		authzAPI.route(DELETE,"/mgmt/cache/:area",API.VOID,new Code(facade,"Clear Cache", true) {
			@Override
			public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
				Result<Void> r;
				String area;
				r = context.cacheClear(trans, area=pathParam(req,"area"));
				switch(r.status) {
					case OK:
						trans.audit().log("Cache " + area + " has been cleared by "+trans.user());
						trans.checkpoint(SUCCESS,Trans.ALWAYS);
						resp.setStatus(HttpStatus.OK_200); 
						break;
					default:
						context.error(trans,resp,r);
				}
			}
		});

		/**
		 * Clear DB Sessions
		 */
		authzAPI.route(DELETE,"/mgmt/dbsession",API.VOID,new Code(facade,"Clear DBSessions", true) {
			@Override
			public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
				try {
					if(req.isUserInRole(Define.ROOT_NS+".db|pool|clear")) {
						SessionFilter.clear();
						context.dbReset(trans);

						trans.audit().log("DB Sessions have been cleared by "+trans.user());

						trans.checkpoint(SUCCESS,Trans.ALWAYS);
						resp.setStatus(HttpStatus.OK_200);
						return;
					}
					context.error(trans,resp,Result.err(Result.ERR_Denied,"%s is not allowed to clear dbsessions",trans.user()));
				} catch(Exception e) {
					trans.error().log(e, "clearing dbsession");
					context.error(trans,resp,Result.err(e));
				}
			}
		});

		/**
		 * Deny an IP 
		 */
		authzAPI.route(POST, "/mgmt/deny/ip/:ip", API.VOID, new Code(facade,"Deny IP",true) {
			@Override
			public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
				String ip = pathParam(req,":ip");
				if(req.isUserInRole(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|ip")) {
					if(DenialOfServiceTaf.denyIP(ip)) {
						trans.audit().log(ip+" has been set to deny by "+trans.user());
						trans.checkpoint(SUCCESS,Trans.ALWAYS);

						resp.setStatus(HttpStatus.CREATED_201);
					} else {
						context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, 
								ip + " is already being denied"));
					}
				} else {
					trans.audit().log(trans.user(),"has attempted to deny",ip,"without authorization");
					context.error(trans,resp,Result.err(Status.ERR_Denied, 
						trans.getUserPrincipal().getName() + " is not allowed to set IP Denial"));
				}
			}
		});
		
		/**
		 * Stop Denying an IP
		 */
		authzAPI.route(DELETE, "/mgmt/deny/ip/:ip", API.VOID, new Code(facade,"Stop Denying IP",true) {
			@Override
			public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
				String ip = pathParam(req,":ip");
				if(req.isUserInRole(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|ip")) {
					if(DenialOfServiceTaf.removeDenyIP(ip)) {
						trans.audit().log(ip+" has been removed from denial by "+trans.user());
						trans.checkpoint(SUCCESS,Trans.ALWAYS);
						resp.setStatus(HttpStatus.OK_200);
					} else {
						context.error(trans,resp,Result.err(Status.ERR_NotFound, 
								ip + " is not on the denial list"));
					}
				} else {
					trans.audit().log(trans.user(),"has attempted to remove",ip," from being denied without authorization");
					context.error(trans,resp,Result.err(Status.ERR_Denied, 
						trans.getUserPrincipal().getName() + " is not allowed to remove IP Denial"));
				}
			}
		});

		/**
		 * Deny an ID 
		 */
		authzAPI.route(POST, "/mgmt/deny/id/:id", API.VOID, new Code(facade,"Deny ID",true) {
			@Override
			public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
				String id = pathParam(req,":id");
				if(req.isUserInRole(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|id")) {
					if(DenialOfServiceTaf.denyID(id)) {
						trans.audit().log(id+" has been set to deny by "+trans.user());
						trans.checkpoint(SUCCESS,Trans.ALWAYS);
						resp.setStatus(HttpStatus.CREATED_201);
					} else {
						context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, 
								id + " is already being denied"));
					}
				} else {
					trans.audit().log(trans.user(),"has attempted to deny",id,"without authorization");
					context.error(trans,resp,Result.err(Status.ERR_Denied, 
						trans.getUserPrincipal().getName() + " is not allowed to set ID Denial"));
				}
			}
		});
		
		/**
		 * Stop Denying an ID
		 */
		authzAPI.route(DELETE, "/mgmt/deny/id/:id", API.VOID, new Code(facade,"Stop Denying ID",true) {
			@Override
			public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
				String id = pathParam(req,":id");
				if(req.isUserInRole(Define.ROOT_NS+".deny|"+Define.ROOT_COMPANY+"|id")) {
					if(DenialOfServiceTaf.removeDenyID(id)) {
						trans.audit().log(id+" has been removed from denial by " + trans.user());
						trans.checkpoint(SUCCESS,Trans.ALWAYS);
						resp.setStatus(HttpStatus.OK_200);
					} else {
						context.error(trans,resp,Result.err(Status.ERR_NotFound, 
								id + " is not on the denial list"));
					}
				} else {
					trans.audit().log(trans.user(),"has attempted to remove",id," from being denied without authorization");
					context.error(trans,resp,Result.err(Status.ERR_Denied, 
						trans.getUserPrincipal().getName() + " is not allowed to remove ID Denial"));
				}
			}
		});

		/**
		 * Deny an ID 
		 */
		authzAPI.route(POST, "/mgmt/log/id/:id", API.VOID, new Code(facade,"Special Log ID",true) {
			@Override
			public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
				String id = pathParam(req,":id");
				if(req.isUserInRole(Define.ROOT_NS+".log|"+Define.ROOT_COMPANY+"|id")) {
					if(Question.specialLogOn(trans,id)) {
						trans.audit().log(id+" has been set to special Log by "+trans.user());
						trans.checkpoint(SUCCESS,Trans.ALWAYS);
						resp.setStatus(HttpStatus.CREATED_201);
					} else {
						context.error(trans,resp,Result.err(Status.ERR_ConflictAlreadyExists, 
								id + " is already being special Logged"));
					}
				} else {
					trans.audit().log(trans.user(),"has attempted to special Log",id,"without authorization");
					context.error(trans,resp,Result.err(Status.ERR_Denied, 
						trans.getUserPrincipal().getName() + " is not allowed to set ID special Logging"));
				}
			}
		});
		
		/**
		 * Stop Denying an ID
		 */
		authzAPI.route(DELETE, "/mgmt/log/id/:id", API.VOID, new Code(facade,"Stop Special Log ID",true) {
			@Override
			public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
				String id = pathParam(req,":id");
				if(req.isUserInRole(Define.ROOT_NS+".log|"+Define.ROOT_COMPANY+"|id")) {
					if(Question.specialLogOff(trans,id)) {
						trans.audit().log(id+" has been removed from special Logging by " + trans.user());
						trans.checkpoint(SUCCESS,Trans.ALWAYS);
						resp.setStatus(HttpStatus.OK_200);
					} else {
						context.error(trans,resp,Result.err(Status.ERR_NotFound, 
								id + " is not on the special Logging list"));
					}
				} else {
					trans.audit().log(trans.user(),"has attempted to remove",id," from being special Logged without authorization");
					context.error(trans,resp,Result.err(Status.ERR_Denied, 
						trans.getUserPrincipal().getName() + " is not allowed to remove ID special Logging"));
				}
			}
		});


	}