use of org.apache.knox.gateway.services.security.KeystoreServiceException in project knox by apache.
the class DefaultTokenAuthorityService method issueToken.
@Override
public JWT issueToken(Principal p, List<String> audiences, String algorithm, long expires) throws TokenServiceException {
String[] claimArray = new String[4];
claimArray[0] = "KNOXSSO";
claimArray[1] = p.getName();
claimArray[2] = null;
if (expires == -1) {
claimArray[3] = null;
} else {
claimArray[3] = String.valueOf(expires);
}
JWT token = null;
if (SUPPORTED_SIG_ALGS.contains(algorithm)) {
token = new JWTToken(algorithm, claimArray, audiences);
RSAPrivateKey key;
char[] passphrase = null;
try {
passphrase = getSigningKeyPassphrase();
} catch (AliasServiceException e) {
throw new TokenServiceException(e);
}
try {
key = (RSAPrivateKey) ks.getSigningKey(getSigningKeyAlias(), passphrase);
JWSSigner signer = new RSASSASigner(key);
token.sign(signer);
} catch (KeystoreServiceException e) {
throw new TokenServiceException(e);
}
} else {
throw new TokenServiceException("Cannot issue token - Unsupported algorithm");
}
return token;
}
use of org.apache.knox.gateway.services.security.KeystoreServiceException in project knox by apache.
the class DefaultTokenAuthorityService method init.
@Override
public void init(GatewayConfig config, Map<String, String> options) throws ServiceLifecycleException {
if (as == null || ks == null) {
throw new ServiceLifecycleException("Alias or Keystore service is not set");
}
signingKeyAlias = config.getSigningKeyAlias();
@SuppressWarnings("unused") RSAPrivateKey key;
char[] passphrase = null;
try {
passphrase = as.getPasswordFromAliasForGateway(SIGNING_KEY_PASSPHRASE);
if (passphrase != null) {
key = (RSAPrivateKey) ks.getSigningKey(getSigningKeyAlias(), passphrase);
if (key == null) {
throw new ServiceLifecycleException("Provisioned passphrase cannot be used to acquire signing key.");
}
}
} catch (AliasServiceException e) {
throw new ServiceLifecycleException("Provisioned signing key passphrase cannot be acquired.", e);
} catch (KeystoreServiceException e) {
throw new ServiceLifecycleException("Provisioned signing key passphrase cannot be acquired.", e);
}
}
use of org.apache.knox.gateway.services.security.KeystoreServiceException in project knox by apache.
the class TokenResource method getAuthenticationToken.
private Response getAuthenticationToken() {
if (clientCertRequired) {
X509Certificate cert = extractCertificate(request);
if (cert != null) {
if (!allowedDNs.contains(cert.getSubjectDN().getName().replaceAll("\\s+", ""))) {
return Response.status(Response.Status.FORBIDDEN).entity("{ \"Unable to get token - untrusted client cert.\" }").build();
}
} else {
return Response.status(Response.Status.FORBIDDEN).entity("{ \"Unable to get token - client cert required.\" }").build();
}
}
GatewayServices services = (GatewayServices) request.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
JWTokenAuthority ts = services.getService(ServiceType.TOKEN_SERVICE);
Principal p = request.getUserPrincipal();
long expires = getExpiry();
if (endpointPublicCert == null) {
// acquire PEM for gateway identity of this gateway instance
KeystoreService ks = services.getService(ServiceType.KEYSTORE_SERVICE);
if (ks != null) {
try {
Certificate cert = ks.getCertificateForGateway();
byte[] bytes = cert.getEncoded();
endpointPublicCert = Base64.encodeBase64String(bytes);
} catch (KeyStoreException | KeystoreServiceException | CertificateEncodingException e) {
// assuming that certs will be properly provisioned across all clients
log.unableToAcquireCertForEndpointClients(e);
}
}
}
String jku = null;
/* remove .../token and replace it with ..../jwks.json */
final int idx = request.getRequestURL().lastIndexOf("/");
if (idx > 1) {
jku = request.getRequestURL().substring(0, idx) + JWKSResource.JWKS_PATH;
}
if (tokenStateService != null) {
if (tokenLimitPerUser != -1) {
// if -1 => unlimited tokens for all users
if (tokenStateService.getTokens(p.getName()).size() >= tokenLimitPerUser) {
log.tokenLimitExceeded(p.getName());
return Response.status(Response.Status.FORBIDDEN).entity("{ \"Unable to get token - token limit exceeded.\" }").build();
}
}
}
try {
final boolean managedToken = tokenStateService != null;
JWT token;
JWTokenAttributes jwtAttributes;
final JWTokenAttributesBuilder jwtAttributesBuilder = new JWTokenAttributesBuilder();
jwtAttributesBuilder.setPrincipal(p).setAlgorithm(signatureAlgorithm).setExpires(expires).setManaged(managedToken).setJku(jku).setType(tokenType);
if (!targetAudiences.isEmpty()) {
jwtAttributesBuilder.setAudiences(targetAudiences);
}
jwtAttributes = jwtAttributesBuilder.build();
token = ts.issueToken(jwtAttributes);
if (token != null) {
String accessToken = token.toString();
String tokenId = TokenUtils.getTokenId(token);
log.issuedToken(getTopologyName(), Tokens.getTokenDisplayText(accessToken), Tokens.getTokenIDDisplayText(tokenId));
final HashMap<String, Object> map = new HashMap<>();
map.put(ACCESS_TOKEN, accessToken);
map.put(TOKEN_ID, tokenId);
map.put(MANAGED_TOKEN, String.valueOf(managedToken));
map.put(TOKEN_TYPE, BEARER);
map.put(EXPIRES_IN, expires);
if (tokenTargetUrl != null) {
map.put(TARGET_URL, tokenTargetUrl);
}
if (tokenClientDataMap != null) {
map.putAll(tokenClientDataMap);
}
if (endpointPublicCert != null) {
map.put(ENDPOINT_PUBLIC_CERT, endpointPublicCert);
}
final String passcode = UUID.randomUUID().toString();
map.put(PASSCODE, generatePasscodeField(tokenId, passcode));
String jsonResponse = JsonUtils.renderAsJsonString(map);
// Optional token store service persistence
if (tokenStateService != null) {
final long issueTime = System.currentTimeMillis();
tokenStateService.addToken(tokenId, issueTime, expires, maxTokenLifetime.orElse(tokenStateService.getDefaultMaxLifetimeDuration()));
final String comment = request.getParameter(COMMENT);
final TokenMetadata tokenMetadata = new TokenMetadata(p.getName(), StringUtils.isBlank(comment) ? null : comment);
tokenMetadata.setPasscode(tokenMAC.hash(tokenId, issueTime, p.getName(), passcode));
tokenStateService.addMetadata(tokenId, tokenMetadata);
log.storedToken(getTopologyName(), Tokens.getTokenDisplayText(accessToken), Tokens.getTokenIDDisplayText(tokenId));
}
return Response.ok().entity(jsonResponse).build();
} else {
return Response.serverError().build();
}
} catch (TokenServiceException e) {
log.unableToIssueToken(e);
}
return Response.ok().entity("{ \"Unable to acquire token.\" }").build();
}
use of org.apache.knox.gateway.services.security.KeystoreServiceException in project knox by apache.
the class DefaultKeystoreService method createKeyStore.
// Package private for unit test access
// We need this to be synchronized to prevent multiple threads from using at once
synchronized KeyStore createKeyStore(Path keystoreFilePath, String keystoreType, char[] password) throws KeystoreServiceException {
// Ensure the parent directory exists...
// This is symlink safe.
Path parentPath = keystoreFilePath.getParent();
if (parentPath != null && !Files.isDirectory(parentPath)) {
try {
// This will attempt to create all missing directories. No failures will occur if the
// directories already exist.
Files.createDirectories(parentPath);
} catch (IOException e) {
LOG.failedToCreateKeystore(keystoreFilePath.toString(), keystoreType, e);
throw new KeystoreServiceException(e);
}
}
try {
KeyStore ks = KeyStore.getInstance(keystoreType);
ks.load(null, null);
writeKeyStoreToFile(ks, keystoreFilePath, password);
return ks;
} catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) {
LOG.failedToCreateKeystore(keystoreFilePath.toString(), keystoreType, e);
throw new KeystoreServiceException(e);
}
}
use of org.apache.knox.gateway.services.security.KeystoreServiceException in project knox by apache.
the class DefaultCryptoService method verify.
@Override
public boolean verify(String algorithm, String signed, byte[] signature) {
boolean verified = false;
try {
Signature sig = Signature.getInstance(algorithm);
sig.initVerify(keystoreService.getCertificateForGateway().getPublicKey());
sig.update(signed.getBytes(StandardCharsets.UTF_8));
verified = sig.verify(signature);
} catch (SignatureException | KeystoreServiceException | InvalidKeyException | NoSuchAlgorithmException | KeyStoreException e) {
LOG.failedToVerifySignature(e);
}
LOG.signatureVerified(verified);
return verified;
}
Aggregations