use of com.auth0.jwt.JWT 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;
}
use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.
the class AuthenticationSuccessFilter method doFilter.
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) servletRequest;
final Optional<Cookie> optionalStringToken;
if (req.getCookies() == null) {
optionalStringToken = Optional.empty();
} else {
optionalStringToken = Arrays.stream(req.getCookies()).filter(cookie -> HttpHeaders.AUTHORIZATION.equals(cookie.getName())).filter(cookie -> cookie.getValue() != null && !cookie.getValue().isEmpty()).findAny();
}
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && !optionalStringToken.isPresent()) {
// JWT signer
final Map<String, Object> claims = new HashMap<>();
claims.put(Claims.ISSUER, jwtIssuer);
final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// Manage authorities, initialize it with dynamic permissions from the IDP
Set<GrantedAuthority> authorities = new HashSet<>(userDetails.getAuthorities());
// We must also load permissions from repository for configured management or portal role
RoleEntity role = membershipService.getRole(MembershipReferenceType.MANAGEMENT, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.MANAGEMENT);
if (role != null) {
authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
}
role = membershipService.getRole(MembershipReferenceType.PORTAL, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.PORTAL);
if (role != null) {
authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
}
claims.put(Claims.PERMISSIONS, authorities);
claims.put(Claims.SUBJECT, userDetails.getUsername());
claims.put(Claims.EMAIL, userDetails.getEmail());
claims.put(Claims.FIRSTNAME, userDetails.getFirstname());
claims.put(Claims.LASTNAME, userDetails.getLastname());
final JWTSigner.Options options = new JWTSigner.Options();
options.setExpirySeconds(jwtExpireAfter);
options.setIssuedAt(true);
options.setJwtId(true);
final Cookie bearerCookie = jwtCookieGenerator.generate("Bearer " + new JWTSigner(jwtSecret).sign(claims, options));
((HttpServletResponse) servletResponse).addCookie(bearerCookie);
}
filterChain.doFilter(servletRequest, servletResponse);
}
use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.
the class UserServiceImpl method register.
/**
* Allows to pre-create a user and send an email notification to finalize its creation.
*/
@Override
public UserEntity register(final NewExternalUserEntity newExternalUserEntity) {
checkUserRegistrationEnabled();
newExternalUserEntity.setUsername(newExternalUserEntity.getEmail());
newExternalUserEntity.setSource("gravitee");
newExternalUserEntity.setSourceId(newExternalUserEntity.getUsername());
final UserEntity userEntity = create(newExternalUserEntity, true);
// generate a JWT to store user's information and for security purpose
final Map<String, Object> claims = new HashMap<>();
claims.put(Claims.ISSUER, environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER));
claims.put(Claims.SUBJECT, userEntity.getUsername());
claims.put(Claims.EMAIL, userEntity.getEmail());
claims.put(Claims.FIRSTNAME, userEntity.getFirstname());
claims.put(Claims.LASTNAME, userEntity.getLastname());
final JWTSigner.Options options = new JWTSigner.Options();
options.setExpirySeconds(environment.getProperty("user.creation.token.expire-after", Integer.class, DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER));
options.setIssuedAt(true);
options.setJwtId(true);
// send a confirm email with the token
final String jwtSecret = environment.getProperty("jwt.secret");
if (jwtSecret == null || jwtSecret.isEmpty()) {
throw new IllegalStateException("JWT secret is mandatory");
}
final String token = new JWTSigner(jwtSecret).sign(claims, options);
String portalUrl = environment.getProperty("portalURL");
if (portalUrl.endsWith("/")) {
portalUrl = portalUrl.substring(0, portalUrl.length() - 1);
}
String registrationUrl = portalUrl + "/#!/registration/confirm/" + token;
final Map<String, Object> params = new NotificationParamsBuilder().user(userEntity).token(token).registrationUrl(registrationUrl).build();
notifierService.trigger(PortalHook.USER_REGISTERED, params);
emailService.sendAsyncEmailNotification(new EmailNotificationBuilder().to(userEntity.getEmail()).subject("User registration - " + userEntity.getUsername()).template(EmailNotificationBuilder.EmailTemplate.USER_REGISTRATION).params(params).build());
return userEntity;
}
use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.
the class UserServiceImpl method create.
/**
* Allows to complete the creation of a user which is pre-created.
* @param registerUserEntity a valid token and a password
* @return the user
*/
@Override
public UserEntity create(final RegisterUserEntity registerUserEntity) {
checkUserRegistrationEnabled();
try {
final String jwtSecret = environment.getProperty("jwt.secret");
if (jwtSecret == null || jwtSecret.isEmpty()) {
throw new IllegalStateException("JWT secret is mandatory");
}
final Map<String, Object> claims = new JWTVerifier(jwtSecret).verify(registerUserEntity.getToken());
final NewUserEntity newUserEntity = new NewUserEntity();
newUserEntity.setUsername(claims.get(Claims.SUBJECT).toString());
newUserEntity.setEmail(claims.get(Claims.EMAIL).toString());
newUserEntity.setFirstname(claims.get(Claims.FIRSTNAME).toString());
newUserEntity.setLastname(claims.get(Claims.LASTNAME).toString());
newUserEntity.setPassword(registerUserEntity.getPassword());
LOGGER.debug("Create an internal user {}", newUserEntity);
Optional<User> checkUser = userRepository.findByUsername(newUserEntity.getUsername());
if (checkUser.isPresent() && StringUtils.isNotBlank(checkUser.get().getPassword())) {
throw new UsernameAlreadyExistsException(newUserEntity.getUsername());
}
User user = convert(newUserEntity);
user.setId(UUID.toString(UUID.random()));
// Encrypt password if internal user
if (user.getPassword() != null) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
}
// Set date fields
user.setUpdatedAt(new Date());
user = userRepository.update(user);
auditService.createPortalAuditLog(Collections.singletonMap(USER, user.getUsername()), User.AuditEvent.USER_CREATED, user.getUpdatedAt(), null, user);
return convert(user, true);
} catch (Exception ex) {
LOGGER.error("An error occurs while trying to create an internal user with the token {}", registerUserEntity.getToken(), ex);
throw new TechnicalManagementException(ex.getMessage(), ex);
}
}
use of com.auth0.jwt.JWT in project DragonProxy by DragonetMC.
the class LoginChainDecoder method decode.
/**
* decode the chain data in Login packet for MCPE Note: the credit of this
* function goes to Nukkit development team
*/
public void decode() {
Map<String, List<String>> map = gson.fromJson(new String(this.chainJWT, StandardCharsets.UTF_8), new TypeToken<Map<String, List<String>>>() {
}.getType());
if (map.isEmpty() || !map.containsKey("chain") || map.get("chain").isEmpty())
return;
List<DecodedJWT> chainJWTs = new ArrayList<>();
// Add the JWT tokens to a chain
for (String token : map.get("chain")) chainJWTs.add(JWT.decode(token));
DecodedJWT clientJWT = null;
if (this.clientDataJWT != null) {
clientJWT = JWT.decode(new String(this.clientDataJWT, StandardCharsets.UTF_8));
chainJWTs.add(clientJWT);
}
// first step, check if the public provided key can decode the received chain
try {
ECPublicKey prevPublicKey = null;
for (DecodedJWT jwt : chainJWTs) {
JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
String encodedPublicKey = null;
ECPublicKey publicKey = null;
if (payload.has("identityPublicKey")) {
encodedPublicKey = payload.get("identityPublicKey").getAsString();
publicKey = (ECPublicKey) EC_KEY_FACTORY.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(encodedPublicKey)));
}
// Trust the root ca public key and use it to verify the chain
if (ENCODED_ROOT_CA_KEY.equals(encodedPublicKey) && payload.has("certificateAuthority") && payload.get("certificateAuthority").getAsBoolean()) {
prevPublicKey = publicKey;
continue;
}
// This will happen if the root ca key we have does not match the one presented by the client chain
if (prevPublicKey == null)
throw new NullPointerException("No trusted public key found in chain, is the client logged in or cracked");
// Throws a SignatureVerificationException if the verification failed
Algorithm.ECDSA384(prevPublicKey, null).verify(jwt);
// Verification was successful since no exception was thrown
// Set the previous public key to this one so that it can be used
// to verify the next JWT token in the chain
prevPublicKey = publicKey;
}
// The for loop successfully verified all JWT tokens with no exceptions thrown
this.loginVerified = true;
Logger.getLogger(this.getClass().getSimpleName()).info("The LoginPacket has been successfully verified for integrity");
} catch (Exception e) {
this.loginVerified = false;
Logger.getLogger(this.getClass().getSimpleName()).info("Failed to verify the integrity of the LoginPacket");
e.printStackTrace();
}
// This is in its own for loop due to the possibility that the chain verification failed
for (DecodedJWT jwt : chainJWTs) {
JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
// Get the information we care about - The UUID and display name
if (payload.has("extraData") && !payload.has("certificateAuthority")) {
extraData = payload.get("extraData").getAsJsonObject();
if (extraData.has("displayName"))
this.username = extraData.get("displayName").getAsString();
if (extraData.has("identity"))
this.clientUniqueId = UUID.fromString(extraData.get("identity").getAsString());
break;
}
}
// debug purpose
if (log_profiles_files) {
try {
BufferedWriter writer1 = new BufferedWriter(new FileWriter("logs/" + username + ".rawChainJTW"));
writer1.write(getChainJWT());
writer1.close();
BufferedWriter writer = new BufferedWriter(new FileWriter("logs/" + username + ".rawClientDataJTW"));
writer.write(getClientDataJWT());
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// debug purpose
int index = 0;
for (DecodedJWT jwt : chainJWTs) {
JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("logs/" + username + "_" + index + ".decodedChain"));
writer.write(payload.toString());
writer.close();
index++;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// client data & skin
if (clientJWT != null) {
this.clientData = gson.fromJson(new String(Base64.getDecoder().decode(clientJWT.getPayload()), StandardCharsets.UTF_8), JsonObject.class);
// debug purpose
if (log_profiles_files) {
try {
BufferedWriter writer1 = new BufferedWriter(new FileWriter("logs/" + username + ".decodedData"));
writer1.write(this.clientData.toString());
writer1.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (this.clientData.has("ClientRandomId"))
this.clientId = this.clientData.get("ClientRandomId").getAsLong();
if (this.clientData.has("SkinData") && this.clientData.has("SkinId")) {
this.skin = new Skin(this.clientData.get("SkinData").getAsString(), this.clientData.get("SkinId").getAsString());
if (this.clientData.has("CapeData"))
this.skin.setCape(this.skin.new Cape(Base64.getDecoder().decode(this.clientData.get("CapeData").getAsString())));
} else
this.skin = Skin.DEFAULT_SKIN_STEVE;
if (this.clientData.has("SkinGeometryName"))
this.skinGeometryName = this.clientData.get("SkinGeometryName").getAsString();
if (this.clientData.has("SkinGeometry"))
this.skinGeometry = Base64.getDecoder().decode(this.clientData.get("SkinGeometry").getAsString());
}
}
Aggregations