Search in sources :

Example 1 with Key

use of com.macasaet.fernet.Key in project fernet-java8 by l0s.

the class AuthenticationResource method createSession.

/**
 * This is an example of an endpoint that generates a new Fernet token. The
 * client authenticates using this method then can use the token provided to
 * perform secured operations. The client may, at their discretion, store
 * the token insecurely (e.g. in a cookie or browser storage) since it will
 * no longer be valid after the TTL (60 seconds by default).
 *
 * @param request
 *            client credentials to create a new session token
 * @return a Fernet token
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String createSession(final LoginRequest request) {
    final User user = repository.findUser(request.getUsername());
    if (user != null && user.isPasswordCorrect(request.getSingleRoundPasswordHash())) {
        // password is correct, so generate an ephemeral session
        // store the session ID in the token payload
        final Session session = new Session(request.getUsername());
        sessionRepository.saveSession(session);
        final Key key = keySupplier.get().iterator().next();
        final Token token = Token.generate(random, key, session.getId().toString());
        return token.serialise();
    }
    throw new NotAuthorizedException(Response.status(Status.UNAUTHORIZED).entity("invalid login").build());
}
Also used : Token(com.macasaet.fernet.Token) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Key(com.macasaet.fernet.Key) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

Example 2 with Key

use of com.macasaet.fernet.Key in project fernet-java8 by l0s.

the class TokenInjectionIT method verifyFailedForgery.

/**
 * This demonstrates a client who attempts to forge a Fernet token but
 * cannot do so without knowing the secret key.
 */
@Test
public final void verifyFailedForgery() {
    // given
    final SecureRandom random = new SecureRandom();
    final Key invalidKey = Key.generateKey(random);
    final Token forgedToken = Token.generate(random, invalidKey, UUID.randomUUID().toString());
    final String tokenString = forgedToken.serialise();
    // when / then
    assertThrows(ForbiddenException.class, () -> target("secrets").request().header("Authorization", "Bearer\t" + tokenString).get(String.class));
}
Also used : SecureRandom(java.security.SecureRandom) Token(com.macasaet.fernet.Token) Key(com.macasaet.fernet.Key) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 3 with Key

use of com.macasaet.fernet.Key in project fernet-java8 by l0s.

the class CreateSimpleKey method main.

public static final void main(final String... args) throws Exception {
    final SecureRandom random = new SecureRandom();
    final Key key = Key.generateKey(random);
    try (FileOutputStream outputStream = new FileOutputStream("simple-key")) {
        key.writeTo(outputStream);
    }
/*
          aws secretsmanager create-secret --name simple-fernet-key --secret-binary fileb://simple-key
          {
               "ARN": "arn:aws:secretsmanager:<region>:<account_id>:secret:simple-fernet-key-<random_value>",
               "Name": "simple-fernet-key",
               "VersionId": "<uuidv4>"
           }
         */
}
Also used : FileOutputStream(java.io.FileOutputStream) SecureRandom(java.security.SecureRandom) Key(com.macasaet.fernet.Key)

Example 4 with Key

use of com.macasaet.fernet.Key in project fernet-java8 by l0s.

the class SecretsManagerTest method verifyPutSecretValueStoresKey.

@Test
public final void verifyPutSecretValueStoresKey() throws IOException {
    // given
    final String expected = "expected";
    final Key key = mock(Key.class);
    final Answer<?> answer = new Answer<Void>() {

        public Void answer(final InvocationOnMock invocation) throws Throwable {
            final OutputStream stream = invocation.getArgument(0);
            stream.write(expected.getBytes("UTF-8"));
            return null;
        }
    };
    doAnswer(answer).when(key).writeTo(any(OutputStream.class));
    // when
    manager.putSecretValue("secret", "version", key, PREVIOUS);
    // then
    final PutSecretValueRequest request = new PutSecretValueRequest();
    request.setSecretId("secret");
    request.setClientRequestToken("version");
    request.setVersionStages(singleton("AWSPREVIOUS"));
    request.setSecretBinary(ByteBuffer.wrap(expected.getBytes("UTF-8")));
    verify(delegate).putSecretValue(eq(request));
}
Also used : Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) PutSecretValueRequest(com.amazonaws.services.secretsmanager.model.PutSecretValueRequest) InvocationOnMock(org.mockito.invocation.InvocationOnMock) OutputStream(java.io.OutputStream) Key(com.macasaet.fernet.Key) Test(org.junit.Test)

Example 5 with Key

use of com.macasaet.fernet.Key in project fernet-java8 by l0s.

the class MultiFernetKeyRotator method createSecret.

@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
protected void createSecret(final String secretId, final String clientRequestToken) {
    final ByteBuffer currentSecret = getSecretsManager().getSecretStage(secretId, CURRENT);
    try {
        if (currentSecret.remaining() % fernetKeySize != 0) {
            throw new IllegalStateException("There must be a multiple of 32 bytes.");
        }
        final int numKeys = currentSecret.remaining() / fernetKeySize;
        List<Key> keys = new ArrayList<>(numKeys + 1);
        while (currentSecret.hasRemaining()) {
            final byte[] signingKey = new byte[16];
            currentSecret.get(signingKey);
            final byte[] encryptionKey = new byte[16];
            currentSecret.get(encryptionKey);
            final Key key = new Key(signingKey, encryptionKey);
            keys.add(key);
            wipe(signingKey);
            wipe(encryptionKey);
        }
        final Key keyToStage = Key.generateKey(getRandom());
        keys.add(0, keyToStage);
        // max active keys + one pending
        final int desiredSize = getMaxActiveKeys() + 1;
        if (keys.size() > desiredSize) {
            keys = keys.subList(0, desiredSize);
        }
        getSecretsManager().putSecretValue(secretId, clientRequestToken, keys, PENDING);
    } finally {
        wipe(currentSecret);
    }
    getLogger().info("createSecret: Successfully put secret for ARN {} and version {}.", secretId, clientRequestToken);
}
Also used : ArrayList(java.util.ArrayList) ByteBuffer(java.nio.ByteBuffer) Key(com.macasaet.fernet.Key)

Aggregations

Key (com.macasaet.fernet.Key)23 Test (org.junit.Test)12 Token (com.macasaet.fernet.Token)10 SecureRandom (java.security.SecureRandom)5 NotAuthorizedException (javax.ws.rs.NotAuthorizedException)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 ByteBuffer (java.nio.ByteBuffer)4 ContainerRequest (org.glassfish.jersey.server.ContainerRequest)4 Context (com.amazonaws.services.lambda.runtime.Context)3 DescribeSecretResult (com.amazonaws.services.secretsmanager.model.DescribeSecretResult)3 PutSecretValueRequest (com.amazonaws.services.secretsmanager.model.PutSecretValueRequest)3 InputStream (java.io.InputStream)3 OutputStream (java.io.OutputStream)3 JerseyTest (org.glassfish.jersey.test.JerseyTest)3 StringInputStream (com.amazonaws.util.StringInputStream)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 FileOutputStream (java.io.FileOutputStream)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2