Search in sources :

Example 1 with JWTVerificationException

use of com.auth0.jwt.exceptions.JWTVerificationException in project open-kilda by telstra.

the class PathVerificationService method handlePacketIn.

private IListener.Command handlePacketIn(IOFSwitch sw, OFPacketIn pkt, FloodlightContext context) {
    long time = System.currentTimeMillis();
    logger.debug("packet_in {} received from {}", pkt.getXid(), sw.getId());
    VerificationPacket verificationPacket = null;
    Ethernet eth = IFloodlightProviderService.bcStore.get(context, IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
    try {
        verificationPacket = deserialize(eth);
    } catch (Exception exception) {
        logger.error("Deserialization failure: {}, exception: {}", exception.getMessage(), exception);
        return Command.CONTINUE;
    }
    try {
        OFPort inPort = pkt.getVersion().compareTo(OFVersion.OF_12) < 0 ? pkt.getInPort() : pkt.getMatch().get(MatchField.IN_PORT);
        ByteBuffer portBB = ByteBuffer.wrap(verificationPacket.getPortId().getValue());
        portBB.position(1);
        OFPort remotePort = OFPort.of(portBB.getShort());
        long timestamp = 0;
        int pathOrdinal = 10;
        IOFSwitch remoteSwitch = null;
        boolean signed = false;
        for (LLDPTLV lldptlv : verificationPacket.getOptionalTLVList()) {
            if (lldptlv.getType() == 127 && lldptlv.getLength() == 12 && lldptlv.getValue()[0] == 0x0 && lldptlv.getValue()[1] == 0x26 && lldptlv.getValue()[2] == (byte) 0xe1 && lldptlv.getValue()[3] == 0x0) {
                ByteBuffer dpidBB = ByteBuffer.wrap(lldptlv.getValue());
                remoteSwitch = switchService.getSwitch(DatapathId.of(dpidBB.getLong(4)));
            } else if (lldptlv.getType() == 127 && lldptlv.getLength() == 12 && lldptlv.getValue()[0] == 0x0 && lldptlv.getValue()[1] == 0x26 && lldptlv.getValue()[2] == (byte) 0xe1 && lldptlv.getValue()[3] == 0x01) {
                ByteBuffer tsBB = ByteBuffer.wrap(lldptlv.getValue());
                /* skip OpenFlow OUI (4 bytes above) */
                long swLatency = sw.getLatency().getValue();
                timestamp = tsBB.getLong(4);
                /* include the RX switch latency to "subtract" it */
                timestamp = timestamp + swLatency;
            } else if (lldptlv.getType() == 127 && lldptlv.getLength() == 8 && lldptlv.getValue()[0] == 0x0 && lldptlv.getValue()[1] == 0x26 && lldptlv.getValue()[2] == (byte) 0xe1 && lldptlv.getValue()[3] == 0x02) {
                ByteBuffer typeBB = ByteBuffer.wrap(lldptlv.getValue());
                pathOrdinal = typeBB.getInt(4);
            } else if (lldptlv.getType() == 127 && lldptlv.getValue()[0] == 0x0 && lldptlv.getValue()[1] == 0x26 && lldptlv.getValue()[2] == (byte) 0xe1 && lldptlv.getValue()[3] == 0x03) {
                ByteBuffer bb = ByteBuffer.wrap(lldptlv.getValue());
                bb.position(4);
                byte[] tokenArray = new byte[lldptlv.getLength() - 4];
                bb.get(tokenArray, 0, tokenArray.length);
                String token = new String(tokenArray);
                try {
                    DecodedJWT jwt = verifier.verify(token);
                    signed = true;
                } catch (JWTVerificationException e) {
                    logger.error("Packet verification failed", e);
                    return Command.STOP;
                }
            }
        }
        if (remoteSwitch == null) {
            return Command.STOP;
        }
        if (!signed) {
            logger.warn("verification packet without sign");
            return Command.STOP;
        }
        U64 latency = (timestamp != 0 && (time - timestamp) > 0) ? U64.of(time - timestamp) : U64.ZERO;
        logger.debug("link discovered: {}-{} ===( {} ms )===> {}-{}", remoteSwitch.getId(), remotePort, latency.getValue(), sw.getId(), inPort);
        // this verification packet was sent from remote switch/port to received switch/port
        // so the link direction is from remote switch/port to received switch/port
        List<PathNode> nodes = Arrays.asList(new PathNode(remoteSwitch.getId().toString(), remotePort.getPortNumber(), 0, latency.getValue()), new PathNode(sw.getId().toString(), inPort.getPortNumber(), 1));
        OFPortDesc port = sw.getPort(inPort);
        long speed = Integer.MAX_VALUE;
        if (port.getVersion().compareTo(OFVersion.OF_13) > 0) {
            for (OFPortDescProp prop : port.getProperties()) {
                if (prop.getType() == 0x0) {
                    speed = ((OFPortDescPropEthernet) prop).getCurrSpeed();
                }
            }
        } else {
            speed = port.getCurrSpeed();
        }
        IslInfoData path = new IslInfoData(latency.getValue(), nodes, speed, IslChangeType.DISCOVERED, getAvailableBandwidth(speed));
        Message message = new InfoMessage(path, System.currentTimeMillis(), "system", null);
        final String json = MAPPER.writeValueAsString(message);
        logger.debug("about to send {}", json);
        producer.send(new ProducerRecord<>(TOPIC, json));
        logger.debug("packet_in processed for {}-{}", sw.getId(), inPort);
    } catch (JsonProcessingException exception) {
        logger.error("could not create json for path packet_in: {}", exception.getMessage(), exception);
    } catch (UnsupportedOperationException exception) {
        logger.error("could not parse packet_in message: {}", exception.getMessage(), exception);
    } catch (Exception exception) {
        logger.error("unknown error during packet_in message processing: {}", exception.getMessage(), exception);
        throw exception;
    }
    return Command.STOP;
}
Also used : IOFSwitch(net.floodlightcontroller.core.IOFSwitch) InfoMessage(org.openkilda.messaging.info.InfoMessage) OFMessage(org.projectfloodlight.openflow.protocol.OFMessage) Message(org.openkilda.messaging.Message) OFPortDescProp(org.projectfloodlight.openflow.protocol.OFPortDescProp) PathNode(org.openkilda.messaging.info.event.PathNode) ByteBuffer(java.nio.ByteBuffer) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) FloodlightModuleException(net.floodlightcontroller.core.module.FloodlightModuleException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) U64(org.projectfloodlight.openflow.types.U64) OFPortDesc(org.projectfloodlight.openflow.protocol.OFPortDesc) InfoMessage(org.openkilda.messaging.info.InfoMessage) OFPortDescPropEthernet(org.projectfloodlight.openflow.protocol.OFPortDescPropEthernet) Ethernet(net.floodlightcontroller.packet.Ethernet) OFPort(org.projectfloodlight.openflow.types.OFPort) IslInfoData(org.openkilda.messaging.info.event.IslInfoData) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) LLDPTLV(net.floodlightcontroller.packet.LLDPTLV)

Example 2 with JWTVerificationException

use of com.auth0.jwt.exceptions.JWTVerificationException in project java-docs-samples by GoogleCloudPlatform.

the class GoogleRSAKeyProvider method getNewCertificate.

@SuppressWarnings("unchecked")
private Map<String, String> getNewCertificate() {
    Gson gson = new Gson();
    String result;
    try {
        result = new Downloader().download(GOOGLEAPIS_CERTS);
    } catch (IOException e) {
        throw new JWTVerificationException("Could not download public Googleapis certs.", e);
    }
    return (Map<String, String>) gson.fromJson(result, HashMap.class);
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) HashMap(java.util.HashMap) Gson(com.google.gson.Gson) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with JWTVerificationException

use of com.auth0.jwt.exceptions.JWTVerificationException in project java-docs-samples by GoogleCloudPlatform.

the class GoogleRSAKeyProvider method transformPemCertificateToRsaKey.

private RSAPublicKey transformPemCertificateToRsaKey(String cert) {
    try {
        InputStream is = new ByteArrayInputStream(cert.getBytes());
        Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(is);
        is.close();
        return safelyCastToRsaPublicKey(certificate.getPublicKey());
    } catch (CertificateException e) {
        throw new JWTVerificationException("Could not extract RSA key from certificate String.", e);
    } catch (IOException e) {
        // Thrown when closing input stream. Built on in-memory array. From immutable String.
        throw new RuntimeException(e);
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) Certificate(java.security.cert.Certificate)

Example 4 with JWTVerificationException

use of com.auth0.jwt.exceptions.JWTVerificationException in project java-docs-samples by GoogleCloudPlatform.

the class VerifyingInstance method verifyToken.

void verifyToken(String token) {
    TokenVerifier gtv = new TokenVerifier();
    // Following are examples how to handle verification failure.
    try {
        DecodedGoogleJWTWrapper decodedJwt = gtv.verifyWithAudience(audience, token);
        System.out.println("Project id : " + decodedJwt.getProjectId());
        System.out.println("Project number : " + decodedJwt.getProjectNumber());
    // This are examples how to handle exceptions, which indicate verification failure.
    } catch (AlgorithmMismatchException e) {
        // We assume that downloaded certs are RSA256, this exception will happen if this changes.
        throw e;
    } catch (SignatureVerificationException e) {
        // Could not verify signature of a token, possibly someone provided forged token.
        throw e;
    } catch (TokenExpiredException e) {
        // We encountered old token, possibly replay attack.
        throw e;
    } catch (InvalidClaimException e) {
        // Different Audience for token and for verification, possibly token for other verifier.
        throw e;
    } catch (JWTVerificationException e) {
        // - InvalidClaimException
        throw e;
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) TokenVerifier(com.example.compute.signedmetadata.token.TokenVerifier) DecodedGoogleJWTWrapper(com.example.compute.signedmetadata.token.DecodedGoogleJWTWrapper) SignatureVerificationException(com.auth0.jwt.exceptions.SignatureVerificationException) InvalidClaimException(com.auth0.jwt.exceptions.InvalidClaimException) AlgorithmMismatchException(com.auth0.jwt.exceptions.AlgorithmMismatchException)

Example 5 with JWTVerificationException

use of com.auth0.jwt.exceptions.JWTVerificationException in project yyl_example by Relucent.

the class JwtDemo method main.

public static void main(String[] args) throws Exception {
    long currentMillis = System.currentTimeMillis();
    // JWT 生存时间(5秒)
    long ttl = 5000;
    // 生成JWT的时间
    Date iat = new Date(currentMillis);
    // 生成JWT失效时间
    Date exp = new Date(currentMillis + ttl);
    // 签名秘钥
    String secret = "key";
    // 签发人
    String issuer = "root";
    // 算法
    Algorithm algorithm = Algorithm.HMAC256(secret);
    // 本地的密码解码
    JWTCreator.Builder builder = JWT.create();
    // 签发时间
    builder.withIssuedAt(iat);
    // 签发人
    builder.withIssuer(issuer);
    // 过期时间
    builder.withExpiresAt(exp);
    // 主题
    builder.withClaim("subject", "MySubject");
    String token = builder.sign(algorithm);
    System.out.println(token);
    // 解密
    JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();
    DecodedJWT jwt = verifier.verify(token);
    Map<String, Claim> claims = jwt.getClaims();
    NullClaim nullClaim = new NullClaim();
    System.out.println(claims.getOrDefault("subject", nullClaim).asString());
    // 等待5秒
    System.out.println("Wait 5 seconds!");
    Thread.sleep(5000);
    try {
        // 这时候Token已经超时了,会抛出异常
        verifier.verify(token);
    } catch (JWTVerificationException e) {
        System.err.println(e);
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JWTCreator(com.auth0.jwt.JWTCreator) NullClaim(com.auth0.jwt.impl.NullClaim) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date) NullClaim(com.auth0.jwt.impl.NullClaim) Claim(com.auth0.jwt.interfaces.Claim)

Aggregations

JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)11 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)7 Claim (com.auth0.jwt.interfaces.Claim)5 Algorithm (com.auth0.jwt.algorithms.Algorithm)2 IOException (java.io.IOException)2 ByteBuffer (java.nio.ByteBuffer)2 LLDPTLV (net.floodlightcontroller.packet.LLDPTLV)2 OFPort (org.projectfloodlight.openflow.types.OFPort)2 JWTCreator (com.auth0.jwt.JWTCreator)1 JWTVerifier (com.auth0.jwt.JWTVerifier)1 AlgorithmMismatchException (com.auth0.jwt.exceptions.AlgorithmMismatchException)1 InvalidClaimException (com.auth0.jwt.exceptions.InvalidClaimException)1 SignatureVerificationException (com.auth0.jwt.exceptions.SignatureVerificationException)1 TokenExpiredException (com.auth0.jwt.exceptions.TokenExpiredException)1 NullClaim (com.auth0.jwt.impl.NullClaim)1 DecodedGoogleJWTWrapper (com.example.compute.signedmetadata.token.DecodedGoogleJWTWrapper)1 TokenVerifier (com.example.compute.signedmetadata.token.TokenVerifier)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Gson (com.google.gson.Gson)1