Create process as different user with Java and Kerberos - kerberos

I am working on a Java server application (running under Windows as a service) and want to achieve the following scenario:
A user issues a POST request to the server. The user is authenticated with Kerberos (SPNEGO, SSO in an enterprise environment).
The service creates a new Java process. The process must run as the authenticated user and not the service user (impersonation/delegation).
The new process should execute in the security context of the user. It must communicate with other remote systems that require Kerberos authentication (e.g. file shares, other web services, ...).
Working proof-of-concept:
Spring Boot application with Waffle for the Kerberos authentication.
Create a new process for the authenticated user. I use JNA and the Windows native function CreateProcessAsUser.
The process is created as the authenticated user. I can verify this with the Process Explorer utility.
What is missing and not working:
The process cannot request other Kerberos tickets (e.g. by calling InitializeSecurityContext())
The process cannot access network shares.
The process cannot communicate with other web services that require Kerberos authentication.
My questions:
What am I missing or what is possibly wrong with my code?
Is it even possible to implement what I want to achieve?
Server - Authentication (shortened, extracted from Waffle):
final byte[] tokenBuffer = authorizationHeader.getTokenBytes();
CredHandle serverCredHandle = new CredHandle();
TimeStamp clientLifetime = new TimeStamp();
int rc = Secur32.INSTANCE.AcquireCredentialsHandle(
null,
"Negotiate",
Sspi.SECPKG_CRED_INBOUND,
null,
null,
null,
null,
serverCredHandle,
clientLifetime);
SecBufferDesc pbClientToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, tokenBuffer);
CtxtHandle phNewServerContext = new CtxtHandle();
SecBufferDesc pbServerToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, Sspi.MAX_TOKEN_SIZE);
IntByReference pfClientContextAttr = new IntByReference();
rc = Secur32.INSTANCE.AcceptSecurityContext(
serverCredHandle,
null,
pbClientToken,
Sspi.ISC_REQ_CONNECTION,
Sspi.SECURITY_NATIVE_DREP,
phNewServerContext,
pbServerToken,
pfClientContextAttr,
null);
rc = Advapi32.INSTANCE.ImpersonateLoggedOnUser(/* provide the security context token */)
Server - CreateProcessAsUser:
// get impersonation token of user
WinNT.HANDLEByReference threadToken = new WinNT.HANDLEByReference();
WinNT.HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread();
boolean threadTokenResult = Advapi32.INSTANCE.OpenThreadToken(
threadHandle,
WinNT.TOKEN_QUERY | WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_ASSIGN_PRIMARY,
false, /* TRUE if the access check is to be made against the process-level security context. FALSE if the access check is to be made against the current security context of the thread calling the OpenThreadToken function. */
threadToken);
// create primary token by duplicating impersonation token
WinNT.HANDLEByReference primaryToken = new WinNT.HANDLEByReference();
boolean primaryTokenResult = Advapi32.INSTANCE.DuplicateTokenEx(
threadToken.getValue(), /* hExistingToken */
WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY | WinNT.TOKEN_ASSIGN_PRIMARY, /* dwDesiredAccess */
null, /* lpTokenAttributes */
WinNT.SECURITY_IMPERSONATION_LEVEL.SecurityDelegation, /* ImpersonationLevel */
WinNT.TOKEN_TYPE.TokenPrimary, /* TokenType */
primaryToken); /* phNewToken */
String environment = createEnvironment(primaryToken);
WinBase.STARTUPINFO startupInfo = new WinBase.STARTUPINFO();
WinBase.PROCESS_INFORMATION processInfo = new WinBase.PROCESS_INFORMATION();
boolean createProcessResult = Advapi32.INSTANCE.CreateProcessAsUser(
primaryToken.getValue(), /* hToken */
null, /* lpApplicationName */
command, /* lpCommandLine */
null, /* lpProcessAttributes */
null, /* lpThreadAttributes */
false, /* bInheritHandles */
WinNT.CREATE_NEW_CONSOLE | WinNT.CREATE_UNICODE_ENVIRONMENT, /* dwCreationFlags */
environment, /* lpEnvironment */
processDirectory, /* lpCurrentDirectory */
startupInfo, /* lpStartupInfo */
processInfo); /* lpProcessInformation */

Related

Generate SPNEGO Token Failured

I tried to generate the token which can be used as the HTTP header to authenticate to the HDFS WebHDFS URL and Oozie REST API URL.
I referenced the url below to have the below code to generate the Negotiate token.
https://www.ibm.com/support/knowledgecenter/en/SS7JFU_8.5.5/com.ibm.websphere.express.doc/ae/tsec_SPNEGO_token.html
public class TokenCreation {
private static final String SPNEGO_OID = "1.3.6.1.5.5.2";
private static final String KERBEROS_OID = "1.2.840.113554.1.2.2";
public static byte[] genToken(String principal) {
System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
byte[] spnegoToken = new byte[0];
try {
Oid spnegoMechOid = new Oid(SPNEGO_OID);
Oid krb5MechOid = new Oid(KERBEROS_OID);
GSSCredential clientGssCreds = null;
GSSManager manager = GSSManager.getInstance();
GSSName gssUserName = manager.createName(principal, GSSName.NT_USER_NAME, krb5MechOid);
clientGssCreds = manager.createCredential(gssUserName.canonicalize(krb5MechOid),
GSSCredential.INDEFINITE_LIFETIME,
krb5MechOid,
GSSCredential.INITIATE_ONLY);
clientGssCreds.add(gssUserName,
GSSCredential.INDEFINITE_LIFETIME,
GSSCredential.INDEFINITE_LIFETIME,
spnegoMechOid, GSSCredential.INITIATE_ONLY);
GSSName gssServerName = manager.createName(principal, GSSName.NT_USER_NAME);
GSSContext clientContext = manager.createContext(gssServerName.canonicalize(spnegoMechOid),
spnegoMechOid,
clientGssCreds,
GSSContext.DEFAULT_LIFETIME);
// optional enable GSS credential delegation
clientContext.requestCredDeleg(true);
// create a SPNEGO token for the target server
spnegoToken = clientContext.initSecContext(spnegoToken, 0, spnegoToken.length);
} catch (GSSException e) {
e.printStackTrace();
}
return spnegoToken;
}
But after running the above code, I always got the below prompt:
2019-09-25 14:12:51 760 [INFO] [pool-2-thread-1] c.s.n.c.u.security.KrbUtils - after loginUserFromKeytab............AtoimcUser:HTTP/host1.exmaple.com#EXAMPLE.COM
2019-09-25 14:12:51 760 [INFO] [pool-2-thread-1] c.s.n.app.oozie.OozieAppCaller - ->>>>>>User Name is HTTP/host1.exmaple.com#EXAMPLE.COM
2019-09-25 14:12:51 760 [INFO] [pool-2-thread-1] c.s.n.app.oozie.OozieAppCaller - ->>>>>>Mode is KERBEROS
>>>KinitOptions cache name is /tmp/krb5cc_0
Kerberos username [root]: ^C^C^C
Kerberos password for root:
You can see at the end of the above output log.
The "Kerberos username" is always prompt to ask for username.
Also I have tried to manually run kinit the keytab.
and the above class can generate the token successfully.
But manually run kinit is NOT the way I wanted.
Would you please help it?
Thanks.
Kerberos and SPNEGO support in Java is cumbersome unfortunately.
I've created a small library to simplify some Kerberos use cases: https://github.com/bedrin/kerb4j
You can use it like this to generate SPNEGO token:
SpnegoClient spnegoClient = SpnegoClient.loginWithKeyTab("svc_consumer", "/opt/myapp/consumer.keytab");
URL url = new URL("http://api.provider.acme.com/api/operation1");
SpnegoContext context = spnegoClient.createContext("http://provider.acme.com"); // Will result in HTTP/provider.acme.com SPN
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", context.createTokenAsAuthroizationHeader());

OpenAM - Getting a Session attribute into an OpenID Connect claim

I'm using OpenAM 13.5 configured to have a SAML circle of trust to federate logins to our applications with third-party IdPs. Some of the SAML assertions received by the third party are mapped as Session level attributes. The SAML part is working fine, but I need to connect to OpenAM an application who can talk OpenID Connect. I created an OpenID Connect service, configured the client accordingly and I can login successfully using the flow "App -> OpenAM UI -> 3rd party IDP -> OpenAM OIDC -> App".
The problem is that I can retrieve only the attributes that are mapped to the data store - the session attributes (e.g. AuthLevel, IDP Name, etc) aren't included in the mapped claims.
I tried to edit the OIDC Claims default script which has a session variable that seems to contain what I need, but unfortunately the session variable is always null.
Is this the correct approach? Why is the session null? Is there something I need to enable in order to read it?
Thanks in advance for your help.
You can not retrieve an SSO session property in OIDC claimscript because the OAuth2 client does not send the SSO tracking cookie in the token request.
It's only possible if you use AM proprietary feature 'always include claims in ID token'.
As described by Bernhard in the comments, once a request arrives to the /userinfo endpoint OpenAM has no way to reconcile the access token with a living session (and the session could not exist any more as well).
However when accessing the claims inside the ID Token by activating the proprietary AM feature "Always include claims in ID Token" the session object is available and we can poll its properties!
For future readers, this is how I modified the OIDC script:
/*
* The contents of this file are subject to the terms of the Common Development and
* Distribution License (the License). You may not use this file except in compliance with the
* License.
*
* You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
* specific language governing permission and limitations under the License.
*
* When distributing Covered Software, include this CDDL Header Notice in each file and include
* the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
* Header, with the fields enclosed by brackets [] replaced by your own identifying
* information: "Portions copyright [year] [name of copyright owner]".
*
* Copyright 2014-2016 ForgeRock AS.
*/
import com.iplanet.sso.SSOException
import com.sun.identity.idm.IdRepoException
import org.forgerock.oauth2.core.UserInfoClaims
/*
* Defined variables:
* logger - always presents, the "OAuth2Provider" debug logger instance
* claims - always present, default server provided claims
* session - present if the request contains the session cookie, the user's session object
* identity - always present, the identity of the resource owner
* scopes - always present, the requested scopes
* requestedClaims - Map<String, Set<String>>
* always present, not empty if the request contains a claims parameter and server has enabled
* claims_parameter_supported, map of requested claims to possible values, otherwise empty,
* requested claims with no requested values will have a key but no value in the map. A key with
* a single value in its Set indicates this is the only value that should be returned.
* Required to return a Map of claims to be added to the id_token claims
*
* Expected return value structure:
* UserInfoClaims {
* Map<String, Object> values; // The values of the claims for the user information
* Map<String, List<String>> compositeScopes; // Mapping of scope name to a list of claim names.
* }
*/
// user session not guaranteed to be present
boolean sessionPresent = session != null
def fromSet = { claim, attr ->
if (attr != null && attr.size() == 1){
attr.iterator().next()
} else if (attr != null && attr.size() > 1){
attr
} else if (logger.warningEnabled()) {
logger.warning("OpenAMScopeValidator.getUserInfo(): Got an empty result for claim=$claim");
}
}
attributeRetriever = { attribute, claim, identity, session, requested ->
if (requested == null || requested.isEmpty()) {
fromSet(claim, identity.getAttribute(attribute))
} else if (requested.size() == 1) {
requested.iterator().next()
} else {
throw new RuntimeException("No selection logic for $claim defined. Values: $requested")
}
}
sessionAttributeRetriever = { attribute, claim, identity, session, requested ->
if (requested == null || requested.isEmpty()) {
if (session != null) {
fromSet(claim, session.getProperty(attribute))
} else {
null
}
} else if (requested.size() == 1) {
requested.iterator().next()
} else {
throw new RuntimeException("No selection logic for $claim defined. Values: $requested")
}
}
// [ {claim}: {attribute retriever}, ... ]
claimAttributes = [
"email": attributeRetriever.curry("mail"),
"address": { claim, identity, session, requested -> [ "formatted" : attributeRetriever("postaladdress", claim, identity, session, requested) ] },
"phone_number": attributeRetriever.curry("telephonenumber"),
"given_name": attributeRetriever.curry("givenname"),
"zoneinfo": attributeRetriever.curry("preferredtimezone"),
"family_name": attributeRetriever.curry("sn"),
"locale": attributeRetriever.curry("preferredlocale"),
"name": attributeRetriever.curry("cn"),
"spid_uid": attributeRetriever.curry("employeeNumber"),
"spid_idp": attributeRetriever.curry("idpEntityId"),
"spid_gender": attributeRetriever.curry("description"),
"spid_authType": sessionAttributeRetriever.curry("AuthType"),
"spid_authLevel": sessionAttributeRetriever.curry("AuthLevel"),
]
// {scope}: [ {claim}, ... ]
scopeClaimsMap = [
"email": [ "email" ],
"address": [ "address" ],
"phone": [ "phone_number" ],
"profile": [ "given_name", "zoneinfo", "family_name", "locale", "name" ],
"spid": [ "spid_uid", "spid_idp", "spid_authType", "spid_authLevel", "spid_gender" ],
]
if (logger.messageEnabled()) {
scopes.findAll { s -> !("openid".equals(s) || scopeClaimsMap.containsKey(s)) }.each { s ->
logger.message("OpenAMScopeValidator.getUserInfo()::Message: scope not bound to claims: $s")
}
}
def computeClaim = { claim, requestedValues ->
try {
[ claim, claimAttributes.get(claim)(claim, identity, session, requestedValues) ]
} catch (IdRepoException e) {
if (logger.warningEnabled()) {
logger.warning("OpenAMScopeValidator.getUserInfo(): Unable to retrieve attribute=$attribute", e);
}
} catch (SSOException e) {
if (logger.warningEnabled()) {
logger.warning("OpenAMScopeValidator.getUserInfo(): Unable to retrieve attribute=$attribute", e);
}
}
}
def computedClaims = scopes.findAll { s -> !"openid".equals(s) && scopeClaimsMap.containsKey(s) }.inject(claims) { map, s ->
scopeClaims = scopeClaimsMap.get(s)
map << scopeClaims.findAll { c -> !requestedClaims.containsKey(c) }.collectEntries([:]) { claim -> computeClaim(claim, null) }
}.findAll { map -> map.value != null } << requestedClaims.collectEntries([:]) { claim, requestedValue ->
computeClaim(claim, requestedValue)
}
def compositeScopes = scopeClaimsMap.findAll { scope ->
scopes.contains(scope.key)
}
return new UserInfoClaims((Map)computedClaims, (Map)compositeScopes)
I also had to add the java.util.ArrayList$Itr class to the script classes whitelist.
Thanks for your help!

Test a Symfony REST API using Behat / Mink : prb with POST request

My challenge here is to find the best way to test a Symfony (3.4) API application using Behat/Mink for functionnal test, in my CICD platform.
Because my testing processes must be called in a shell script, all the tests must be very linear. I have no way to start a standalone webserver like Apache or the PHP/Symfony webserver. Also, Docker is not an option.
For the moment, I can successfully test the GET verbs of the API using the Mink syntax :
-- file test.feature
#function1
Scenario Outline: Test my api
When I go to "/api/v1/hello"
Then the response is JSON
The "I go to" instruction is implemented by Mink (http://docs.behat.org/en/v2.5/cookbook/behat_and_mink.html) and it emulates a GET request only. When this instruction is called by BeHat, the app Symfony kernel is "spawned" and the "api/v1/hello" method is called internally : there is no network trafic, no TCP connection, there is no need for a dedicated webserver (apache, or the symfony standalone server). It looks like Behat is emulating a webserver and start by itself the Symfony app it its own user space.
Now I want to test the POST verbs of my API, with a json payload, but unfortunally Mink do not have other verbs than GET.
I have read some articles over the web (keyword : behat test post api) but all I have seen is based on a Guzzl/Curl client. So a real client-to-server connection is made to http://localhost and a real webserver have to respond to the request.
I want the Symfony API to be called internally without using an other webserver.
Is there a way to do that ? How to test a Symfony REST API and specially the POST verb without needing a standalone server to reply ?
Thank you.
Here is how I do a functional test of a POST API, with BeHat, without a local running webserver :
test.feature :
#function1
Scenario Outline: Test my api
Given I have the payload
"""
{ "data":"object"}
"""
When I request "POST /api/v1/post"
Then the response is JSON
The featureContext file implement two functions :
"I Have The Payload" : See here https://github.com/philsturgeon/build-apis-you-wont-hate/blob/master/chapter8/app/tests/behat/features/bootstrap/FeatureContext.php
"I request" : based on code provided by philsturgeon just above, I modify it to have something like that :
/**
* #When /^I request "(GET|PUT|POST|DELETE|PATCH) ([^"]*)"$/
*/
public function iRequest($httpMethod, $resource)
{
$this->lastResponse = $this->lastRequest = null;
$this->iAmOnHomepage();
$method = strtoupper($httpMethod);
$components = parse_url($this->getSession()->getCurrentUrl());
$baseUrl = $components['scheme'].'://'.$components['host'];
$this->requestUrl = $baseUrl.$resource;
$formParams = json_decode($this->requestPayload, true);
$formParamsList = [];
foreach($formParams as $param => $value) {
$formParamsList[$param] = json_encode($value);
}
// Construct request
$headers = [
'Accept'=>'application/json',
'Content-Type'=>'application/x-www-form-urlencoded'
];
try {
// Magic is here : allow to simulate any HTTP verb
$client = $this->getSession()->getDriver()->getClient();
$client->request(
$method,
$this->requestUrl,
$formParamsList,
[],
$headers,
null);
} catch (BadResponseException $e) {
$response = $e->getResponse();
// Sometimes the request will fail, at which point we have
// no response at all. Let Guzzle give an error here, it's
// pretty self-explanatory.
if (null === $response) {
throw $e;
}
$this->lastResponse = $e->getResponse();
throw new \Exception('Bad response.');
}
}
If you use Mink then it is quite easy
class FeatureContext extends RawMinkContext
{
/**
* #When make POST request to some Uri
*/
public function makePostRequestToSomeUri(): void
{
$uri = '/some-end-point';
/** #var \Symfony\Component\BrowserKit\Client $client */
$client = $this->getSession()->getDriver()->getClient();
$postParams = [];
$files = [];
$serverParams = [];
$rawContent = '';
$client->request(
\Symfony\Component\HttpFoundation\Request::METHOD_POST,
$uri,
$postParams,
$files,
$serverParams,
$rawContent
);
/** #var \Symfony\Component\HttpFoundation\Response $response */
$response = $client->getResponse();
//...
}
}

Is it possible to secure a ColdFusion 11 REST Service with HTTP BASIC Authentication?

I am setting up a simple REST Service in ColdFusion 11. The web server is IIS 8.5 on Windows Server 2012R2.
This REST Service needs to be secured to prevent unauthorized users from accessing/writing data. For the time being, there will be only one authorized user, so I want to keep authentication/authorization as simple as possible. My initial thought is to use HTTP BASIC Authentication.
Here's the setup for the REST Service:
Source Directory: C:\web\site1\remoteapi\
REST path: inventory
To implement this, I configured the source directory of the REST Service in IIS to authorize only one user, disable Anonymous authentication, and enable Basic authentication.
When I call the source directory directly in a browser (i.e. http://site1/remoteapi/inventory.cfc?method=read), I am presented with the Basic authentication dialog.
However, when I attempt to request the REST path (http://site1/rest/inventory/), I am not challenged at all.
How can I implement HTTP BASIC authentication on the REST path?
So, due to the need to get this done without much delay, I went ahead and using some principles from Ben Nadel's website, I wrote my own authentication into the onRequestStart() method of the REST Service's Application.cfc. Here is the basic code, though it uses hard-coded values in the VARIABLES scope to validate the username and password and also does not include any actual "authorization" setting:
public boolean function onRequestStart(required string targetPage) {
LOCAL.Response = SUPER.onRequestStart(ARGUMENTS.targetpage);
if (!StructKeyExists(GetHTTPRequestData().Headers, "Authorization")) {
cfheader(
name="WWW-Authenticate",
value="Basic realm=""REST API Access"""
);
LOCAL.RESTResponse = {
status = 401,
content = {Message = "Unauthorized"}
};
restSetResponse(LOCAL.RESTResponse);
}
else {
LOCAL.IsAuthenticated = true;
LOCAL.EncodedCredentials =
GetToken( GetHTTPRequestData().Headers.Authorization, 2, " " );
// Credential string is not Base64
if ( !ArrayLen(
REMatch(
"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$",
LOCAL.EncodedCredentials
)
)
) {
LOCAL.IsAuthenticated = false;
}
else {
// Convert Base64 to String
LOCAL.Credentials =
ToString(ToBinary( LOCAL.EncodedCredentials ));
LOCAL.Username = GetToken( LOCAL.Credentials, 1, ":" );
LOCAL.Password = GetToken( LOCAL.Credentials, 2, ":" );
if ( LOCAL.Username != VARIABLES.CREDENTIALS.Username
|| LOCAL.Password != VARIABLES.CREDENTIALS.Password
) {
LOCAL.IsAuthenticated = false;
}
}
if (!LOCAL.IsAuthenticated) {
LOCAL.Response = {
status = 403,
content = {Message = "Forbidden"}
};
restSetResponse(LOCAL.Response);
}
}
return LOCAL.Response;
}

SIGPIPE (Broken pipe) on tcp_disconnect to exec a client (WCF Soap 1.1 and server)

I am developing a Qt client (C++) with gSOAP lib, which is supposed to discuss with a Web Service by Microsoft (WCF). I use SOAP 1.1 on both sides.
My client code is as follows :
CustomBinding_USCOREISynchronisation service;
soap_ssl_init(); /* init OpenSSL (just once) */
soap_init2(service.soap, SOAP_IO_KEEPALIVE, SOAP_IO_KEEPALIVE);
service.soap->max_keep_alive = 1000; // at most 100 calls per keep-alive session
service.soap->accept_timeout = 6000; // optional: let server time out after ten minutes of inactivity
if (soap_ssl_client_context(service.soap,
SOAP_SSL_NO_AUTHENTICATION,
NULL, /* keyfile: required only when client must authenticate to server (see SSL docs on how to obtain this file) */
NULL, /* password to read the key file (not used with GNUTLS) */
NULL, /* cacert file to store trusted certificates (needed to verify server) */ NULL, /* capath to directory with trusted certificates */
NULL /* if randfile!=NULL: use a file with random data to seed randomness */
))
{
soap_print_fault(service.soap, stderr);
exit(1);
}
_ns1__Connect req;
_ns1__ConnectResponse resp;
std::string strLogin = "tata#gmail.com";
std::string strPassword = "681982981298192891287B0A";
bool bInternalUser = true;
req.login = &strLogin;
req.password = &strPassword;
req.isInternalUser = &bInternalUser;
int err = service.__ns1__Connect(&req, &resp);
if (SOAP_OK == err)
qDebug() << ":D";
else
{
qDebug() << "Error : " << err;
soap_print_fault(service.soap, stderr);
}
qDebug() << "Result of Connect : " << resp.ConnectResult;
Problem: when I execute the program, I get a SIGPIPE (Broken pipe) in the "tcp_disconnect" function, on the exactly line "r = SSL_shutdown (soap-> ssl);".
Error message generated:
Error -1 fault: SOAP-ENV: Client [no subcode]
"End of file or no input: Operation interrupted or timed out"
Detail: [no detail]
Do you have any idea why? If you need more resources or information, please let me know!
A big thank in advance,
Louep.