Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Client authentication on server side via callback #163

Merged
merged 6 commits into from
Nov 4, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions OCPP-J/src/main/java/eu/chargetime/ocpp/WebSocketListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,17 @@ of this software and associated documentation files (the "Software"), to deal
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.handshake.ServerHandshakeBuilder;
import org.java_websocket.server.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -46,6 +50,9 @@ public class WebSocketListener implements Listener {

private static final int TIMEOUT_IN_MILLIS = 10000;

private static final int OCPPJ_CP_MIN_PASSWORD_LENGTH = 16;
private static final int OCPPJ_CP_MAX_PASSWORD_LENGTH = 20;

private final ISessionFactory sessionFactory;
private final List<Draft> drafts;

Expand Down Expand Up @@ -109,6 +116,50 @@ public void relay(String message) {
sessionFactory.createSession(new JSONCommunicator(receiver)), information);
}

@Override
public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket webSocket, Draft draft,
ClientHandshake clientHandshake) throws InvalidDataException {
SessionInformation information =
new SessionInformation.Builder()
.Identifier(clientHandshake.getResourceDescriptor())
.InternetAddress(webSocket.getRemoteSocketAddress())
.build();

String username = null;
byte[] password = null;
if (clientHandshake.hasFieldValue("Authorization")) {
String authorization = clientHandshake.getFieldValue("Authorization");
if (authorization != null && authorization.toLowerCase().startsWith("basic")) {
// Authorization: Basic base64credentials
String base64Credentials = authorization.substring("Basic".length()).trim();
byte[] credDecoded = Base64.getDecoder().decode(base64Credentials);
// split credentials on username and password
for (int i = 0; i < credDecoded.length; i++) {
if (credDecoded[i] == ':') {
username = new String(Arrays.copyOfRange(credDecoded, 0, i), StandardCharsets.UTF_8);
if (i != credDecoded.length - 1) {
dimaa6 marked this conversation as resolved.
Show resolved Hide resolved
password = Arrays.copyOfRange(credDecoded, i + 1, credDecoded.length);
}
break;
}
}
dimaa6 marked this conversation as resolved.
Show resolved Hide resolved
}
if (password == null || password.length < OCPPJ_CP_MIN_PASSWORD_LENGTH || password.length > OCPPJ_CP_MAX_PASSWORD_LENGTH)
throw new InvalidDataException(401, "Invalid password length");
}

try {
handler.authenticateSession(information, username, password);
}
catch (AuthenticationException e) {
throw new InvalidDataException(e.getErrorCode(), e.getMessage());
}
catch (Exception e) {
throw new InvalidDataException(401, e.getMessage());
}
return super.onWebsocketHandshakeReceivedAsServer(webSocket, draft, clientHandshake);
}

@Override
public void onClose(WebSocket webSocket, int code, String reason, boolean remote) {
logger.debug(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package eu.chargetime.ocpp;

import java.io.Serializable;

public class AuthenticationException extends Exception implements Serializable {
private static final long serialVersionUID = -2323276402779073385L;
private final int errorcode;

public AuthenticationException(int errorcode) {
this.errorcode = errorcode;
}

public AuthenticationException(int errorcode, String s) {
super(s);
this.errorcode = errorcode;
}

public AuthenticationException(int errorcode, Throwable t) {
super(t);
this.errorcode = errorcode;
}

public AuthenticationException(int errorcode, String s, Throwable t) {
super(s, t);
this.errorcode = errorcode;
}

public int getErrorCode() {
return this.errorcode;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,6 @@ of this software and associated documentation files (the "Software"), to deal
import eu.chargetime.ocpp.model.SessionInformation;

public interface ListenerEvents {
void authenticateSession(SessionInformation information, String username, byte[] password) throws AuthenticationException;
void newSession(ISession session, SessionInformation information);
}
159 changes: 85 additions & 74 deletions ocpp-common/src/main/java/eu/chargetime/ocpp/Server.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ of this software and associated documentation files (the "Software"), to deal
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

import eu.chargetime.ocpp.model.SessionInformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -78,80 +80,89 @@ public void open(String hostname, int port, ServerEvents serverEvents) {
listener.open(
hostname,
port,
(session, information) -> {
session.accept(
new SessionEvents() {
@Override
public void handleConfirmation(String uniqueId, Confirmation confirmation) {

Optional<CompletableFuture<Confirmation>> promiseOptional =
promiseRepository.getPromise(uniqueId);
if (promiseOptional.isPresent()) {
promiseOptional.get().complete(confirmation);
promiseRepository.removePromise(uniqueId);
} else {
logger.debug("Promise not found for confirmation {}", confirmation);
}
}

@Override
public Confirmation handleRequest(Request request)
throws UnsupportedFeatureException {
Optional<Feature> featureOptional = featureRepository.findFeature(request);
if (featureOptional.isPresent()) {
Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
return featureOptional.get().handleRequest(sessionIdOptional.get(), request);
} else {
logger.error(
"Unable to handle request ({}), the active session was not found.",
request);
throw new IllegalStateException("Active session not found");
}
} else {
throw new UnsupportedFeatureException();
}
}

@Override
public void handleError(
String uniqueId, String errorCode, String errorDescription, Object payload) {
Optional<CompletableFuture<Confirmation>> promiseOptional =
promiseRepository.getPromise(uniqueId);
if (promiseOptional.isPresent()) {
promiseOptional
.get()
.completeExceptionally(
new CallErrorException(errorCode, errorDescription, payload));
promiseRepository.removePromise(uniqueId);
} else {
logger.debug("Promise not found for error {}", errorDescription);
}
}

@Override
public void handleConnectionClosed() {
Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
serverEvents.lostSession(sessionIdOptional.get());
sessions.remove(sessionIdOptional.get());
} else {
logger.warn("Active session not found");
}
}

@Override
public void handleConnectionOpened() {}
});

sessions.put(session.getSessionId(), session);

Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
serverEvents.newSession(sessionIdOptional.get(), information);
logger.debug("Session created: {}", session.getSessionId());
} else {
throw new IllegalStateException("Failed to create a session");
new ListenerEvents() {

@Override
public void authenticateSession(SessionInformation information, String username, byte[] password) throws AuthenticationException {
serverEvents.authenticateSession(information, username, password);
}

@Override
public void newSession(ISession session, SessionInformation information) {
session.accept(
new SessionEvents() {
@Override
public void handleConfirmation(String uniqueId, Confirmation confirmation) {

Optional<CompletableFuture<Confirmation>> promiseOptional =
promiseRepository.getPromise(uniqueId);
if (promiseOptional.isPresent()) {
promiseOptional.get().complete(confirmation);
promiseRepository.removePromise(uniqueId);
} else {
logger.debug("Promise not found for confirmation {}", confirmation);
}
}

@Override
public Confirmation handleRequest(Request request)
throws UnsupportedFeatureException {
Optional<Feature> featureOptional = featureRepository.findFeature(request);
if (featureOptional.isPresent()) {
Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
return featureOptional.get().handleRequest(sessionIdOptional.get(), request);
} else {
logger.error(
"Unable to handle request ({}), the active session was not found.",
request);
throw new IllegalStateException("Active session not found");
}
} else {
throw new UnsupportedFeatureException();
}
}

@Override
public void handleError(
String uniqueId, String errorCode, String errorDescription, Object payload) {
Optional<CompletableFuture<Confirmation>> promiseOptional =
promiseRepository.getPromise(uniqueId);
if (promiseOptional.isPresent()) {
promiseOptional
.get()
.completeExceptionally(
new CallErrorException(errorCode, errorDescription, payload));
promiseRepository.removePromise(uniqueId);
} else {
logger.debug("Promise not found for error {}", errorDescription);
}
}

@Override
public void handleConnectionClosed() {
Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
serverEvents.lostSession(sessionIdOptional.get());
sessions.remove(sessionIdOptional.get());
} else {
logger.warn("Active session not found");
}
}

@Override
public void handleConnectionOpened() {}
});

sessions.put(session.getSessionId(), session);

Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
serverEvents.newSession(sessionIdOptional.get(), information);
logger.debug("Session created: {}", session.getSessionId());
} else {
throw new IllegalStateException("Failed to create a session");
}
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ of this software and associated documentation files (the "Software"), to deal
import java.util.UUID;

public interface ServerEvents {
default void authenticateSession(SessionInformation information, String username, byte[] password) throws AuthenticationException {}

void newSession(UUID sessionIndex, SessionInformation information);

void lostSession(UUID sessionIndex);
Expand Down