index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/entityauth/UnauthenticatedEntityAuthenticationHandle.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.common.entityauth; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.EntityAuthenticationFactory; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.entityauth.UnauthenticatedAuthenticationData; import com.netflix.msl.entityauth.UnauthenticatedAuthenticationFactory; import com.netflix.msl.util.AuthenticationUtils; import mslcli.common.CmdArguments; import mslcli.common.IllegalCmdArgumentException; import mslcli.common.util.AppContext; import mslcli.common.util.ConfigurationException; /** * <p> * Plugin implementation for generating unauthenticated entity authentication data and factory * </p> * * @author Vadim Spector <[email protected]> */ public class UnauthenticatedEntityAuthenticationHandle extends EntityAuthenticationHandle { /** * ctor */ public UnauthenticatedEntityAuthenticationHandle() { super(EntityAuthenticationScheme.NONE); } @Override public EntityAuthenticationData getEntityAuthenticationData(final AppContext appCtx, final CmdArguments args) throws IllegalCmdArgumentException { return new UnauthenticatedAuthenticationData(args.getEntityId()); } @Override public EntityAuthenticationFactory getEntityAuthenticationFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils) throws ConfigurationException, IllegalCmdArgumentException { return new UnauthenticatedAuthenticationFactory(authutils); } }
2,000
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/entityauth/SimpleRsaStore.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.common.entityauth; import java.security.KeyPair; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Map; import java.util.Set; import com.netflix.msl.entityauth.RsaStore; import mslcli.common.util.SharedUtil; /** * <p> * Memory-backed RSA key store, mapping IDs to RSA key pairs. * Note, that ID is the identity of RSA key pair, not of the * entity using it. Each entity needs to know the ID of the RSA * key pair it should use. * </p> * * @author Vadim Spector <[email protected]> */ public class SimpleRsaStore implements RsaStore { /** * <p>Create a new RSA store that will return the provided public and/or * private keys for the specified server RSA key pair ID. * * Multiple server instances may be configured to use the same RSA key pair id. * * A public key must be provided to authenticate remote entities. A private key * must be provided to authenticate local entities.</p> * * @param keys RSA key pairs keyed by server entity id */ public SimpleRsaStore(final Map<String,KeyPair> keys) { if (keys == null) { throw new IllegalArgumentException("NULL RSA key map"); } this.keys = keys; } /** * @see com.netflix.msl.entityauth.RsaStore#getIdentities() */ @Override public Set<String> getIdentities() { return keys.keySet(); } /** * @see com.netflix.msl.entityauth.RsaStore#getPublicKey(String) */ @Override public PublicKey getPublicKey(final String identity) { final KeyPair pair = keys.get(identity); return (pair != null) ? pair.getPublic() : null; } /** * @see com.netflix.msl.entityauth.RsaStore#getPrivateKey(String) */ @Override public PrivateKey getPrivateKey(final String identity) { final KeyPair pair = keys.get(identity); return (pair != null) ? pair.getPrivate() : null; } @Override public String toString() { return SharedUtil.toString(this); } /** map of RSA key pair IDs into key pairs */ private final Map<String,KeyPair> keys; }
2,001
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/entityauth/UnauthenticatedSuffixedEntityAuthenticationHandle.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.common.entityauth; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.EntityAuthenticationFactory; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.entityauth.UnauthenticatedSuffixedAuthenticationData; import com.netflix.msl.entityauth.UnauthenticatedSuffixedAuthenticationFactory; import com.netflix.msl.util.AuthenticationUtils; import mslcli.common.CmdArguments; import mslcli.common.IllegalCmdArgumentException; import mslcli.common.util.AppContext; import mslcli.common.util.ConfigurationException; /** * <p> * Plugin implementation for generating unauthenticated suffixed entity authentication data and authentication factory * </p> * * @author Vadim Spector <[email protected]> */ public class UnauthenticatedSuffixedEntityAuthenticationHandle extends EntityAuthenticationHandle { /** * ctor */ public UnauthenticatedSuffixedEntityAuthenticationHandle() { super(EntityAuthenticationScheme.NONE_SUFFIXED); } @Override public EntityAuthenticationData getEntityAuthenticationData(final AppContext appCtx, final CmdArguments args) throws IllegalCmdArgumentException { return new UnauthenticatedSuffixedAuthenticationData(args.getEntityId(), "1"); } @Override public EntityAuthenticationFactory getEntityAuthenticationFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils) throws ConfigurationException, IllegalCmdArgumentException { return new UnauthenticatedSuffixedAuthenticationFactory(authutils); } }
2,002
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/entityauth/SimplePresharedKeyStore.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.common.entityauth; import java.util.HashMap; import java.util.Map; import com.netflix.msl.entityauth.KeySetStore; import com.netflix.msl.entityauth.KeySetStore.KeySet; import mslcli.common.util.SharedUtil; /** * <p> * Sample preshared key store backed by memory. * </p> * * @author Vadim Spector <[email protected]> */ public class SimplePresharedKeyStore implements KeySetStore { /** * <p>Create a new preshared store that will return the provided preshared * keys for the specified identity.</p> * * @param presharedKeys {identity, preshared_keys} map */ public SimplePresharedKeyStore(final Map<String,KeySet> presharedKeys) { if (presharedKeys == null) { throw new IllegalArgumentException("NULL preshared key map"); } this.presharedKeys.putAll(presharedKeys); } /** * @see com.netflix.msl.entityauth.KeySetStore#getKeys(String) */ @Override public KeySet getKeys(final String identity) { if (identity == null) { throw new IllegalArgumentException("NULL identity"); } return presharedKeys.get(identity); } @Override public String toString() { return SharedUtil.toString(this); } /** preshared keys database */ private final Map<String,KeySet> presharedKeys = new HashMap<String,KeySet>(); }
2,003
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/entityauth/EntityAuthenticationHandle.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.common.entityauth; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.EntityAuthenticationFactory; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.util.AuthenticationUtils; import mslcli.common.CmdArguments; import mslcli.common.IllegalCmdArgumentException; import mslcli.common.util.AppContext; import mslcli.common.util.ConfigurationException; import mslcli.common.util.SharedUtil; /** * <p> * Abstract class to facilitate creating plugin implementations for generating * entity authentication data and entity authentication factory. * </p> * * @author Vadim Spector <[email protected]> */ public abstract class EntityAuthenticationHandle { /** * @param scheme EntityAuthenticationScheme */ protected EntityAuthenticationHandle(final EntityAuthenticationScheme scheme) { this.scheme = scheme; } /** * @return key exchange scheme */ public final EntityAuthenticationScheme getScheme() { return scheme; } /** * @param appCtx application context * @param args command line arguments * @return entity authentication data to be included into a message * @throws ConfigurationException * @throws IllegalCmdArgumentException */ public abstract EntityAuthenticationData getEntityAuthenticationData(final AppContext appCtx, final CmdArguments args) throws ConfigurationException, IllegalCmdArgumentException; /** * @param appCtx application context * @param args command line arguments * @param authutils authentication utilities * @return entity authentication factory * @throws ConfigurationException * @throws IllegalCmdArgumentException */ public abstract EntityAuthenticationFactory getEntityAuthenticationFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils) throws ConfigurationException, IllegalCmdArgumentException; @Override public final String toString() { return SharedUtil.toString(this, scheme); } /** entity authentication scheme */ private final EntityAuthenticationScheme scheme; }
2,004
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/entityauth/RsaEntityAuthenticationHandle.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.common.entityauth; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.EntityAuthenticationFactory; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.entityauth.RsaAuthenticationData; import com.netflix.msl.entityauth.RsaAuthenticationFactory; import com.netflix.msl.util.AuthenticationUtils; import mslcli.common.CmdArguments; import mslcli.common.IllegalCmdArgumentException; import mslcli.common.util.AppContext; import mslcli.common.util.ConfigurationException; /** * <p> * Plugin implementation for generating RSA entity authentication data and authentication factory * </p> * * @author Vadim Spector <[email protected]> */ public class RsaEntityAuthenticationHandle extends EntityAuthenticationHandle { /** * ctor */ public RsaEntityAuthenticationHandle() { super(EntityAuthenticationScheme.RSA); } @Override public EntityAuthenticationData getEntityAuthenticationData(final AppContext appCtx, final CmdArguments args) throws ConfigurationException, IllegalCmdArgumentException { return new RsaAuthenticationData(args.getEntityId(), appCtx.getRsaKeyId(args.getEntityId())); } @Override public EntityAuthenticationFactory getEntityAuthenticationFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils) throws ConfigurationException, IllegalCmdArgumentException { return new RsaAuthenticationFactory(appCtx.getRsaStore(), authutils); } }
2,005
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/client/Client.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.client; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import mslcli.client.msg.ClientRequestMessageContext; import mslcli.client.util.ClientMslContext; import mslcli.common.CmdArguments; import mslcli.common.IllegalCmdArgumentException; import mslcli.common.util.AppContext; import mslcli.common.util.ConfigurationException; import mslcli.common.util.SharedUtil; import com.netflix.msl.MslException; import com.netflix.msl.io.JavaUrl; import com.netflix.msl.msg.ErrorHeader; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MslControl; import com.netflix.msl.msg.MslControl.MslChannel; import com.netflix.msl.util.MslContext; import com.netflix.msl.util.MslStore; /** * <p> * MSL client. Hides some complexities of MSL core APIs and send/receive error handling. * Instance of thsi class is bound to a given client entity identity via an instance of * ClientMslConfig, which, in turn, is bound to a given client entity identity. * </p> * * @author Vadim Spector <[email protected]> */ public final class Client { /** timeout in milliseconds for processing request and composing response */ private static final int TIMEOUT_MS = 120 * 1000; /** * Data object encapsulating payload and/or error header from the server */ public static final class Response { /** * @param payload message application payload of the response, if any * @param errHeader MSL error header in the response, if any */ private Response(final byte[] payload, final ErrorHeader errHeader) { this.payload = payload; this.errHeader = errHeader; } /** * @return application payload in the response, if any */ public byte[] getPayload() { return payload; } /** * @return MSL error header in the response, if any */ public ErrorHeader getErrorHeader() { return errHeader; } /** application payload */ private final byte[] payload; /** MSL error header */ private final ErrorHeader errHeader; } /** * @param appCtx application context * @param args command-line arguments (well, they may not be necessarily specified from the command line, just the same parsing scheme) * @throws ConfigurationException * @throws IllegalCmdArgumentException */ public Client(final AppContext appCtx, final CmdArguments args) throws ConfigurationException, IllegalCmdArgumentException { if (appCtx == null) { throw new IllegalArgumentException("NULL app context"); } if (args == null) { throw new IllegalArgumentException("NULL arguments"); } // Set app context. this.appCtx = appCtx; // Set args - create independent instance this.args = new CmdArguments(args); // Init MSL configuration this.mslCfg = new ClientMslConfig(appCtx, this.args); this.mslCfg.validate(); // Set up the MSL Control this.mslCtrl = appCtx.getMslControl(); // set up entity identity this.entityId = this.args.getEntityId(); } /** * modify current args with the diff * @param diffArgs additional arguments to modify the existing configuration * @return copy of the current args * @throws IllegalCmdArgumentException */ public CmdArguments modifyConfig(final CmdArguments diffArgs) throws IllegalCmdArgumentException { if (diffArgs.hasEntityId()) { throw new IllegalCmdArgumentException("Cannot Reset Entity Identity"); } args.merge(diffArgs); mslCfg.validate(); appCtx.info(String.format("%s: %s", this, args.getParameters())); return new CmdArguments(args); } /** * @return current args as a string */ public String getConfigInfo() { return args.getParameters(); } /** * @return copy of the current args * @throws IllegalCmdArgumentException */ public CmdArguments getConfig() throws IllegalCmdArgumentException { return new CmdArguments(args); } /** * Send single request. * @param request message payload to send * @return response encapsulating payload and/or error header * @throws ConfigurationException * @throws ExecutionException * @throws IllegalCmdArgumentException * @throws IOException * @throws InterruptedException * @throws MslException */ public Response sendRequest(final byte[] request) throws ConfigurationException, ExecutionException, IllegalCmdArgumentException, IOException, InterruptedException, MslException { // validate MslConfig mslCfg.validate(); // set remote URL final JavaUrl remoteUrl = new JavaUrl(args.getUrl()); final MslContext mslCtx = new ClientMslContext(appCtx, mslCfg); final MessageContext msgCtx = new ClientRequestMessageContext(mslCfg, request); final Future<MslChannel> f = mslCtrl.request(mslCtx, msgCtx, remoteUrl, TIMEOUT_MS); final MslChannel ch; ch = f.get(); if (ch == null) return null; final ErrorHeader errHeader = ch.input.getErrorHeader(); if (errHeader == null) { return new Response(SharedUtil.readIntoArray(ch.input), null); } else { return new Response(null, errHeader); } } /** * @return MSL Store */ public MslStore getMslStore() { return mslCfg.getMslStore(); } /** * save MSL Store * @throws IOException if cannot save MSL store */ public void saveMslStore() throws IOException { mslCfg.saveMslStore(); } /** * @return entity identity */ public String getEntityId() { return entityId; } @Override public String toString() { return SharedUtil.toString(this, entityId); } /** App context */ private final AppContext appCtx; /** Args */ private final CmdArguments args; /** MSL config */ private final ClientMslConfig mslCfg; /** MSL control */ private final MslControl mslCtrl; /** Entity identity */ private final String entityId; }
2,006
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/client/ClientApp.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.client; import java.io.IOException; import java.io.InputStream; import java.net.ConnectException; import java.security.Security; import java.util.concurrent.ExecutionException; import mslcli.common.CmdArguments; import mslcli.common.IllegalCmdArgumentException; import mslcli.common.IllegalCmdArgumentRuntimeException; import mslcli.common.Triplet; import mslcli.common.util.AppContext; import mslcli.common.util.ConfigurationException; import mslcli.common.util.ConfigurationRuntimeException; import mslcli.common.util.MslProperties; import mslcli.common.util.SharedUtil; import org.bouncycastle.jce.provider.BouncyCastleProvider; import com.netflix.msl.MslConstants; import com.netflix.msl.MslException; import com.netflix.msl.msg.ConsoleFilterStreamFactory; /** * <p> * MSL client launcher program. Allows sending a single or multiple MSL messages to one or more MLS * servers, using different message MSL security configuration options. * </p> * * @author Vadim Spector <[email protected]> */ public final class ClientApp { // Add BouncyCastle provider. static { Security.addProvider(new BouncyCastleProvider()); } /** interactive prompt for setting/changing runtime arguments */ private static final String CMD_PROMPT = "args"; /** MSL CLI client manual file name */ private static final String HELP_FILE = "mslclient_manual.txt"; /** interactive command to print help */ private static final String CMD_HELP = "help"; /** interactive command to list current runtime arguments */ private static final String CMD_LIST = "list"; /** interactive command to save MSL store */ private static final String CMD_SAVE = "save"; /** interactive command to exit MSL CLI client program */ private static final String CMD_QUIT = "quit"; /** interactive command to print the list of interactive commands */ private static final String CMD_HINT = "?"; /** * enumeration of status codes returned by MSL CLI program */ public enum Status { /** success status */ OK(0, "Success"), /** invalid command line arguments */ ARG_ERROR (1, "Invalid Arguments"), /** invalid configuration file */ CFG_ERROR (2, "Configuration File Error"), /** exception from the MSL stack */ MSL_EXC_ERROR(3, "MSL Exception"), /** MSL protocol error from the server */ MSL_ERROR (4, "Server MSL Error Reply"), /** problem connecting/talking to the server */ COMM_ERROR (5, "Server Communication Error"), /** internal exception */ EXE_ERROR (6, "Internal Execution Error"); /** exit status code */ private final int code; /** exit status code explanation */ private final String info; /** * @param code status code * @param info status code explanation */ Status(final int code, final String info) { this.code = code; this.info = info; } @Override public String toString() { return String.format("%d: %s", code, info); } } /** runtime arguments */ private final CmdArguments cmdParam; /** application context */ private final AppContext appCtx; /** client bound to the given entity identity */ private Client client; /** console filter stream factory for logging */ private final ConsoleFilterStreamFactory consoleFilterStreamFactory; /** * Launcher of MSL CLI client. See user manual in HELP_FILE. * @param args command line arguments */ public static void main(final String[] args) { Status status = Status.OK; try { if (args.length == 0) { err("Use " + CMD_HELP + " for help"); status = Status.ARG_ERROR; } else if (CMD_HELP.equalsIgnoreCase(args[0])) { help(); status = Status.OK; } else { final CmdArguments cmdParam = new CmdArguments(args); final ClientApp clientApp = new ClientApp(cmdParam); if (cmdParam.isInteractive()) { clientApp.sendInteractive(); status = Status.OK; } else { status = clientApp.sendRequest(null); } clientApp.shutdown(); } } catch (final ConfigurationException e) { err(e.getMessage()); status = Status.CFG_ERROR; } catch (final IllegalCmdArgumentException e) { err(e.getMessage()); status = Status.ARG_ERROR; } catch (final IOException e) { err(e.getMessage()); status = Status.EXE_ERROR; SharedUtil.getRootCause(e).printStackTrace(System.err); } catch (final RuntimeException e) { err(e.getMessage()); status = Status.EXE_ERROR; SharedUtil.getRootCause(e).printStackTrace(System.err); } out("Exit Status " + status); System.exit(status.code); } /** * ClientApp holds the instance of one Client and some other objects which are global for the application. * Instance of Client is supposed to be re-instantiated only when its entity identity changes, * which is only applicable in the interactive mode. Changing entity identity within a given Client * instance would be too convoluted; it makes sense to permanently bind Client with its entity ID. * * @param cmdParam encapsulation of command-line arguments * @throws ConfigurationException if some configuration parameters required for initialization are missing, invalid, or mutually inconsistent * @throws IllegalCmdArgumentException if some command line arguments required for initialization are missing, invalid, or mutually inconsistent * @throws IOException if configuration file reading failed */ public ClientApp(final CmdArguments cmdParam) throws ConfigurationException, IllegalCmdArgumentException, IOException { if (cmdParam == null) { throw new IllegalArgumentException("NULL Arguments"); } // save command-line arguments this.cmdParam = cmdParam; // load configuration from the configuration file final MslProperties mslProp = MslProperties.getInstance(SharedUtil.loadPropertiesFromFile(cmdParam.getConfigFilePath())); // load PSK if specified final String pskFile = cmdParam.getPskFile(); if (pskFile != null) { final Triplet<String,String,String> pskEntry; try { pskEntry = SharedUtil.readPskFile(pskFile); } catch (final IOException e) { throw new ConfigurationException(e.getMessage()); } cmdParam.merge(new CmdArguments(new String[] { CmdArguments.P_EID, pskEntry.x })); mslProp.addPresharedKeys(pskEntry); } // load MGK if specified final String mgkFile = cmdParam.getMgkFile(); if (mgkFile != null) { final Triplet<String,String,String> mgkEntry; try { mgkEntry = SharedUtil.readPskFile(mgkFile); } catch (final IOException e) { throw new ConfigurationException(e.getMessage()); } cmdParam.merge(new CmdArguments(new String[] { CmdArguments.P_EID, mgkEntry.x })); mslProp.addMgkKeys(mgkEntry); } // initialize application context this.appCtx = AppContext.getInstance(mslProp); // initialize console steram factory for logging this.consoleFilterStreamFactory = new ConsoleFilterStreamFactory(); } /** * In a loop as a user to modify command-line arguments and then send a single request, * until a user enters "quit" command. * * @throws IllegalCmdArgumentException invalid / inconsistent command line arguments * @throws IOException in case of user input reading error */ public void sendInteractive() throws IllegalCmdArgumentException, IOException { while (true) { final String options = SharedUtil.readInput(CMD_PROMPT); if (optMatch(CMD_QUIT, options)) { return; } if (optMatch(CMD_HELP, options)) { help(); continue; } if (optMatch(CMD_LIST, options)) { if (client != null) { out(client.getConfigInfo()); } else { err(cmdParam.getParameters()); } continue; } if (optMatch(CMD_SAVE, options)) { if (client != null) client.saveMslStore(); continue; } if (optMatch(CMD_HINT, options)) { hint(); continue; } try { // parse entered parameters just like command-line arguments final CmdArguments p; if (options != null && !options.trim().isEmpty()) { p = new CmdArguments(SharedUtil.split(options)); } else { p = null; } final Status status = sendRequest(p); if (status != Status.OK) { out("Status: " + status.toString()); } } catch (final IllegalCmdArgumentException e) { err(e.getMessage()); } catch (final RuntimeException e) { err(e.getMessage()); } } } /** * @param option option to be selected * @param val user entry * @return true if user entry is the beginning of the option string */ private static boolean optMatch(final String option, final String val) { return (option != null) && (val != null) && (val.trim().length() != 0) && option.startsWith(val.trim()); } /** * send single request * * @param args additional command-line arguments specified in interactive mode (null in non-interactive mode) * @return Status containing either reply payload or MSL error */ public Status sendRequest(final CmdArguments args) { Status status = Status.OK; try_label: try { CmdArguments currentCmdParam = (client != null) ? client.getConfig() : cmdParam; // set verbose mode if (currentCmdParam.isVerbose()) { appCtx.getMslControl().setFilterFactory(consoleFilterStreamFactory); } else { appCtx.getMslControl().setFilterFactory(null); } // (re)initialize Client for the first time or whenever entity identity changes if ((client == null) || ((args != null) && (args.getOptEntityId() != null) && !client.getEntityId().equals(args.getOptEntityId()))) { out("New Client"); // update current args if (args != null) currentCmdParam.merge(args); if (client != null) { client.saveMslStore(); client = null; // required for keeping the state, in case the next line throws exception } // create new client client = new Client(appCtx, currentCmdParam); } else if (args != null) { currentCmdParam = client.modifyConfig(args); } // set request payload byte[] requestPayload = null; final String inputFile = currentCmdParam.getPayloadInputFile(); requestPayload = currentCmdParam.getPayloadMessage(); if (inputFile != null && requestPayload != null) { appCtx.error("Input File and Input Message cannot be both specified"); status = Status.ARG_ERROR; break try_label; } if (inputFile != null) { requestPayload = SharedUtil.readFromFile(inputFile); } else { if (requestPayload == null) { requestPayload = new byte[0]; } } /* See if the output file for response payload is specified. * If it is, it must either exist or be creatable. */ final String outputFile = currentCmdParam.getPayloadOutputFile(); /* ******************************************** * FINALLY: SEND REQUEST AND PROCESS RESPONSE * **********************************************/ final int nsend = client.getConfig().getNumSends(); int count; final long t_start = System.currentTimeMillis(); for (count = 0; count < nsend; count++) { final Client.Response response = client.sendRequest(requestPayload); // Non-NULL response payload - good if (response.getPayload() != null) { if (count == 0) { if (outputFile != null) { SharedUtil.saveToFile(outputFile, response.getPayload(), false /*overwrite*/); } else { out("Response: " + new String(response.getPayload(), MslConstants.DEFAULT_CHARSET)); } } status = Status.OK; // NULL payload, must be MSL error response } else if (response.getErrorHeader() != null) { if (response.getErrorHeader().getErrorMessage() != null) { err(String.format("MSL RESPONSE ERROR: error_code %d, error_msg \"%s\"", response.getErrorHeader().getErrorCode().intValue(), response.getErrorHeader().getErrorMessage())); } else { err(String.format("ERROR: %s" + response.getErrorHeader())); } status = Status.MSL_ERROR; // NULL payload, NULL error header - should never happen } else { out("Response with no payload or error header ???"); status = Status.MSL_ERROR; } } final long t_total = System.currentTimeMillis() - t_start; if (count != 0) { out(String.format("Messages Sent: %d, Total Time: %d msec, Per Message: %d msec", count, t_total, t_total/count)); } } catch (final MslException e) { err(SharedUtil.getMslExceptionInfo(e)); status = Status.MSL_EXC_ERROR; SharedUtil.getRootCause(e).printStackTrace(System.err); } catch (final ConfigurationException e) { err("Error: " + e.getMessage()); status = Status.CFG_ERROR; } catch (final ConfigurationRuntimeException e) { err("Error: " + e.getCause().getMessage()); status = Status.CFG_ERROR; } catch (final IllegalCmdArgumentException e) { err("Error: " + e.getMessage()); status = Status.ARG_ERROR; } catch (final IllegalCmdArgumentRuntimeException e) { err("Error: " + e.getCause().getMessage()); status = Status.ARG_ERROR; } catch (final ConnectException e) { err("Error: " + e.getMessage()); status = Status.COMM_ERROR; } catch (final ExecutionException e) { final Throwable thr = SharedUtil.getRootCause(e); if (thr instanceof ConfigurationException) { err("Error: " + thr.getMessage()); status = Status.CFG_ERROR; } else if (thr instanceof IllegalCmdArgumentException) { err("Error: " + thr.getMessage()); status = Status.ARG_ERROR; } else if (thr instanceof MslException) { err(SharedUtil.getMslExceptionInfo((MslException)thr)); status = Status.MSL_EXC_ERROR; SharedUtil.getRootCause(e).printStackTrace(System.err); } else if (thr instanceof ConnectException) { err("Error: " + thr.getMessage()); status = Status.COMM_ERROR; } else { err("Error: " + thr.getMessage()); thr.printStackTrace(System.err); status = Status.EXE_ERROR; } } catch (final IOException e) { err("Error: " + e.getMessage()); SharedUtil.getRootCause(e).printStackTrace(System.err); status = Status.EXE_ERROR; } catch (final InterruptedException e) { err("Error: " + e.getMessage()); SharedUtil.getRootCause(e).printStackTrace(System.err); status = Status.EXE_ERROR; } catch (final RuntimeException e) { err("Error: " + e.getMessage()); SharedUtil.getRootCause(e).printStackTrace(System.err); status = Status.EXE_ERROR; } return status; } /** * shutdown activities * @throws IOException if cannot save MSL store */ public void shutdown() throws IOException { if (client != null) client.saveMslStore(); } /** * helper - print help file */ private static void help() { InputStream input = null; try { input = ClientApp.class.getResourceAsStream(HELP_FILE); final String helpInfo = new String(SharedUtil.readIntoArray(input), MslConstants.DEFAULT_CHARSET); out(helpInfo); } catch (final Exception e) { err(String.format("Cannot read help file %s: %s", HELP_FILE, e.getMessage())); } finally { if (input != null) try { input.close(); } catch (final Exception ignore) {} } } /** * helper - interactive mode hint */ private static void hint() { out("Choices:"); out("a) Modify Command-line arguments, if any need to be modified, and press Enter to send a message."); out(" Use exactly the same syntax as from the command line."); out(String.format("b) Type \"%s\" for listing currently selected command-line arguments.", CMD_LIST)); out(String.format("c) Type \"%s\" for the detailed instructions on using this tool.", CMD_HELP)); out(String.format("d) Type \"%s\" to save MSL store to the disk. MSL store is saved automatically on exit.", CMD_SAVE)); out(String.format("e) Type \"%s\" to quit this tool.", CMD_QUIT)); } /** * @param msg message to log */ private static void out(final String msg) { System.out.println(msg); } /** * @param msg message to log */ private static void err(final String msg) { System.err.println(msg); } }
2,007
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/client/ClientMslConfig.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.client; import mslcli.client.util.ClientAuthenticationUtils; import mslcli.common.CmdArguments; import mslcli.common.IllegalCmdArgumentException; import mslcli.common.MslConfig; import mslcli.common.util.AppContext; import mslcli.common.util.ConfigurationException; /** * <p> * The configuration class for specific MSl client entity ID. * Each time the app changes client entity ID, new instance * needs to be created. * </p> * * @author Vadim Spector <[email protected]> */ public final class ClientMslConfig extends MslConfig { /** * Constructor. * * @param appCtx application context * @param args command line arguments * @throws ConfigurationException * @throws IllegalCmdArgumentException */ public ClientMslConfig(final AppContext appCtx, final CmdArguments args) throws ConfigurationException, IllegalCmdArgumentException { super(appCtx, args, new ClientAuthenticationUtils(args.getEntityId(), appCtx)); } }
2,008
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/client
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/client/util/ClientMslContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.client.util; import com.netflix.msl.MslCryptoException; import com.netflix.msl.crypto.ClientMslCryptoContext; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.tokens.ClientTokenFactory; import com.netflix.msl.tokens.TokenFactory; import mslcli.client.ClientMslConfig; import mslcli.common.IllegalCmdArgumentException; import mslcli.common.util.AppContext; import mslcli.common.util.CommonMslContext; import mslcli.common.util.ConfigurationException; /** * <p> * Sample client MSL context for clients talking to trusted network servers. * It represents configurations specific to a given client entity ID. * </p> * * @author Vadim Spector <[email protected]> */ public final class ClientMslContext extends CommonMslContext { /** * <p>Create a new MSL context.</p> * * @param appCtx application context * @param mslCfg encapsulation of MSL configuration parameters * @throws ConfigurationException if some configuration parameters required for initialization are missing, invalid, or mutually inconsistent * @throws IllegalCmdArgumentException if some command line arguments required for initialization are missing, invalid, or mutually inconsistent */ public ClientMslContext(final AppContext appCtx, final ClientMslConfig mslCfg) throws ConfigurationException, IllegalCmdArgumentException { super(appCtx, mslCfg); /* MSL crypto context. Since MSL client does not encrypt/decrypt master tokens, * ClientMslCryptoContext is used. It has all dummy methods. This class * is defined in MSL core. */ this.mslCryptoContext = new ClientMslCryptoContext(); // key token factory this.tokenFactory = new ClientTokenFactory(); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getMslCryptoContext() */ @Override public ICryptoContext getMslCryptoContext() throws MslCryptoException { return mslCryptoContext; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getTokenFactory() */ @Override public TokenFactory getTokenFactory() { return tokenFactory; } /** MSL crypt context */ private final ICryptoContext mslCryptoContext; /** client token factory */ private final TokenFactory tokenFactory; }
2,009
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/client
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/client/util/ClientAuthenticationUtils.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.client.util; import mslcli.common.util.AppContext; import mslcli.common.util.CommonAuthenticationUtils; import mslcli.common.util.ConfigurationException; /** * <p> * Utility telling which entity authentication, user authentication, * and key exchange schemes are permitted/supported for a given entity. * So far, the base class functionality is sufficient. * </p> * * @author Vadim Spector <[email protected]> */ public class ClientAuthenticationUtils extends CommonAuthenticationUtils { /** * <p>Create a new authentication utils instance for the specified client identity.</p> * * @param clientId local client entity identity. * @param appCtx application context * @throws ConfigurationException */ public ClientAuthenticationUtils(final String clientId, final AppContext appCtx) throws ConfigurationException { super(clientId, appCtx); } }
2,010
0
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/client
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/client/msg/ClientRequestMessageContext.java
/** * Copyright (c) 2014-2018 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.client.msg; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.MslMessageException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.keyx.KeyRequestData; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MessageDebugContext; import com.netflix.msl.msg.MessageOutputStream; import com.netflix.msl.msg.MessageServiceTokenBuilder; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.userauth.UserAuthenticationData; import mslcli.common.IllegalCmdArgumentException; import mslcli.common.MslConfig; import mslcli.common.msg.MessageConfig; import mslcli.common.util.ConfigurationException; import mslcli.common.util.SharedUtil; /** * <p>Client Request message context.</p> * * @author Vadim Spector <[email protected]> */ public class ClientRequestMessageContext implements MessageContext { /** whether message should be encrypted */ private final boolean isEncrypted; /** whether message should be integrity protected */ private final boolean isIntegrityProtected; /** whether message should be non-replayable */ private final boolean isNonReplayable; /** message payload */ private final byte[] payload; /** map of crypto contexts */ private final Map<String,ICryptoContext> cryptoContexts; /** User ID. */ private final String userId; /** User authentication data. */ private final UserAuthenticationData userAuthData; /** Key request data. */ private final Set<KeyRequestData> keyRequestData; /** * Constructor * * @param mslCfg MSL configuration * @param payload message payload * @throws IllegalCmdArgumentException * @throws ConfigurationException * @throws MslKeyExchangeException */ public ClientRequestMessageContext(final MslConfig mslCfg, final byte[] payload) throws MslKeyExchangeException, ConfigurationException, IllegalCmdArgumentException { if (mslCfg == null) { throw new IllegalArgumentException("NULL MSL config"); } final MessageConfig msgCfg = mslCfg.getMessageConfig(); this.isEncrypted = msgCfg.isEncrypted; this.isIntegrityProtected = msgCfg.isIntegrityProtected; this.isNonReplayable = msgCfg.isNonReplayable; this.payload = payload; this.cryptoContexts = Collections.<String,ICryptoContext>emptyMap(); this.userId = mslCfg.getUserId(); this.userAuthData = mslCfg.getUserAuthenticationData(); final Set<KeyRequestData> krd = new HashSet<KeyRequestData>(); krd.add(mslCfg.getKeyRequestData()); this.keyRequestData = Collections.unmodifiableSet(krd); } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#getCryptoContext() */ @Override public Map<String,ICryptoContext> getCryptoContexts() { return cryptoContexts; } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#getRemoteEntityIdentity() */ @Override public String getRemoteEntityIdentity() { return null; } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#isEncrypted() */ @Override public boolean isEncrypted() { return isEncrypted; } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#isIntegrityProtected() */ @Override public boolean isIntegrityProtected() { return isIntegrityProtected; } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#isNonReplayable() */ @Override public boolean isNonReplayable() { return isNonReplayable; } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#isRequestingTokens() */ @Override public boolean isRequestingTokens() { return false; } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#getUserId() */ @Override public String getUserId() { return userId; } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#getUserAuthData() */ @Override public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required) { if ((reauthCode == null) && required) { return userAuthData; } else { return null; } } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#getUser() */ @Override public MslUser getUser() { return null; } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#getKeyRequestData() */ @Override public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException { return keyRequestData; } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#updateServiceTokens() */ @Override public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) throws MslMessageException, MslCryptoException, MslEncodingException, MslException { // do nothing on client side } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#write(com.netflix.msl.msg.MessageOutputStream) */ @Override public void write(final MessageOutputStream output) throws IOException { if (payload != null) { output.write(payload); output.flush(); output.close(); } } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#getDebugContext() */ @Override public MessageDebugContext getDebugContext() { return null; } @Override public String toString() { return SharedUtil.toString(this); } }
2,011
0
Create_ds/msl/examples/burp/src/main/java
Create_ds/msl/examples/burp/src/main/java/burp/IHttpListener.java
package burp; /* * @(#)IHttpListener.java * * Copyright PortSwigger Ltd. All rights reserved. * * This code may be used to extend the functionality of Burp Suite Free Edition * and Burp Suite Professional, provided that this usage does not violate the * license terms for those products. */ import burp.msl.WiretapException; /** * Extensions can implement this interface and then call * <code>IBurpExtenderCallbacks.registerHttpListener()</code> to register an * HTTP listener. The listener will be notified of requests and responses made * by any Burp tool. Extensions can perform custom analysis or modification of * these messages by registering an HTTP listener. */ public interface IHttpListener { /** * This method is invoked when an HTTP request is about to be issued, and * when an HTTP response has been received. * * @param toolFlag A flag indicating the Burp tool that issued the request. * Burp tool flags are defined in the * <code>IBurpExtenderCallbacks</code> interface. * @param messageIsRequest Flags whether the method is being invoked for a * request or response. * @param messageInfo Details of the request / response to be processed. * Extensions can call the setter methods on this object to update the * current message and so modify Burp's behavior. */ void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) throws WiretapException; }
2,012
0
Create_ds/msl/examples/burp/src/main/java
Create_ds/msl/examples/burp/src/main/java/burp/MSLHttpListener.java
/** * Copyright (c) 2014-2018 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PrintWriter; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.Set; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslError; import com.netflix.msl.MslException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationFactory; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.io.MslEncoderException; import com.netflix.msl.io.MslEncoderFactory; import com.netflix.msl.io.MslEncoderFormat; import com.netflix.msl.io.MslEncoderUtils; import com.netflix.msl.io.MslObject; import com.netflix.msl.msg.ErrorHeader; import com.netflix.msl.msg.MessageHeader; import com.netflix.msl.tokens.MasterToken; import com.netflix.msl.tokens.UserIdToken; import com.netflix.msl.userauth.UserAuthenticationFactory; import com.netflix.msl.util.Base64; import com.netflix.msl.util.MslTestUtils; import burp.msl.WiretapException; import burp.msl.WiretapModule; import burp.msl.msg.CaptureMessageDebugContext; import burp.msl.msg.WiretapMessageContext; import burp.msl.msg.WiretapMessageInputStream; import burp.msl.util.WiretapMslContext; /** * User: skommidi * Date: 9/25/14 */ public class MSLHttpListener implements IHttpListener { private static final String KEY_ENTITY_AUTHENTICATION_DATA = "entityauthdata"; private static final String KEY_MASTER_TOKEN = "mastertoken"; private static final String KEY_HEADERDATA = "headerdata"; private static final String KEY_SIGNATURE = "signature"; private static final String KEY_MESSAGE_ID = "messageid"; private static final String KEY_RENEWABLE = "renewable"; private static final String KEY_CAPABILITIES = "capabilities"; private static final String KEY_KEY_REQUEST_DATA = "keyrequestdata"; private static final String KEY_KEY_RESPONSE_DATA = "keyresponsedata"; private static final String KEY_USER_AUTHENTICATION_DATA = "userauthdata"; private static final String KEY_USER_ID_TOKEN = "useridtoken"; private static final String KEY_SERVICE_TOKENS = "servicetokens"; private static final String KEY_NON_REPLAYABLE_ID = "nonreplayableid"; private static final String KEY_HANDSHAKE = "handshake"; private static final String KEY_PAYLOAD = "payload"; private static final String KEY_ERRORDATA = "errordata"; private static final String KEY_ERROR_CODE = "errorcode"; private static final String KEY_INTERNAL_CODE = "internalcode"; private static final String KEY_ERROR_MESSAGE = "errormsg"; private static final String KEY_USER_MESSAGE = "usermsg"; private static final String KEY_DATA = "data"; private static final String KEY_TOKENDATA = "tokendata"; private static final String KEY_RENEWAL_WINDOW = "renewalwindow"; private static final String KEY_EXPIRATION = "expiration"; private static final String KEY_SEQUENCE_NUMBER = "sequencenumber"; private static final String KEY_SERIAL_NUMBER = "serialnumber"; private static final String KEY_SESSIONDATA = "sessiondata"; private static final String KEY_MASTER_TOKEN_SERIAL_NUMBER = "mtserialnumber"; private static final String KEY_USERDATA = "userdata"; public MSLHttpListener() throws MslCryptoException { this(null, null); } public MSLHttpListener(final IBurpExtenderCallbacks callbacks, final IExtensionHelpers helpers) { this.callbacks = callbacks; this.helpers = helpers; // obtain our output streams if(this.callbacks != null && this.helpers != null) { stdout = new PrintWriter(callbacks.getStdout(), true); } else { stdout = new PrintWriter(System.out); } try { initializeMsl(); } catch (final MslCryptoException e) { throw new RuntimeException(e.getMessage(), e); } } private void initializeMsl() throws MslCryptoException { final WiretapModule module = new WiretapModule(); final Set<EntityAuthenticationFactory> entityAuthFactories = module.provideEntityAuthFactories(); final Set<UserAuthenticationFactory> userAuthFactories = module.provideUserAuthFactories(); this.ctx = new WiretapMslContext(entityAuthFactories, userAuthFactories); // Change the entity auth data to your usecase ctx.setEntityAuthenticationData(EntityAuthenticationScheme.PSK); final CaptureMessageDebugContext dbgCtx = new CaptureMessageDebugContext(true, true); try { msgCtx = new WiretapMessageContext(dbgCtx); } catch (final MslKeyExchangeException e) { throw new RuntimeException(e.getMessage()); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage()); } catch (final InvalidAlgorithmParameterException e) { throw new RuntimeException(e.getMessage()); } } @Override public void processHttpMessage(final int toolFlag, final boolean messageIsRequest, final IHttpRequestResponse messageInfo) throws WiretapException { if(messageIsRequest) { // Get MSL Message final String body = getBody(messageIsRequest, messageInfo); if(body == null) return; stdout.println(); stdout.println("Request:"); // stdout.println(body); // stdout.println("Starting MSL Processing"); processMslMessage(body); } else { // Get MSL Message final String body = getBody(messageIsRequest, messageInfo); if(body == null) return; stdout.println(); stdout.println("Response:"); // stdout.println(body); // stdout.println("Starting MSL Processing"); processMslMessage(body); } } protected String getBody(final boolean messageIsRequest, final IHttpRequestResponse messageInfo) { String body = null; if(messageIsRequest) { final IRequestInfo requestInfo = this.helpers.analyzeRequest(messageInfo); // Ignore HTTP Get Requests. if(requestInfo.getMethod().equalsIgnoreCase("GET")) { ignoreNextResponse = true; return body; } ignoreNextResponse = false; // Extracting body part of request message, this is actual MSL message. final String request = new String(messageInfo.getRequest()); body = request.substring(requestInfo.getBodyOffset()); } else { if(ignoreNextResponse) { return body; } final IResponseInfo responseInfo = this.helpers.analyzeResponse(messageInfo.getResponse()); // Extracting body part of request message, this is actual MSL message. final String response = new String(messageInfo.getResponse()); body = response.substring(responseInfo.getBodyOffset()); } return body; } protected String getBody(final byte[] message) { String body = null; final IRequestInfo requestInfo = this.helpers.analyzeRequest(null, message); // Extracting body part of request message, this is actual MSL message. final String request = new String(message); body = request.substring(requestInfo.getBodyOffset()); return body; } protected String processMslMessage(final String body) throws WiretapException { final MslEncoderFactory encoder = ctx.getMslEncoderFactory(); final MslEncoderFormat format = encoder.getPreferredFormat(null); final StringBuilder retData = new StringBuilder(""); WiretapMessageInputStream mis; try { final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes()); mis = new WiretapMessageInputStream(this.ctx, byteArrayInputStream, this.msgCtx.getKeyRequestData(), this.msgCtx.getCryptoContexts()); } catch (final IOException e) { throw new WiretapException(e.getMessage(), e); } catch (final MslException e) { throw new WiretapException(e.getMessage(), e); } // Check if instance of ErrorHeader final ErrorHeader errorHeader = mis.getErrorHeader(); try { if (errorHeader != null) { // Create error headerdata MSL Object final MslObject errHeaderMo = encoder.createObject(); // if entity auth data is present add that to the JSON object if(errorHeader.getEntityAuthenticationData() != null) { try { errHeaderMo.put(KEY_ENTITY_AUTHENTICATION_DATA, errorHeader.getEntityAuthenticationData()); } catch (final IllegalArgumentException e) { throw new WiretapException(e.getMessage(), e); } } final MslObject errordataMo = encoder.createObject(); try { errordataMo.put(KEY_MESSAGE_ID, errorHeader.getMessageId()); errordataMo.put(KEY_ERROR_CODE, errorHeader.getErrorCode().intValue()); errordataMo.put(KEY_INTERNAL_CODE, errorHeader.getInternalCode()); errordataMo.put(KEY_ERROR_MESSAGE, errorHeader.getErrorMessage()); errordataMo.put(KEY_USER_MESSAGE, errorHeader.getUserMessage()); // Add headerdata in clear errHeaderMo.put(KEY_ERRORDATA, errordataMo); stdout.println(errHeaderMo); retData.append(errHeaderMo.toString() + "\n"); stdout.println(); retData.append("\n"); } catch (final IllegalArgumentException e) { throw new WiretapException(e.getMessage(), e); } return retData.toString(); } } finally { try { mis.close(); } catch (final IOException e) {} } try { final MessageHeader messageHeader = mis.getMessageHeader(); // Create message headerdata MSL object final MslObject msgHeaderMo = encoder.createObject(); // if entity auth data is present add that to the MSL object if(messageHeader.getEntityAuthenticationData() != null) { try { msgHeaderMo.put(KEY_ENTITY_AUTHENTICATION_DATA, messageHeader.getEntityAuthenticationData()); } catch (final IllegalArgumentException e) { throw new WiretapException(e.getMessage(), e); } } MasterToken masterToken = null; // if master token is present add that to the JSON object if(messageHeader.getMasterToken() != null) { masterToken = messageHeader.getMasterToken(); try { final MslObject parsedMasterTokenMo = parseMasterToken(masterToken); msgHeaderMo.put(KEY_MASTER_TOKEN, parsedMasterTokenMo); } catch (final IllegalArgumentException e) { throw new WiretapException(e.getMessage(), e); } catch (final MslException e) { throw new WiretapException(e.getMessage(), e); } } final MslObject headerdataMo = encoder.createObject(); try { headerdataMo.put(KEY_MESSAGE_ID, messageHeader.getMessageId()); headerdataMo.put(KEY_NON_REPLAYABLE_ID, messageHeader.getNonReplayableId()); headerdataMo.put(KEY_RENEWABLE, messageHeader.isRenewable()); headerdataMo.put(KEY_HANDSHAKE, messageHeader.isHandshake()); headerdataMo.put(KEY_CAPABILITIES, messageHeader.getMessageCapabilities()); if(!messageHeader.getKeyRequestData().isEmpty()) headerdataMo.put(KEY_KEY_REQUEST_DATA, MslEncoderUtils.createArray(ctx, format, messageHeader.getKeyRequestData())); if(messageHeader.getKeyResponseData() != null) { final MslObject keyResponseDataMo = MslTestUtils.toMslObject(encoder, messageHeader.getKeyResponseData()); if(messageHeader.getKeyResponseData().getMasterToken() != null) { masterToken = messageHeader.getKeyResponseData().getMasterToken(); keyResponseDataMo.remove(KEY_MASTER_TOKEN); final MslObject parsedMasterTokenMo = parseMasterToken(messageHeader.getKeyResponseData().getMasterToken()); keyResponseDataMo.put(KEY_MASTER_TOKEN, parsedMasterTokenMo); } headerdataMo.put(KEY_KEY_RESPONSE_DATA, keyResponseDataMo); } if(messageHeader.getUserAuthenticationData() != null) headerdataMo.put(KEY_USER_AUTHENTICATION_DATA, messageHeader.getUserAuthenticationData()); if(messageHeader.getUserIdToken() != null) { headerdataMo.put(KEY_USER_ID_TOKEN, parseUserIdToken(messageHeader.getUserIdToken(), masterToken)); } if(!messageHeader.getServiceTokens().isEmpty()) headerdataMo.put(KEY_SERVICE_TOKENS, MslEncoderUtils.createArray(ctx, format, messageHeader.getServiceTokens())); // Add headerdata in clear msgHeaderMo.put(KEY_HEADERDATA, headerdataMo); stdout.println(msgHeaderMo); retData.append(msgHeaderMo.toString() + "\n"); } catch (final MslEncoderException e) { throw new WiretapException(e.getMessage(), e); } catch (final MslException e) { throw new WiretapException(e.getMessage(), e); } try { MslObject payloadTokenMo; while((payloadTokenMo = mis.nextPayload()) != null) { final String data = Base64.encode(payloadTokenMo.getBytes(KEY_DATA)); payloadTokenMo.remove(KEY_DATA); payloadTokenMo.put(KEY_DATA, data); final MslObject payloadMo = encoder.createObject(); payloadMo.put(KEY_PAYLOAD, payloadTokenMo); stdout.println(payloadMo); retData.append(payloadMo.toString() + "\n"); } stdout.println(); retData.append("\n"); } catch (final Exception e) { throw new WiretapException(e.getMessage(), e); } stdout.flush(); } finally { try { mis.close(); } catch (final IOException e) {} } return retData.toString(); } private MslObject parseUserIdToken(final UserIdToken userIdToken, final MasterToken masterToken) throws MslException { final MslEncoderFactory encoder = ctx.getMslEncoderFactory(); final ICryptoContext cryptoContext = ctx.getMslCryptoContext(); byte[] tokendata; // Verify the JSON representation. boolean verified = false; try { final MslObject userIdTokenMo = MslTestUtils.toMslObject(encoder, userIdToken); tokendata = userIdTokenMo.getBytes(KEY_TOKENDATA); if (tokendata.length == 0) throw new MslEncodingException(MslError.USERIDTOKEN_TOKENDATA_MISSING, "useridtoken " + userIdTokenMo.toString()).setMasterToken(masterToken); final byte[] signature = userIdTokenMo.getBytes(KEY_SIGNATURE); verified = cryptoContext.verify(tokendata, signature, encoder); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "useridtoken " + userIdToken, e).setMasterToken(masterToken); } // Pull the token data. final MslObject tokenDataMo; byte[] userdata; long mtSerialNumber; try { tokenDataMo = encoder.parseObject(tokendata); final long renewalWindow = tokenDataMo.getLong(KEY_RENEWAL_WINDOW); final long expiration = tokenDataMo.getLong(KEY_EXPIRATION); if (expiration < renewalWindow) throw new MslException(MslError.USERIDTOKEN_EXPIRES_BEFORE_RENEWAL, "usertokendata " + tokenDataMo).setMasterToken(masterToken); mtSerialNumber = tokenDataMo.getLong(KEY_MASTER_TOKEN_SERIAL_NUMBER); if (mtSerialNumber < 0 || mtSerialNumber > MslConstants.MAX_LONG_VALUE) throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_SERIAL_NUMBER_OUT_OF_RANGE, "usertokendata " + tokenDataMo).setMasterToken(masterToken); final long serialNumber = tokenDataMo.getLong(KEY_SERIAL_NUMBER); if (serialNumber < 0 || serialNumber > MslConstants.MAX_LONG_VALUE) throw new MslException(MslError.USERIDTOKEN_SERIAL_NUMBER_OUT_OF_RANGE, "usertokendata " + tokenDataMo).setMasterToken(masterToken); final byte[] ciphertext = tokenDataMo.getBytes(KEY_USERDATA); if (ciphertext.length == 0) throw new MslException(MslError.USERIDTOKEN_USERDATA_MISSING, tokenDataMo.getString(KEY_USERDATA)).setMasterToken(masterToken); userdata = (verified) ? cryptoContext.decrypt(ciphertext, encoder) : null; tokenDataMo.remove(KEY_USERDATA); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.USERIDTOKEN_TOKENDATA_PARSE_ERROR, "usertokendata " + Base64.encode(tokendata), e).setMasterToken(masterToken); } catch (final MslCryptoException e) { e.setMasterToken(masterToken); throw e; } // Pull the user data. if (userdata != null) { try { final MslObject userDataMo = encoder.parseObject(userdata); tokenDataMo.put(KEY_USERDATA, userDataMo); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.USERIDTOKEN_USERDATA_PARSE_ERROR, "userdata " + Base64.encode(userdata), e).setMasterToken(masterToken); } } // Verify serial numbers. if (masterToken == null || mtSerialNumber != masterToken.getSerialNumber()) throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit mtserialnumber " + mtSerialNumber + "; mt " + masterToken).setMasterToken(masterToken); return tokenDataMo; } private MslObject parseMasterToken(final MasterToken masterToken) throws MslException { final ICryptoContext cryptoContext = ctx.getMslCryptoContext(); final MslEncoderFactory encoder = ctx.getMslEncoderFactory(); byte[] tokendata; // Verify the JSON representation. boolean verified = false; try { final MslObject masterTokenMo = MslTestUtils.toMslObject(encoder, masterToken); tokendata = masterTokenMo.getBytes(KEY_TOKENDATA); if (tokendata.length == 0) throw new MslEncodingException(MslError.MASTERTOKEN_TOKENDATA_MISSING, "mastertoken " + masterTokenMo.toString()); final byte[] signature = masterTokenMo.getBytes(KEY_SIGNATURE); verified = cryptoContext.verify(tokendata, signature, encoder); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "mastertoken " + masterToken, e); } // Pull the token data. final MslObject tokenDataMo; final byte[] sessiondata; try { tokenDataMo = encoder.parseObject(tokendata); final long renewalWindow = tokenDataMo.getLong(KEY_RENEWAL_WINDOW); final long expiration = tokenDataMo.getLong(KEY_EXPIRATION); if (expiration < renewalWindow) throw new MslException(MslError.MASTERTOKEN_EXPIRES_BEFORE_RENEWAL, "mastertokendata " + tokenDataMo); final long sequenceNumber = tokenDataMo.getLong(KEY_SEQUENCE_NUMBER); if (sequenceNumber < 0 || sequenceNumber > MslConstants.MAX_LONG_VALUE) throw new MslException(MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_RANGE, "mastertokendata " + tokenDataMo); final long serialNumber = tokenDataMo.getLong(KEY_SERIAL_NUMBER); if (serialNumber < 0 || serialNumber > MslConstants.MAX_LONG_VALUE) throw new MslException(MslError.MASTERTOKEN_SERIAL_NUMBER_OUT_OF_RANGE, "mastertokendata " + tokenDataMo); final byte[] ciphertext; try { ciphertext = tokenDataMo.getBytes(KEY_SESSIONDATA); } catch (final IllegalArgumentException e) { throw new MslEncodingException(MslError.MASTERTOKEN_SESSIONDATA_INVALID, tokenDataMo.getString(KEY_SESSIONDATA)); } if (ciphertext == null || ciphertext.length == 0) throw new MslEncodingException(MslError.MASTERTOKEN_SESSIONDATA_MISSING, tokenDataMo.getString(KEY_SESSIONDATA)); sessiondata = (verified) ? cryptoContext.decrypt(ciphertext, encoder) : null; tokenDataMo.remove(KEY_SESSIONDATA); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MASTERTOKEN_TOKENDATA_PARSE_ERROR, "mastertokendata " + Base64.encode(tokendata), e); } // Pull the session data. if (sessiondata != null) { try { final MslObject sessionDataMo = encoder.parseObject(sessiondata); tokenDataMo.put(KEY_SESSIONDATA, sessionDataMo); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MASTERTOKEN_SESSIONDATA_PARSE_ERROR, "sessiondata " + Base64.encode(sessiondata), e); } } return tokenDataMo; } private final PrintWriter stdout; private final IBurpExtenderCallbacks callbacks; private final IExtensionHelpers helpers; private WiretapMessageContext msgCtx; private WiretapMslContext ctx = null; private boolean ignoreNextResponse = false; }
2,013
0
Create_ds/msl/examples/burp/src/main/java
Create_ds/msl/examples/burp/src/main/java/burp/MSLTab.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp; import burp.msl.WiretapException; import java.awt.*; /** * User: skommidi * Date: 9/25/14 */ public class MSLTab implements IMessageEditorTab { public MSLTab(IMessageEditorController controller, boolean editable, IBurpExtenderCallbacks callbacks, IExtensionHelpers helpers) { this.editable = editable; this.callbacks = callbacks; this.helpers = helpers; // create an instance of Burp's text editor txtInput = callbacks.createTextEditor(); txtInput.setEditable(editable); this.mslHttpListener = new MSLHttpListener(this.callbacks, this.helpers); } @Override public String getTabCaption() { return "MSL Parse"; } @Override public Component getUiComponent() { return txtInput.getComponent(); } @Override public boolean isEnabled(byte[] content, boolean isRequest) { return true; } @Override public void setMessage(byte[] content, boolean isRequest) { if(content == null) { // clear our display txtInput.setText(null); txtInput.setEditable(false); } else { // TODO: fix setText String data = null; String body = mslHttpListener.getBody(content); try { data = mslHttpListener.processMslMessage(body); } catch (WiretapException e) { throw new RuntimeException(e.getMessage(), e); } txtInput.setText(data.getBytes()); txtInput.setEditable(editable); } // remember the displayed content currentMessage = content; } @Override public byte[] getMessage() { // determine whether the user modified the deserialized data if (txtInput.isTextModified()) { // reserialize the data // TODO: fix the reserialization part return currentMessage; } else return currentMessage; } @Override public boolean isModified() { return txtInput.isTextModified(); } @Override public byte[] getSelectedData() { return txtInput.getSelectedText(); } private final IBurpExtenderCallbacks callbacks; private final IExtensionHelpers helpers; private final boolean editable; private final MSLHttpListener mslHttpListener; private ITextEditor txtInput; private byte[] currentMessage; }
2,014
0
Create_ds/msl/examples/burp/src/main/java
Create_ds/msl/examples/burp/src/main/java/burp/MSLTabFactory.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp; /** * User: skommidi * Date: 9/25/14 */ public class MSLTabFactory implements IMessageEditorTabFactory { public MSLTabFactory(IBurpExtenderCallbacks callbacks, IExtensionHelpers helpers) { this.callbacks = callbacks; this.helpers = helpers; } @Override public IMessageEditorTab createNewInstance(IMessageEditorController controller, boolean editable) { MSLTab mslTab = new MSLTab(controller, editable, callbacks, helpers); return mslTab; } private final IBurpExtenderCallbacks callbacks; private final IExtensionHelpers helpers; }
2,015
0
Create_ds/msl/examples/burp/src/main/java
Create_ds/msl/examples/burp/src/main/java/burp/BurpExtender.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp; /** * User: skommidi * Date: 9/10/14 */ public class BurpExtender implements IBurpExtender { /** * Implement {@link IBurpExtender} * * @param callbacks */ @Override public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) { // set our extension name callbacks.setExtensionName("MSL extension"); // obtain callbacks object this.callbacks = callbacks; callbacks.issueAlert("Hello There!!!"); // obtain an extension helpers object this.helpers = callbacks.getHelpers(); // registering MSL Tab factory callbacks.registerMessageEditorTabFactory(new MSLTabFactory(this.callbacks, this.helpers)); // registering http listener callbacks.registerHttpListener(new MSLHttpListener(this.callbacks, this.helpers)); } private IExtensionHelpers helpers; private IBurpExtenderCallbacks callbacks; }
2,016
0
Create_ds/msl/examples/burp/src/main/java/burp
Create_ds/msl/examples/burp/src/main/java/burp/msl/WiretapModule.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp.msl; import java.util.HashSet; import java.util.Set; import com.netflix.msl.entityauth.EntityAuthenticationFactory; import com.netflix.msl.entityauth.MockPresharedAuthenticationFactory; import com.netflix.msl.entityauth.MockRsaAuthenticationFactory; import com.netflix.msl.entityauth.MockX509AuthenticationFactory; import com.netflix.msl.entityauth.UnauthenticatedAuthenticationFactory; import com.netflix.msl.userauth.MockEmailPasswordAuthenticationFactory; import com.netflix.msl.userauth.UserAuthenticationFactory; import com.netflix.msl.util.AuthenticationUtils; import com.netflix.msl.util.MockAuthenticationUtils; /** * User: skommidi * Date: 9/22/14 */ public class WiretapModule { public Set<EntityAuthenticationFactory> provideEntityAuthFactories() { final AuthenticationUtils authutils = new MockAuthenticationUtils(); final Set<EntityAuthenticationFactory> factories = new HashSet<EntityAuthenticationFactory>(); factories.add(new UnauthenticatedAuthenticationFactory(authutils)); factories.add(new MockPresharedAuthenticationFactory()); factories.add(new MockRsaAuthenticationFactory()); factories.add(new MockX509AuthenticationFactory()); return factories; } public Set<UserAuthenticationFactory> provideUserAuthFactories() { final Set<UserAuthenticationFactory> factories = new HashSet<UserAuthenticationFactory>(); factories.add(new MockEmailPasswordAuthenticationFactory()); return factories; } }
2,017
0
Create_ds/msl/examples/burp/src/main/java/burp
Create_ds/msl/examples/burp/src/main/java/burp/msl/WiretapException.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp.msl; /** * <p>Thrown when a wiretap exception occurs.</p> * * @author Wesley Miaw <[email protected]> */ public class WiretapException extends Exception { private static final long serialVersionUID = 664626450364720991L; /** * <p>Create a new wiretap exception with the provided message.</p> * * @param message the detail message. */ public WiretapException(final String message) { super(message); } /** * <p>Create a new wiretap exception with the provided message and * cause.</p> * * @param message the detail message. * @param cause the cause. May be {@code null}. */ public WiretapException(final String message, final Throwable cause) { super(message, cause); } }
2,018
0
Create_ds/msl/examples/burp/src/main/java/burp/msl
Create_ds/msl/examples/burp/src/main/java/burp/msl/util/WiretapMslContext.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp.msl.util; import java.security.SecureRandom; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import burp.msl.tokens.EchoingTokenFactory; import com.netflix.msl.MslCryptoException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.crypto.JcaAlgorithm; import com.netflix.msl.crypto.SymmetricCryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.EntityAuthenticationFactory; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.entityauth.MockPresharedAuthenticationFactory; import com.netflix.msl.entityauth.MockRsaAuthenticationFactory; import com.netflix.msl.entityauth.MockX509AuthenticationFactory; import com.netflix.msl.entityauth.PresharedAuthenticationData; import com.netflix.msl.entityauth.RsaAuthenticationData; import com.netflix.msl.entityauth.UnauthenticatedAuthenticationData; import com.netflix.msl.entityauth.X509AuthenticationData; import com.netflix.msl.io.DefaultMslEncoderFactory; import com.netflix.msl.io.MslEncoderFactory; import com.netflix.msl.keyx.AsymmetricWrappedExchange; import com.netflix.msl.keyx.DiffieHellmanExchange; import com.netflix.msl.keyx.KeyExchangeFactory; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.keyx.MockDiffieHellmanParameters; import com.netflix.msl.keyx.SymmetricWrappedExchange; import com.netflix.msl.msg.MessageCapabilities; import com.netflix.msl.tokens.TokenFactory; import com.netflix.msl.userauth.UserAuthenticationFactory; import com.netflix.msl.userauth.UserAuthenticationScheme; import com.netflix.msl.util.AuthenticationUtils; import com.netflix.msl.util.MockAuthenticationUtils; import com.netflix.msl.util.MslContext; import com.netflix.msl.util.MslStore; import com.netflix.msl.util.NullMslStore; /** * User: skommidi * Date: 9/22/14 */ public class WiretapMslContext extends MslContext { /** * Key exchange factory comparator. */ private static class KeyExchangeFactoryComparator implements Comparator<KeyExchangeFactory> { /** Scheme priorities. Lower values are higher priority. */ private final Map<KeyExchangeScheme,Integer> schemePriorities = new HashMap<KeyExchangeScheme,Integer>(); /** * Create a new key exchange factory comparator. */ public KeyExchangeFactoryComparator() { schemePriorities.put(KeyExchangeScheme.JWK_LADDER, 0); schemePriorities.put(KeyExchangeScheme.JWE_LADDER, 1); schemePriorities.put(KeyExchangeScheme.DIFFIE_HELLMAN, 2); schemePriorities.put(KeyExchangeScheme.SYMMETRIC_WRAPPED, 3); schemePriorities.put(KeyExchangeScheme.ASYMMETRIC_WRAPPED, 4); } /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(final KeyExchangeFactory a, final KeyExchangeFactory b) { final KeyExchangeScheme schemeA = a.getScheme(); final KeyExchangeScheme schemeB = b.getScheme(); final Integer priorityA = schemePriorities.get(schemeA); final Integer priorityB = schemePriorities.get(schemeB); return priorityA.compareTo(priorityB); } } /** * <p>Create a new wiretap MSL context.</p> * * @param entityAuthFactories entity authentication factories. * @param userAuthFactories user authentication factories. */ public WiretapMslContext(final Set<EntityAuthenticationFactory> entityAuthFactories, final Set<UserAuthenticationFactory> userAuthFactories) { final SecretKey mslEncryptionKey = new SecretKeySpec(MSL_ENCRYPTION_KEY, JcaAlgorithm.AES); final SecretKey mslHmacKey = new SecretKeySpec(MSL_HMAC_KEY, JcaAlgorithm.HMAC_SHA256); final SecretKey mslWrappingKey = new SecretKeySpec(MSL_WRAPPING_KEY, JcaAlgorithm.AESKW); this.mslCryptoContext = new SymmetricCryptoContext(this, "TestMslKeys", mslEncryptionKey, mslHmacKey, mslWrappingKey); // Entity authentication factories are mapped as-is. final Map<EntityAuthenticationScheme,EntityAuthenticationFactory> entityAuthFactoriesMap = new HashMap<EntityAuthenticationScheme,EntityAuthenticationFactory>(); for (final EntityAuthenticationFactory factory : entityAuthFactories) { entityAuthFactoriesMap.put(factory.getScheme(), factory); } this.entityAuthFactories = Collections.unmodifiableMap(entityAuthFactoriesMap); // User authentication factories are mapped as-is. final Map<UserAuthenticationScheme,UserAuthenticationFactory> userAuthFactoriesMap = new HashMap<UserAuthenticationScheme,UserAuthenticationFactory>(); for (final UserAuthenticationFactory factory : userAuthFactories) { userAuthFactoriesMap.put(factory.getScheme(), factory); } this.userAuthFactories = Collections.unmodifiableMap(userAuthFactoriesMap); final MockDiffieHellmanParameters params = MockDiffieHellmanParameters.getDefaultParameters(); final AuthenticationUtils authutils = new MockAuthenticationUtils(); final SortedSet<KeyExchangeFactory> keyExchangeFactoriesSet = new TreeSet<KeyExchangeFactory>(new KeyExchangeFactoryComparator()); keyExchangeFactoriesSet.add(new AsymmetricWrappedExchange(authutils)); keyExchangeFactoriesSet.add(new SymmetricWrappedExchange(authutils)); keyExchangeFactoriesSet.add(new DiffieHellmanExchange(params, authutils)); this.keyExchangeFactories = Collections.unmodifiableSortedSet(keyExchangeFactoriesSet); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getTime() */ @Override public long getTime() { return System.currentTimeMillis(); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getRandom() */ @Override public Random getRandom() { return random; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#isPeerToPeer() */ @Override public boolean isPeerToPeer() { return false; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getMessageCapabilities() */ @Override public MessageCapabilities getMessageCapabilities() { return capabilities; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getEntityAuthenticationData(com.netflix.msl.util.MslContext.ReauthCode) */ @Override public EntityAuthenticationData getEntityAuthenticationData(final ReauthCode reauthCode) { return entityAuthData; } public void setEntityAuthenticationData(final EntityAuthenticationScheme scheme) throws MslCryptoException { if (EntityAuthenticationScheme.PSK.equals(scheme)) entityAuthData = new PresharedAuthenticationData(MockPresharedAuthenticationFactory.PSK_ESN); else if (EntityAuthenticationScheme.X509.equals(scheme)) entityAuthData = new X509AuthenticationData(MockX509AuthenticationFactory.X509_CERT); else if (EntityAuthenticationScheme.RSA.equals(scheme)) entityAuthData = new RsaAuthenticationData(MockRsaAuthenticationFactory.RSA_ESN, MockRsaAuthenticationFactory.RSA_PUBKEY_ID); else if (EntityAuthenticationScheme.NONE.equals(scheme)) entityAuthData = new UnauthenticatedAuthenticationData("MOCKUNAUTH-ESN"); else throw new IllegalArgumentException("Unsupported authentication type: " + scheme.name()); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getMslCryptoContext() */ @Override public ICryptoContext getMslCryptoContext() { return mslCryptoContext; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getEntityAuthenticationScheme(java.lang.String) */ @Override public EntityAuthenticationScheme getEntityAuthenticationScheme(final String name) { return EntityAuthenticationScheme.getScheme(name); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getEntityAuthenticationFactory(com.netflix.msl.entityauth.EntityAuthenticationScheme) */ @Override public EntityAuthenticationFactory getEntityAuthenticationFactory(final EntityAuthenticationScheme scheme) { return entityAuthFactories.get(scheme); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getUserAuthenticationScheme(java.lang.String) */ @Override public UserAuthenticationScheme getUserAuthenticationScheme(final String name) { return UserAuthenticationScheme.getScheme(name); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getUserAuthenticationFactory(com.netflix.msl.userauth.UserAuthenticationScheme) */ @Override public UserAuthenticationFactory getUserAuthenticationFactory(final UserAuthenticationScheme scheme) { return userAuthFactories.get(scheme); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getTokenFactory() */ @Override public TokenFactory getTokenFactory() { return tokenFactory; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getKeyExchangeScheme(java.lang.String) */ @Override public KeyExchangeScheme getKeyExchangeScheme(final String name) { return KeyExchangeScheme.getScheme(name); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getKeyExchangeFactory(com.netflix.msl.keyx.KeyExchangeScheme) */ @Override public KeyExchangeFactory getKeyExchangeFactory(final KeyExchangeScheme scheme) { for (final KeyExchangeFactory factory : keyExchangeFactories) { if (factory.getScheme().equals(scheme)) return factory; } return null; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getKeyExchangeFactories() */ @Override public SortedSet<KeyExchangeFactory> getKeyExchangeFactories() { return keyExchangeFactories; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getMslStore() */ @Override public MslStore getMslStore() { return mslStore; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getMslEncoderFactory() */ @Override public MslEncoderFactory getMslEncoderFactory() { return encoderFactory; } /** MSL encryption key. */ private static final byte[] MSL_ENCRYPTION_KEY = { (byte)0x1d, (byte)0x58, (byte)0xf3, (byte)0xb8, (byte)0xf7, (byte)0x47, (byte)0xd1, (byte)0x6a, (byte)0xb1, (byte)0x93, (byte)0xc4, (byte)0xc0, (byte)0xa6, (byte)0x24, (byte)0xea, (byte)0xcf, }; /** MSL HMAC key. */ private static final byte[] MSL_HMAC_KEY = { (byte)0xd7, (byte)0xae, (byte)0xbf, (byte)0xd5, (byte)0x87, (byte)0x9b, (byte)0xb0, (byte)0xe0, (byte)0xad, (byte)0x01, (byte)0x6a, (byte)0x4c, (byte)0xf3, (byte)0xcb, (byte)0x39, (byte)0x82, (byte)0xf5, (byte)0xba, (byte)0x26, (byte)0x0d, (byte)0xa5, (byte)0x20, (byte)0x24, (byte)0x5b, (byte)0xb4, (byte)0x22, (byte)0x75, (byte)0xbd, (byte)0x79, (byte)0x47, (byte)0x37, (byte)0x0c, }; /** MSL wrapping key. */ private static final byte[] MSL_WRAPPING_KEY = { (byte)0x83, (byte)0xb6, (byte)0x9a, (byte)0x15, (byte)0x80, (byte)0xd3, (byte)0x23, (byte)0xa2, (byte)0xe7, (byte)0x9d, (byte)0xd9, (byte)0xb2, (byte)0x26, (byte)0x26, (byte)0xb3, (byte)0xf6, }; /** Secure random. */ private final Random random = new SecureRandom(); /** Message capabilities. */ private final MessageCapabilities capabilities = new MessageCapabilities(null, null, null); /** Entity authentication data. */ private EntityAuthenticationData entityAuthData = new UnauthenticatedAuthenticationData("WireTap"); /** MSL token crypto context. */ private final ICryptoContext mslCryptoContext; /** Map of supported entity authentication schemes onto factories. */ private final Map<EntityAuthenticationScheme, EntityAuthenticationFactory> entityAuthFactories; /** Map of supported user authentication schemes onto factories. */ private final Map<UserAuthenticationScheme, UserAuthenticationFactory> userAuthFactories; /** Token factory. */ private final TokenFactory tokenFactory = new EchoingTokenFactory(); /** Supported key exchange factories in preferred order. */ private final SortedSet<KeyExchangeFactory> keyExchangeFactories; /** MSL store. */ private final MslStore mslStore = new NullMslStore(); /** MSL encoder factory. */ private final MslEncoderFactory encoderFactory = new DefaultMslEncoderFactory(); }
2,019
0
Create_ds/msl/examples/burp/src/main/java/burp/msl
Create_ds/msl/examples/burp/src/main/java/burp/msl/msg/WiretapMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp.msl.msg; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.keyx.AsymmetricWrappedExchange; import com.netflix.msl.keyx.DiffieHellmanExchange; import com.netflix.msl.keyx.DiffieHellmanParameters; import com.netflix.msl.keyx.KeyRequestData; import com.netflix.msl.keyx.MockDiffieHellmanParameters; import com.netflix.msl.keyx.SymmetricWrappedExchange; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MessageDebugContext; import com.netflix.msl.msg.MessageOutputStream; import com.netflix.msl.msg.MessageServiceTokenBuilder; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.userauth.UserAuthenticationData; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * <p>This message context does not specify any security requirements and * imposes no unnecessary message properties (e.g. no user, no modifications * to service tokens).</p> * * @author Wesley Miaw <[email protected]> */ public class WiretapMessageContext implements MessageContext { private static final String DH_PARAMETERS_ID = "1"; private static final String RSA_KEYPAIR_ID = "rsaKeypairId"; /** * <p>Create a new wiretap message context with the provided message debug * context. The debug context is used to capture received MSL message * headers which can then be inspected.</p> * * @param dbgCtx the message debug context. */ public WiretapMessageContext(final MessageDebugContext dbgCtx) throws MslKeyExchangeException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { this.dbgCtx = dbgCtx; keyRequestData = new HashSet<KeyRequestData>(); { final DiffieHellmanParameters params = MockDiffieHellmanParameters.getDefaultParameters(); final DHParameterSpec paramSpec = params.getParameterSpec(MockDiffieHellmanParameters.DEFAULT_ID); final KeyPairGenerator generator = KeyPairGenerator.getInstance("DH"); generator.initialize(paramSpec); final KeyPair requestKeyPair = generator.generateKeyPair(); final BigInteger publicKey = ((DHPublicKey)requestKeyPair.getPublic()).getY(); final DHPrivateKey privateKey = (DHPrivateKey)requestKeyPair.getPrivate(); keyRequestData.add(new DiffieHellmanExchange.RequestData(DH_PARAMETERS_ID, publicKey, privateKey)); } { final KeyPairGenerator rsaGenerator = KeyPairGenerator.getInstance("RSA"); final KeyPair rsaKeyPair = rsaGenerator.generateKeyPair(); final PublicKey publicKey = rsaKeyPair.getPublic(); final PrivateKey privateKey = rsaKeyPair.getPrivate(); keyRequestData.add(new AsymmetricWrappedExchange.RequestData(RSA_KEYPAIR_ID, AsymmetricWrappedExchange.RequestData.Mechanism.RSA, publicKey, privateKey)); } { keyRequestData.add(new SymmetricWrappedExchange.RequestData(SymmetricWrappedExchange.KeyId.PSK)); } } @Override public Map<String, ICryptoContext> getCryptoContexts() { return Collections.emptyMap(); } @Override public String getRemoteEntityIdentity() { return null; } @Override public boolean isEncrypted() { return false; } @Override public boolean isIntegrityProtected() { return false; } @Override public boolean isNonReplayable() { return false; } @Override public boolean isRequestingTokens() { return false; } @Override public String getUserId() { return null; } @Override public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required) { return null; } @Override public MslUser getUser() { return null; } @Override public Set<KeyRequestData> getKeyRequestData() { return Collections.unmodifiableSet(keyRequestData); } @Override public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) { } @Override public void write(final MessageOutputStream output) throws IOException { output.close(); } @Override public MessageDebugContext getDebugContext() { return dbgCtx; } /** Message debug context. */ private final MessageDebugContext dbgCtx; private final HashSet<KeyRequestData> keyRequestData; }
2,020
0
Create_ds/msl/examples/burp/src/main/java/burp/msl
Create_ds/msl/examples/burp/src/main/java/burp/msl/msg/CaptureMessageDebugContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp.msl.msg; import com.netflix.msl.msg.Header; import com.netflix.msl.msg.MessageDebugContext; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * <p>Capture sent and received MSL (message and error) headers.</p> * * @author Wesley Miaw <[email protected]> */ public class CaptureMessageDebugContext implements MessageDebugContext { /** * <p>Create a new capture message debug context that will capture sent * and/or received headers.</p> * * @param captureSent capture sent headers. * @param captureReceived capture received headers. */ public CaptureMessageDebugContext(final boolean captureSent, final boolean captureReceived) { this.captureSent = captureSent; this.captureReceived = captureReceived; } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageDebugContext#sentHeader(com.netflix.msl.msg.Header) */ @Override public void sentHeader(final Header header) { if (captureSent) sent.add(header); } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageDebugContext#receivedHeader(com.netflix.msl.msg.Header) */ @Override public void receivedHeader(final Header header) { if (captureReceived) received.add(header); } /** * @return the sent headers, in order. */ public List<Header> getSentHeaders() { return Collections.unmodifiableList(sent); } /** * @return the received headers, in order. */ public List<Header> getReceivedHeaders() { return Collections.unmodifiableList(received); } /** Capture sent headers. */ private final boolean captureSent; /** Capture received headers. */ private final boolean captureReceived; /** Sent headers. */ private final List<Header> sent = new ArrayList<Header>(); /** Received headers. */ private final List<Header> received = new ArrayList<Header>(); }
2,021
0
Create_ds/msl/examples/burp/src/main/java/burp/msl
Create_ds/msl/examples/burp/src/main/java/burp/msl/msg/WiretapMessageInputStream.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp.msl.msg; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Set; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslEntityAuthException; import com.netflix.msl.MslError; import com.netflix.msl.MslException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.MslMasterTokenException; import com.netflix.msl.MslMessageException; import com.netflix.msl.MslUserAuthException; import com.netflix.msl.MslUserIdTokenException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.io.MslEncoderException; import com.netflix.msl.io.MslEncoderFactory; import com.netflix.msl.io.MslObject; import com.netflix.msl.keyx.KeyRequestData; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.util.Base64; import com.netflix.msl.util.MslContext; /** * User: skommidi * Date: 9/24/14 */ public class WiretapMessageInputStream extends MessageInputStream { /** Key payload. */ private static final String KEY_PAYLOAD = "payload"; /** Key signature. */ private static final String KEY_SIGNATURE = "signature"; /** * <p>Construct a new message input stream. The header is parsed.</p> * * <p>If key request data is provided and a matching key response data is * found in the message header the key exchange will be performed to * process the message payloads.</p> * * <p>Service tokens will be decrypted and verified with the provided crypto * contexts identified by token name. A default crypto context may be * provided by using the empty string as the token name; if a token name is * not explcitly mapped onto a crypto context, the default crypto context * will be used.</p> * * @param ctx MSL context. * @param source MSL input stream. * @param keyRequestData key request data to use when processing key * response data. * @param cryptoContexts the map of service token names onto crypto * contexts used to decrypt and verify service tokens. * @throws IOException if there is a problem reading from the input stream. * @throws MslEncodingException if there is an error parsing the message. * @throws MslCryptoException if there is an error decrypting or verifying * the header or creating the message payload crypto context. * @throws MslEntityAuthException if unable to create the entity * authentication data. * @throws MslUserAuthException if unable to create the user authentication * data. * @throws MslMessageException if the message master token is expired and * the message is not renewable. * @throws MslMasterTokenException if the master token is not trusted and * needs to be or if it has been revoked. * @throws MslUserIdTokenException if the user ID token has been revoked. * @throws MslKeyExchangeException if there is an error with the key * request data or key response data or the key exchange scheme is * not supported. * @throws MslMessageException if the message master token is expired and * the message is not renewable. * @throws MslException if the message does not contain an entity * authentication data or a master token, or a token is improperly * bound to another token. */ public WiretapMessageInputStream(final MslContext ctx, final InputStream source, final Set<KeyRequestData> keyRequestData, final Map<String, ICryptoContext> cryptoContexts) throws IOException, MslEncodingException, MslEntityAuthException, MslCryptoException, MslUserAuthException, MslMessageException, MslKeyExchangeException, MslMasterTokenException, MslUserIdTokenException, MslMessageException, MslException { super(ctx, source, keyRequestData, cryptoContexts); this.ctx = ctx; } /** * <p>Retrieve the next payload chunk as a decrypted MSL object.</p> * * @return the next payload chunk or {@code null} if none remaining. * @throws MslEncodingException if there is a problem parsing the data. * @throws MslMessageException if the payload verification failed. * @throws MslCryptoException if there is a problem decrypting or verifying * the payload chunk. */ public MslObject nextPayload() throws MslEncodingException, MslMessageException, MslCryptoException { // Grab the next payload chunk MSL object. final MslObject payloadChunk = nextMslObject(); if (payloadChunk == null) return null; // Verify the payload chunk and pull the payload ciphertext. final MslEncoderFactory encoder = ctx.getMslEncoderFactory(); final ICryptoContext cryptoContext = getPayloadCryptoContext(); byte[] payload; try { payload = payloadChunk.getBytes(KEY_PAYLOAD); final byte[] signature = payloadChunk.getBytes(KEY_SIGNATURE); if (!cryptoContext.verify(payload, signature, encoder)) throw new MslCryptoException(MslError.PAYLOAD_VERIFICATION_FAILED); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "payload chunk " + payloadChunk.toString(), e); } // Decrypt the payload. final byte[] plaintext = cryptoContext.decrypt(payload, encoder); // Parse the decrypted payload. try { final MslObject payloadMo = encoder.parseObject(plaintext); return payloadMo; } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "payload chunk payload " + Base64.encode(plaintext), e); } } /** MSL context. */ private final MslContext ctx; }
2,022
0
Create_ds/msl/examples/burp/src/main/java/burp/msl
Create_ds/msl/examples/burp/src/main/java/burp/msl/tokens/EchoingTokenFactory.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp.msl.tokens; import java.util.Date; import javax.crypto.SecretKey; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslError; import com.netflix.msl.MslException; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.io.MslObject; import com.netflix.msl.tokens.MasterToken; import com.netflix.msl.tokens.MockMslUser; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.tokens.TokenFactory; import com.netflix.msl.tokens.UserIdToken; import com.netflix.msl.util.MslContext; /** * <p>This token factory accepts all tokens, creates dummy tokens, and echoes * back tokens for renewal. We must return dummy tokens even though they won't * be used because it is not acceptable to return {@code null} and response * messages will be automatically generated when responding to handshake * requests.</p> * * @author Wesley Miaw <[email protected]> */ public class EchoingTokenFactory implements TokenFactory { /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isMasterTokenRevoked(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken) */ @Override public MslError isMasterTokenRevoked(final MslContext ctx, final MasterToken masterToken) { return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#acceptNonReplayableId(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, long) */ @Override public MslError acceptNonReplayableId(final MslContext ctx, final MasterToken masterToken, final long nonReplayableId) { return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.entityauth.EntityAuthenticationData, javax.crypto.SecretKey, javax.crypto.SecretKey, com.netflix.msl.io.MslObject) */ @Override public MasterToken createMasterToken(final MslContext ctx, final EntityAuthenticationData entityAuthData, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException { final Date renewalWindow = new Date(); final Date expiration = renewalWindow; final String identity = entityAuthData.getIdentity(); return new MasterToken(ctx, renewalWindow, expiration, 0, 0, issuerData, identity, hmacKey, hmacKey); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isMasterTokenRenewable(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken) */ @Override public MslError isMasterTokenRenewable(final MslContext ctx, final MasterToken masterToken) { return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#renewMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, javax.crypto.SecretKey, javax.crypto.SecretKey, com.netflix.msl.io.MslObject) */ @Override public MasterToken renewMasterToken(final MslContext ctx, final MasterToken masterToken, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) { return masterToken; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isUserIdTokenRevoked(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken) */ @Override public MslError isUserIdTokenRevoked(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken) { return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MslUser, com.netflix.msl.tokens.MasterToken) */ @Override public UserIdToken createUserIdToken(final MslContext ctx, final MslUser user, final MasterToken masterToken) throws MslEncodingException, MslCryptoException { final Date renewalWindow = new Date(); final Date expiration = renewalWindow; return new UserIdToken(ctx, renewalWindow, expiration, masterToken, 0, null, user); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#renewUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.UserIdToken, com.netflix.msl.tokens.MasterToken) */ @Override public UserIdToken renewUserIdToken(final MslContext ctx, final UserIdToken userIdToken, final MasterToken masterToken) { return userIdToken; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createUser(com.netflix.msl.util.MslContext, java.lang.String) */ @Override public MslUser createUser(final MslContext ctx, final String userdata) throws MslException { try { return new MockMslUser(userdata); } catch (final Throwable t) { throw new MslException(MslError.USERIDTOKEN_USERDATA_INVALID, userdata, t); } } }
2,023
0
Create_ds/msl/examples/kancolle/src/main/java
Create_ds/msl/examples/kancolle/src/main/java/kancolle/KanColleFactory.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle; import kancolle.entityauth.KanmusuDatabase; import kancolle.entityauth.NavalPortDatabase; import kancolle.userauth.OfficerDatabase; import kancolle.util.ConsoleManager; import kancolle.util.KanmusuMslContext; import kancolle.util.NavalPortMslContext; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslInternalException; /** * <p>KanColle Kanmusu ships and naval ports factory.</p> * * @author Wesley Miaw <[email protected]> */ public class KanColleFactory { /** * <p>Create a new KanColle factory backed by the provided databases.</p> * * @param ships ships database. * @param ports ports database. * @param officers officers database. */ public KanColleFactory(final KanmusuDatabase ships, final NavalPortDatabase ports, final OfficerDatabase officers) { this.ships = ships; this.ports = ports; this.officers = officers; } /** * <p>Create a new naval port with the specified callsign.</p> * * @param callsign port callsign. * @return a new naval port. */ public NavalPort createNavalPort(final String callsign) { final NavalPortMslContext ctx = new NavalPortMslContext(callsign, ships, ports, officers); try { return new NavalPort(ctx, console); } catch (final MslCryptoException e) { throw new MslInternalException("Unable to retrieve entity authentication data identity.", e); } } /** * <p>Create a new Kanmusu ship with the specified type and name and origin * naval port.</p> * * @param type ship type. * @param name ship name. * @param officer officer name. * @param fingerprint officer fingerprint. * @param port origin port. * @return a new Kanmusu ship. */ public Kanmusu createKanmusu(final String type, final String name, final String officer, final byte[] fingerprint, final NavalPort port) { try { final KanmusuMslContext ctx = new KanmusuMslContext(type, name, ships, ports, officers); return new Kanmusu(ctx, officer, fingerprint, port, console); } catch (final MslCryptoException e) { throw new MslInternalException("Unable to retrieve entity authentication data identity.", e); } } /** Shared console manager. */ private final ConsoleManager console = new ConsoleManager(); /** Ships database. */ private final KanmusuDatabase ships; /** Ports database. */ private final NavalPortDatabase ports; /** Officers database. */ private final OfficerDatabase officers; }
2,024
0
Create_ds/msl/examples/kancolle/src/main/java
Create_ds/msl/examples/kancolle/src/main/java/kancolle/KanColleConstants.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle; /** * @author Wesley Miaw <[email protected]> */ public class KanColleConstants { /** English US BCP-47 code. */ public static final String en_US = "en-US"; /** Japanese Japan BCP-47 code. */ public static final String ja_JP = "ja-JP"; }
2,025
0
Create_ds/msl/examples/kancolle/src/main/java
Create_ds/msl/examples/kancolle/src/main/java/kancolle/KanColleMslError.java
/** * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle; import com.netflix.msl.MslConstants.ResponseCode; import com.netflix.msl.MslError; /** * <p>KanColle error codes and descriptions.</p> * * @author Wesley Miaw <[email protected]> */ public class KanColleMslError extends MslError { /** KanColle internal error code offset value. */ private static final int OFFSET = 100000; // 0 Message Security Layer // 1 Master Token public static final MslError KANMUSU_REVOKED_DESTROYED = new KanColleMslError(1000, ResponseCode.ENTITYDATA_REAUTH, "Kanmusu revoked because it was confirmed destroyed."); public static final MslError KANMUSU_REVOKED_UNKNOWN = new KanColleMslError(1001, ResponseCode.ENTITYDATA_REAUTH, "Kanmusu revoked because the ship identity is unknown."); public static final MslError NAVALPORT_REVOKED_DESTROYED = new KanColleMslError(1002, ResponseCode.ENTITYDATA_REAUTH, "Naval port revoked because it was confirmed destroyed."); public static final MslError NAVALPORT_REVOKED_UNKNOWN = new KanColleMslError(1003, ResponseCode.ENTITYDATA_REAUTH, "Naval port revoked because the callsign is unknown."); public static final MslError NAVALPORT_REVOKED_INACTIVE = new KanColleMslError(1004, ResponseCode.ENTITYDATA_REAUTH, "Naval port revoked because it is inactive."); // 2 User ID Token public static final MslError OFFICER_REVOKED_DISCHARGED = new KanColleMslError(2000, ResponseCode.USERDATA_REAUTH, "Officer revoked because it was discharged."); public static final MslError OFFICER_REVOKED_COURT_MARTIALED = new KanColleMslError(2001, ResponseCode.USERDATA_REAUTH, "Officer revoked because it was court martialed."); public static final MslError OFFICER_REVOKED_DECEASED = new KanColleMslError(2002, ResponseCode.USERDATA_REAUTH, "Officer revoked because it is deceased."); public static final MslError OFFICER_REVOKED_KIA = new KanColleMslError(2003, ResponseCode.USERDATA_REAUTH, "Officer revoked because it was killed in action."); public static final MslError OFFICER_REVOKED_UNKNOWN = new KanColleMslError(2004, ResponseCode.USERDATA_REAUTH, "Officer revoked because it is unknown."); // 3 Service Token // 4 Entity Authentication public static final MslError ENTITYAUTH_KANMUSU_DESTROYED = new KanColleMslError(4000, ResponseCode.ENTITYDATA_REAUTH, "Kanmusu confirmed destroyed."); public static final MslError ENTITYAUTH_NAVALPORT_DESTROYED = new KanColleMslError(4001, ResponseCode.ENTITYDATA_REAUTH, "Naval port confirmed destroyed."); public static final MslError ENTITYAUTH_NAVALPORT_INACTIVE = new KanColleMslError(4002, ResponseCode.ENTITYDATA_REAUTH, "Naval port inactive."); public static final MslError KANMUSU_ILLEGAL_IDENTITY = new KanColleMslError(4003, ResponseCode.ENTITYDATA_REAUTH, "Kanmusu type or name contains a colon."); public static final MslError NAVALPORT_ILLEGAL_IDENTITY = new KanColleMslError(4004, ResponseCode.ENTITYDATA_REAUTH, "Naval port callsign contains a colon."); // 5 User Authentication public static final MslError OFFICER_FINGERPRINT_INCORRECT = new KanColleMslError(5000, ResponseCode.USERDATA_REAUTH, "Officer name or fingerprint is incorrect."); public static final MslError OFFICER_NOT_FOUND = new KanColleMslError(5001, ResponseCode.USERDATA_REAUTH, "Officer name not found."); public static final MslError USERAUTH_OFFICER_DISCHARGED = new KanColleMslError(5002, ResponseCode.USERDATA_REAUTH, "Officer was honorably discharged."); public static final MslError USERAUTH_OFFICER_COURT_MARTIALED = new KanColleMslError(5003, ResponseCode.USERDATA_REAUTH, "Officer was court martialed."); public static final MslError USERAUTH_OFFICER_KIA = new KanColleMslError(5004, ResponseCode.USERDATA_REAUTH, "Officer confirmed killed in action."); public static final MslError USERAUTH_OFFICER_DECEASED = new KanColleMslError(5005, ResponseCode.USERDATA_REAUTH, "Officer confirmed deceased."); // 6 Message public static final MslError MSG_TYPE_UNKNOWN = new KanColleMslError(6001, ResponseCode.FAIL, "Message type unknown."); public static final MslError MSG_RECORD_COUNT_INVALID = new KanColleMslError(6002, ResponseCode.FAIL, "Message record count is not a number."); public static final MslError MSG_RECORDS_TRUNCATED = new KanColleMslError(6003, ResponseCode.FAIL, "Premature end of message records."); public static final MslError MSG_RECORD_NUMBER_MISSING = new KanColleMslError(6004, ResponseCode.FAIL, "Message record is missing the initial record number."); public static final MslError MSG_RECORD_NUMBER_MISMATCH = new KanColleMslError(6005, ResponseCode.FAIL, "Message record number is incorrect."); // 7 Key Exchange // 9 Internal Errors /** * Construct a KanColle MSL error with the specified internal and response * error codes and message. * * @param internalCode internal error code. * @param responseCode response error code. * @param message developer-consumable error message. */ protected KanColleMslError(final int internalCode, final ResponseCode responseCode, final String msg) { super(OFFSET + internalCode, responseCode, msg); } }
2,026
0
Create_ds/msl/examples/kancolle/src/main/java
Create_ds/msl/examples/kancolle/src/main/java/kancolle/NavalPort.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import kancolle.kc.KanColleServer; import kancolle.msg.AckMessageContext; import kancolle.msg.ErrorMessageContext; import kancolle.msg.Message; import kancolle.msg.Message.Type; import kancolle.msg.MessageProcessor; import kancolle.msg.OrderResponseMessageContext; import kancolle.msg.ReceiveMessageContext; import kancolle.util.ConsoleManager; import kancolle.util.NavalPortMslContext; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslMessageException; import com.netflix.msl.msg.ErrorHeader; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.msg.MslControl; import com.netflix.msl.msg.MslControl.MslChannel; import com.netflix.msl.util.MslContext; /** * <p>KanColle naval port.</p> * * @author Wesley Miaw <[email protected]> */ public class NavalPort extends Thread implements KanColleServer { /** * Connection struct. */ private static class Connection { /** * @param in input stream from remote entity. * @param out output stream to remote entity. */ public Connection(final InputStream in, final OutputStream out) { this.in = in; this.out = out; } /** Input stream from remote entity. */ public final InputStream in; /** Output stream to remote entity. */ public final OutputStream out; } /** * <p>Create a new naval port.</p> * * @param ctx this naval port's MSL context. * @param console the console manager. * @throws MslCryptoException if there is an error getting the naval port * identity from the MSL context. */ NavalPort(final NavalPortMslContext ctx, final ConsoleManager console) throws MslCryptoException { this.ctx = ctx; this.identity = ctx.getEntityAuthenticationData(null).getIdentity(); this.console = console; this.ctrl = new MslControl(0); } /** * @return the naval port callsign. */ @Override public String getIdentity() { return identity; } /** * <p>Accept a connection from a remote entity.</p> * * @param in input stream from remote entity. * @param out output stream to remote entity. * @throws IOException if the connection cannot be established. */ @Override public void connect(final InputStream in, final OutputStream out) throws IOException { try { final Connection c = new Connection(in, out); queue.put(c); } catch (final InterruptedException e) { throw new IOException("Failed to place connection onto the queue.", e); } } @Override public void run() { // Wait for a connection. while (true) try { final Connection c = queue.take(); // Receive the message. final MessageContext rcvCtx = new ReceiveMessageContext(); final Future<MessageInputStream> requestFuture = ctrl.receive(ctx, rcvCtx, c.in, c.out, 0); final MessageInputStream request; try { request = requestFuture.get(); } catch (final ExecutionException e) { e.printStackTrace(System.err); continue; } if (request == null) continue; // Log errors. final ErrorHeader error = request.getErrorHeader(); if (error != null) { console.error(identity, error); continue; } // Read message. final Message message; try { message = MessageProcessor.parse(request); } catch (final MslMessageException e) { e.printStackTrace(System.err); continue; } catch (final IOException e) { e.printStackTrace(System.err); continue; } console.message(identity, message); // If requesting orders prompt for order entry. MessageContext respCtx; if (message.getType() == Type.ORDER_REQUEST) { try { final String requestor = request.getIdentity(); final String orders = console.in(identity, "Orders for " + requestor); respCtx = new OrderResponseMessageContext(orders); } catch (final MslCryptoException e) { e.printStackTrace(System.err); respCtx = new ErrorMessageContext(e.getMessage()); } } // Otherwise simply acknowledge the message. else { respCtx = new AckMessageContext(); } // Send the response. final Future<MslChannel> respondFuture = ctrl.respond(ctx, respCtx, c.in, c.out, request, 0); try { respondFuture.get(); } catch (final ExecutionException e) { e.printStackTrace(System.err); continue; } } catch (final InterruptedException e) { e.printStackTrace(System.err); break; } } /** MSL context. */ private final MslContext ctx; /** Naval port identity. */ private final String identity; /** Console manager. */ private final ConsoleManager console; /** MSL control. */ private final MslControl ctrl; /** Input/Output connection queue. */ private final BlockingQueue<Connection> queue = new LinkedBlockingQueue<Connection>(); }
2,027
0
Create_ds/msl/examples/kancolle/src/main/java
Create_ds/msl/examples/kancolle/src/main/java/kancolle/Kanmusu.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import kancolle.keyx.DiffieHellmanManager; import kancolle.keyx.KanColleDiffieHellmanParameters; import kancolle.msg.CriticalMessageContext; import kancolle.msg.Message; import kancolle.msg.Message.Type; import kancolle.msg.MessageProcessor; import kancolle.msg.OrderRequestMessageContext; import kancolle.msg.PingMessageContext; import kancolle.msg.ReportMessageContext; import kancolle.util.ConsoleManager; import kancolle.util.KanmusuMslContext; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslMessageException; import com.netflix.msl.io.JavaUrl; import com.netflix.msl.io.Url; import com.netflix.msl.msg.ErrorHeader; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.msg.MslControl; import com.netflix.msl.msg.MslControl.MslChannel; import com.netflix.msl.util.MslContext; /** * <p>KanColle Kanmusu ship.</p> * * @author Wesley Miaw <[email protected]> */ public class Kanmusu extends Thread { /** Ping interval in milliseconds. */ private static final long PING_INTERVAL = 10000; /** * Request container struct. */ private static class Request { /** * @param msgCtx request message context. * @param responseType expected response message type. */ public Request(final MessageContext msgCtx, final Type responseType) { this.msgCtx = msgCtx; this.responseType = responseType; } /** Request message context. */ public final MessageContext msgCtx; /** Expected response type. */ public final Type responseType; } /** * <p>Create a new Kanmusu ship.</p> * * @param ctx Kanmusu MSL context. * @param name officer name. * @param fingerprint officer fingerprint. * @param port port of origin. * @param console the console manager. * @throws MslCryptoException if there is an error getting the Kanmusu ship * identity from the MSL context. */ Kanmusu(final KanmusuMslContext ctx, final String name, final byte[] fingerprint, final NavalPort port, final ConsoleManager console) throws MslCryptoException { this.ctx = ctx; this.identity = ctx.getEntityAuthenticationData(null).getIdentity(); this.name = name; this.fingerprint = fingerprint; this.port = port; this.console = console; this.ctrl = new MslControl(0); final KanColleDiffieHellmanParameters parameters = new KanColleDiffieHellmanParameters(); this.keyxManager = new DiffieHellmanManager(parameters, KanColleDiffieHellmanParameters.PARAM_ID); } /** * <p>Change the origin naval port for this ship.</p> * * @param port the new port of origin. */ public void changeOriginPort(final NavalPort port) { dataLock.lock(); try { this.port = port; } finally { dataLock.unlock(); } } /** * <p>Send a report to the port of origin.</p> * * @param records report records. * @throws InterruptedException if interrupted while attempting to queue * the request. */ public void report(final List<String> records) throws InterruptedException { final MessageContext msgCtx = new ReportMessageContext(name, fingerprint, records, keyxManager); final Request request = new Request(msgCtx, Type.ACK); requests.put(request); } /** * <p>Send a critical report to the port of origin.</p> * * @param records report records. * @throws InterruptedException if interrupted while attempting to queue * the request. */ public void critical(final List<String> records) throws InterruptedException { final String callsign = port.getIdentity(); final MessageContext msgCtx = new CriticalMessageContext(name, fingerprint, callsign, records, keyxManager); final Request request = new Request(msgCtx, Type.ACK); requests.put(request); } /** * <p>Request orders from the port of origin.</p> * * @throws InterruptedException if interrupted while attempting to queue * the request. */ public void requestOrders() throws InterruptedException { final MessageContext msgCtx = new OrderRequestMessageContext(name, fingerprint, keyxManager); final Request request = new Request(msgCtx, Type.ORDER_RESPONSE); requests.put(request); } @Override public void run() { while (true) try { // Construct the port URL. final Url portUrl = new JavaUrl(new URL("kc://" + port.getIdentity() + "/")); // Wait for a request or send a ping if the ping interval has // elapsed. final Request request; final long now = System.currentTimeMillis(); if (now >= lastPing + PING_INTERVAL) { final MessageContext msgCtx = new PingMessageContext(); request = new Request(msgCtx, Type.ACK); } else { request = requests.poll(PING_INTERVAL, TimeUnit.MILLISECONDS); if (request == null) continue; } // Send the request. final Future<MslChannel> future = ctrl.request(ctx, request.msgCtx, portUrl, 0); final MslChannel channel; try { channel = future.get(); } catch (final ExecutionException e) { e.printStackTrace(System.err); continue; } catch (final InterruptedException e) { e.printStackTrace(System.err); continue; } // Check for cancellation or interruption. if (channel == null) continue; // Check for an error. final MessageInputStream mis = channel.input; final ErrorHeader error = mis.getErrorHeader(); if (error != null) { console.error(identity, error); continue; } // Parse the response. final Message response; try { response = MessageProcessor.parse(mis); } catch (final MslMessageException e) { e.printStackTrace(System.err); continue; } catch (final IOException e) { e.printStackTrace(System.err); continue; } // Verify the response. final Type type = response.getType(); if (!request.responseType.equals(type)) { console.out(identity, "Expected response type " + request.responseType + "; received response type " + type + "."); continue; } // Output the response. console.message(identity, response); } catch (final MalformedURLException e) { e.printStackTrace(System.err); break; } catch (final InterruptedException e) { e.printStackTrace(System.err); break; } } /** MSL context. */ private final MslContext ctx; /** Kanmusu ship identity. */ private final String identity; /** Console manager. */ private final ConsoleManager console; /** MSL control. */ private final MslControl ctrl; /** Key exchange manager. */ private final DiffieHellmanManager keyxManager; /** Officer name. */ private String name; /** Officer fingerprint. */ private byte[] fingerprint; /** Default naval port. */ private NavalPort port; /** Time of last ping. */ private long lastPing = 0; /** Queued requests. */ private final BlockingQueue<Request> requests = new LinkedBlockingQueue<Request>(); /** Data lock. */ private final Lock dataLock = new ReentrantLock(); }
2,028
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/crypto/KanColleCryptoContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.crypto; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import com.netflix.msl.MslInternalException; import com.netflix.msl.crypto.SymmetricCryptoContext; import com.netflix.msl.util.MslContext; /** * <p>This crypto context derives an AES-128 and HMAC-SHA256 key pair from the * SHA-384 of a secret value.</p> * * @author Wesley Miaw <[email protected]> */ public class KanColleCryptoContext extends SymmetricCryptoContext { /** AES-128 algorithm. */ private static final String AES_ALGO = "AES"; /** HMAC-SHA256 algorithm. */ private static final String HMAC_SHA256_ALGO = "HmacSHA256"; /** SHA-384 algorithm. */ private static final String SHA_384_ALGO = "SHA-384"; /** AES-128 key length in bytes. */ private static final int AES_128_LENGTH = 16; /** HMAC-SHA256 key length in bytes. */ private static final int HMAC_SHA256_LENGTH = 32; /** * Derives an AES-128 key from the first 16 bytes of the SHA-384 of the * secret. * * @param secret the secret. * @return the encryption key. */ private static SecretKey deriveEncryptionKey(final String secret) { try { final MessageDigest sha384 = MessageDigest.getInstance(SHA_384_ALGO); final byte[] hash = sha384.digest(secret.getBytes()); final byte[] keydata = Arrays.copyOf(hash, AES_128_LENGTH); return new SecretKeySpec(keydata, AES_ALGO); } catch (final NoSuchAlgorithmException e) { throw new MslInternalException(SHA_384_ALGO + " algorithm not found.", e); } } /** * Derives an HMAC-SHA256 key from the last 32 bytes of the SHA-384 of the * secret. * * @param secret the secret. * @return the HMAC key. */ private static SecretKey deriveHmacKey(final String secret) { try { final MessageDigest sha384 = MessageDigest.getInstance(SHA_384_ALGO); final byte[] hash = sha384.digest(secret.getBytes()); final byte[] keydata = Arrays.copyOfRange(hash, AES_128_LENGTH, AES_128_LENGTH + HMAC_SHA256_LENGTH); return new SecretKeySpec(keydata, HMAC_SHA256_ALGO); } catch (final NoSuchAlgorithmException e) { throw new MslInternalException(SHA_384_ALGO + " algorithm not found.", e); } } /** * Create a new KanColle crypto context from the given secret. * * @param ctx MSL context. * @param id the key set identity. * @param secret the secret. */ public KanColleCryptoContext(final MslContext ctx, final String id, final String secret) { super(ctx, id, deriveEncryptionKey(secret), deriveHmacKey(secret), null); } }
2,029
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/kc/Handler.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.kc; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; /** * <p>KanColle URL stream handler.</p> * * @author Wesley Miaw <[email protected]> */ public class Handler extends URLStreamHandler { /* (non-Javadoc) * @see java.net.URLStreamHandler#openConnection(java.net.URL) */ @Override protected URLConnection openConnection(final URL u) throws IOException { return new KcConnection(u); } }
2,030
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/kc/KcConnection.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.kc; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.net.URL; import java.net.URLConnection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * <p>A local URL connection backed by piped input and output streams. The * registered protocol is "kc".</p> * * @author Wesley Miaw <[email protected]> */ public class KcConnection extends URLConnection { /** Known servers. */ private static final Map<String,KanColleServer> servers = new ConcurrentHashMap<String,KanColleServer>(); /** * <p>Register a KanColle server. It can then be connected by using a URL * {@code kc://identity} where {@code identity} is the server identity.</p> * * @param server KanColle server. */ public static void addServer(final KanColleServer server) { final String identity = server.getIdentity(); servers.put(identity, server); } /** * <p>Construct a URL connection to the specified URL.</p> * * @param u the specified URL. */ public KcConnection(final URL u) { super(u); } /* (non-Javadoc) * @see java.net.URLConnection#connect() */ @Override public void connect() throws IOException { // Lookup the port identified in the URL. final String identity = url.getHost(); final KanColleServer server = servers.get(identity); if (server == null) throw new IOException("No server registered with the identity " + identity + "."); // Create the piped input and output streams. final PipedOutputStream portOutput = new PipedOutputStream(); in = new PipedInputStream(portOutput); final PipedInputStream portInput = new PipedInputStream(); out = new PipedOutputStream(portInput); // Connect to the port. server.connect(portInput, portOutput); } /* (non-Javadoc) * @see java.net.URLConnection#getInputStream() */ @Override public InputStream getInputStream() { return in; } /* (non-Javadoc) * @see java.net.URLConnection#getOutputStream() */ @Override public OutputStream getOutputStream() throws IOException { return out; } /** Input stream to read from the URL. */ private InputStream in; /** Output stream to write to the URL. */ private OutputStream out; }
2,031
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/kc/KcStreamHandlerFactory.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.kc; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; /** * <p>URL stream handler factory for the KanColle protocol.</p> * * @author Wesley Miaw <[email protected]> */ public class KcStreamHandlerFactory implements URLStreamHandlerFactory { /* (non-Javadoc) * @see java.net.URLStreamHandlerFactory#createURLStreamHandler(java.lang.String) */ @Override public URLStreamHandler createURLStreamHandler(final String protocol) { if ("kc".equals(protocol)) return new Handler(); return null; } }
2,032
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/kc/KanColleServer.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.kc; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * <p>A KanColle server accepts connections and is identified by its MSL entity * identity.</p> * * @author Wesley Miaw <[email protected]> */ public interface KanColleServer { /** * <p>Return the server identity.</p> * * @return the server identity. */ public String getIdentity(); /** * <p>Establish a connection between the remote entity and this server. The * input stream is used by the server to read data from the remote entity. * The output stream is used by the server to send data to the remote * entity.</p> * * @param in input stream from remote entity. * @param out output stream to remote entity. * @throws IOException if the connection cannot be established. */ public void connect(final InputStream in, final OutputStream out) throws IOException; }
2,033
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/app/KanColle.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.app; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.HashSet; import java.util.Properties; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import kancolle.entityauth.CodeBook; import kancolle.entityauth.FivePageCodeBook; import kancolle.kc.KcStreamHandlerFactory; /** * <p>KanColle application.</p> * * @author Wesley Miaw <[email protected]> */ public class KanColle { /** Kanmusu database resource name. */ private static final String KANMUSU_DB = "/kancolle/db/kanmusu.properties"; /** Officer database resource name. */ private static final String OFFICER_DB = "/kancolle/db/officers.properties"; /** Naval port database resource name. */ private static final String PORT_DB = "/kancolle/db/ports.properties"; /** Code book resource directory. */ private static final String CODEBOOK_DIRECTORY = "/kancolle/codebooks/"; /** * <p>Load a properties resource.</p> * * @param filename properties filename. * @return the loaded properties. * @throws IOException if there is an error loading the properties file. */ private static Properties loadProperties(final String filename) throws IOException { final Properties p = new Properties(); final InputStream in = KanColle.class.getResourceAsStream(filename); if (in == null) throw new FileNotFoundException(filename); try { p.load(in); return p; } finally { in.close(); } } /** * <p>Load a code book resource.</p> * * @param filename code book filename. * @return the loaded code book. * @throws IOException if there is an error reading the code book file. */ private static CodeBook loadCodebook(final String filename) throws IOException { final InputStream in = KanColle.class.getResourceAsStream(filename); if (in == null) throw new FileNotFoundException(filename); try { return new FivePageCodeBook(in); } finally { in.close(); } } /** * <p>Return all file resources found under the specified directory.</p> * * @param directory resource directory. * @return the file resources found in the directory. * @throws IOException if there is an error accessing the directory. * @throws URISyntaxException if there is an error accessing the directory. */ private static String[] getSubResources(final String directory) throws IOException, URISyntaxException { final URL dir = KanColle.class.getResource(directory); if (dir == null) throw new FileNotFoundException(directory); // Handle file loads. if (dir.getProtocol().equals("file")) { final Set<String> result = new HashSet<String>(); final String[] files = new File(dir.toURI()).list(); for (final String file : files) result.add(directory + (directory.endsWith("/") ? "" : "/")+ file); return result.toArray(new String[result.size()]); } // Handle JAR loads. if (dir.getProtocol().equals("jar")) { // Courtesy {@link http://stackoverflow.com/questions/6247144/how-to-load-a-folder-from-a-jar} final String jarPath = dir.getPath().substring(5, dir.getPath().indexOf('!')); final JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); try { final Enumeration<JarEntry> entries = jar.entries(); final Set<String> result = new HashSet<String>(); while (entries.hasMoreElements()) { final String name = entries.nextElement().getName(); if (name.startsWith(directory)) { final String entry = name.substring(directory.length()); // Skip sub-directories. final int checkSubdir = entry.indexOf('/'); if (checkSubdir >= 0) continue; result.add(name); } } return result.toArray(new String[result.size()]); } finally { jar.close(); } } // Fail. throw new IOException("Unable to retrieve contents of " + directory + " using " + dir.toURI() + "."); } /** * @param args command line arguments. * @throws IOException if there is an error loading the configuration data. * @throws URISyntaxException if there is an error accessing the code book * directory. */ public static void main(final String[] args) throws IOException, URISyntaxException { // Register KanColle stream handler factory. The system property is an // alternative mechanism included for informational purposes. URL.setURLStreamHandlerFactory(new KcStreamHandlerFactory()); System.setProperty("java.protocol.handler.pkgs", "kancolle.kc"); // Read the databases. final Properties kanmusuProps = loadProperties(KANMUSU_DB); final Properties officerProps = loadProperties(OFFICER_DB); final Properties portProps = loadProperties(PORT_DB); // Read the codebooks. final String[] codebookUrls = getSubResources(CODEBOOK_DIRECTORY); final Set<CodeBook> codebooks = new HashSet<CodeBook>(); for (final String codebookUrl : codebookUrls) { final CodeBook codebook = loadCodebook(codebookUrl); codebooks.add(codebook); } // Create officers. // Create ports. // Create Kanmusu. } }
2,034
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/util/KanColleMslContext.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.util; import java.security.SecureRandom; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import kancolle.KanColleConstants; import kancolle.entityauth.KanColleEntityAuthenticationScheme; import kancolle.entityauth.KanmusuAuthenticationFactory; import kancolle.entityauth.KanmusuDatabase; import kancolle.entityauth.NavalPortAuthenticationFactory; import kancolle.entityauth.NavalPortDatabase; import kancolle.keyx.KanColleDiffieHellmanParameters; import kancolle.keyx.KanColleKeyxComparator; import kancolle.tokens.KanColleTokenFactory; import kancolle.userauth.KanColleUserAuthenticationScheme; import kancolle.userauth.OfficerAuthenticationFactory; import kancolle.userauth.OfficerDatabase; import com.netflix.msl.MslConstants.CompressionAlgorithm; import com.netflix.msl.entityauth.EntityAuthenticationFactory; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.io.DefaultMslEncoderFactory; import com.netflix.msl.io.MslEncoderFactory; import com.netflix.msl.io.MslEncoderFormat; import com.netflix.msl.keyx.AsymmetricWrappedExchange; import com.netflix.msl.keyx.DiffieHellmanExchange; import com.netflix.msl.keyx.DiffieHellmanParameters; import com.netflix.msl.keyx.KeyExchangeFactory; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.MessageCapabilities; import com.netflix.msl.tokens.TokenFactory; import com.netflix.msl.userauth.UserAuthenticationFactory; import com.netflix.msl.userauth.UserAuthenticationScheme; import com.netflix.msl.util.MslContext; import com.netflix.msl.util.MslStore; import com.netflix.msl.util.SimpleMslStore; /** * <p>KanColle MSL context.</p> * * @author Wesley Miaw <[email protected]> */ public abstract class KanColleMslContext extends MslContext { /** * Create a new KanColle MSL context. * * @param ships Kanmusu ships database. * @param ports naval ports database. * @param officers officers database. */ protected KanColleMslContext(final KanmusuDatabase ships, final NavalPortDatabase ports, final OfficerDatabase officers) { // Message capabilities. final Set<CompressionAlgorithm> compressionAlgos = new HashSet<CompressionAlgorithm>(); compressionAlgos.add(CompressionAlgorithm.GZIP); final List<String> languages = Arrays.asList(KanColleConstants.en_US, KanColleConstants.ja_JP); final Set<MslEncoderFormat> encoderFormats = new HashSet<MslEncoderFormat>(); encoderFormats.add(MslEncoderFormat.JSON); this.messageCaps = new MessageCapabilities(compressionAlgos, languages, encoderFormats); // Auxiliary authentication classes. final DiffieHellmanParameters params = new KanColleDiffieHellmanParameters(); final KanColleAuthenticationUtils authutils = new KanColleAuthenticationUtils(ships, ports, officers); // Entity authentication factories. entityAuthFactories.put(KanColleEntityAuthenticationScheme.KANMUSU, new KanmusuAuthenticationFactory(ships)); entityAuthFactories.put(KanColleEntityAuthenticationScheme.NAVAL_PORT, new NavalPortAuthenticationFactory(ports)); // User authentication factories. userAuthFactories.put(KanColleUserAuthenticationScheme.OFFICER, new OfficerAuthenticationFactory(officers)); // Key exchange factories. keyxFactories.add(new DiffieHellmanExchange(params, authutils)); keyxFactories.add(new AsymmetricWrappedExchange(authutils)); // Token factory. this.tokenFactory = new KanColleTokenFactory(authutils); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getTime() */ @Override public long getTime() { return System.currentTimeMillis(); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getRandom() */ @Override public Random getRandom() { return new SecureRandom(); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#isPeerToPeer() */ @Override public boolean isPeerToPeer() { return false; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getMessageCapabilities() */ @Override public MessageCapabilities getMessageCapabilities() { return messageCaps; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getEntityAuthenticationScheme(java.lang.String) */ @Override public EntityAuthenticationScheme getEntityAuthenticationScheme(final String name) { return EntityAuthenticationScheme.getScheme(name); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getEntityAuthenticationFactory(com.netflix.msl.entityauth.EntityAuthenticationScheme) */ @Override public EntityAuthenticationFactory getEntityAuthenticationFactory(final EntityAuthenticationScheme scheme) { return entityAuthFactories.get(scheme); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getUserAuthenticationScheme(java.lang.String) */ @Override public UserAuthenticationScheme getUserAuthenticationScheme(final String name) { return UserAuthenticationScheme.getScheme(name); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getUserAuthenticationFactory(com.netflix.msl.userauth.UserAuthenticationScheme) */ @Override public UserAuthenticationFactory getUserAuthenticationFactory(final UserAuthenticationScheme scheme) { return userAuthFactories.get(scheme); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getTokenFactory() */ @Override public TokenFactory getTokenFactory() { return tokenFactory; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getKeyExchangeScheme(java.lang.String) */ @Override public KeyExchangeScheme getKeyExchangeScheme(final String name) { return KeyExchangeScheme.getScheme(name); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getKeyExchangeFactory(com.netflix.msl.keyx.KeyExchangeScheme) */ @Override public KeyExchangeFactory getKeyExchangeFactory(final KeyExchangeScheme scheme) { for (final KeyExchangeFactory factory : keyxFactories) { if (factory.getScheme().equals(scheme)) return factory; } return null; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getKeyExchangeFactories() */ @Override public SortedSet<KeyExchangeFactory> getKeyExchangeFactories() { return Collections.unmodifiableSortedSet(keyxFactories); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getMslStore() */ @Override public MslStore getMslStore() { return store; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getMslEncoderFactory() */ @Override public MslEncoderFactory getMslEncoderFactory() { return encoderFactory; } /** Message capabilities. */ private final MessageCapabilities messageCaps; /** Entity authentication factories by scheme. */ private final Map<EntityAuthenticationScheme,EntityAuthenticationFactory> entityAuthFactories = new HashMap<EntityAuthenticationScheme,EntityAuthenticationFactory>(); /** User authentication factories by scheme. */ private final Map<UserAuthenticationScheme,UserAuthenticationFactory> userAuthFactories = new HashMap<UserAuthenticationScheme,UserAuthenticationFactory>(); /** Key exchange factories. */ private final SortedSet<KeyExchangeFactory> keyxFactories = new TreeSet<KeyExchangeFactory>(new KanColleKeyxComparator()); /** Token factory. */ private final TokenFactory tokenFactory; /** MSL store. */ private final MslStore store = new SimpleMslStore(); /** MSL encoder factory. */ private final MslEncoderFactory encoderFactory = new DefaultMslEncoderFactory(); }
2,035
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/util/NavalPortMslContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.util; import java.util.Random; import kancolle.crypto.KanColleCryptoContext; import kancolle.entityauth.CodeBook; import kancolle.entityauth.KanmusuDatabase; import kancolle.entityauth.NavalPortAuthenticationData; import kancolle.entityauth.NavalPortDatabase; import kancolle.userauth.OfficerDatabase; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslInternalException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationData; /** * <p>MSL context for naval ports.</p> * * @author Wesley Miaw <[email protected]> */ public class NavalPortMslContext extends KanColleMslContext { /** MSL crypto context key derivation secret suffix. */ private static final String KEY_DERIVATION_SECRET = "KanColleNavalPortSecret"; /** * Create a new naval port MSL context for the specified port. * * @param callsign naval port callsign. * @param ships Kanmusu ships database. * @param ports naval ports database. * @param officers officers database. * @throws MslCryptoException if there is an error accessing the entity * authentication data identity. * @throws MslInternalException if the callsign is invalid. */ public NavalPortMslContext(final String callsign, final KanmusuDatabase ships, final NavalPortDatabase ports, final OfficerDatabase officers) { super(ships, ports, officers); // Entity authentication data is created on demand. this.callsign = callsign; this.ports = ports; // MSL crypto context individualized to this entity. final String secret = callsign + ":" + KEY_DERIVATION_SECRET; this.mslCryptoContext = new KanColleCryptoContext(this, callsign, secret); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getMslCryptoContext() */ @Override public ICryptoContext getMslCryptoContext() throws MslCryptoException { return mslCryptoContext; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getEntityAuthenticationData(com.netflix.msl.util.MslContext.ReauthCode) */ @Override public synchronized EntityAuthenticationData getEntityAuthenticationData(final ReauthCode reauthCode) { // We cannot provide new entity authentication data. if (reauthCode == ReauthCode.ENTITYDATA_REAUTH) return null; // When having to perform entity re-authentication, or if we don't yet // have entity authentication data, generate new entity authentication // data. if (entityAuthData == null || reauthCode != null) { // Grab the code book. final CodeBook book = ports.getCodeBook(callsign); if (book == null) throw new MslInternalException("No code book found for naval port " + callsign + "."); // Pick a random page and word. final Random r = getRandom(); final int page = r.nextInt(book.getPageCount()) + 1; final int word = r.nextInt(book.getWordCount(page)) + 1; entityAuthData = new NavalPortAuthenticationData(callsign, page, word); } // Return the entity authentication data. return entityAuthData; } /** Entity authentication data. */ private EntityAuthenticationData entityAuthData; /** Naval port callsign. */ private final String callsign; /** Naval port database. */ private final NavalPortDatabase ports; /** MSL crypto context. */ private final ICryptoContext mslCryptoContext; }
2,036
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/util/ConsoleManager.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import kancolle.msg.Message; import kancolle.msg.Message.Type; import com.netflix.msl.MslCryptoException; import com.netflix.msl.msg.ErrorHeader; /** * <p>A thread-safe interactive console manager.</p> * * @author Wesley Miaw <[email protected]> */ public class ConsoleManager extends Thread { /** * <p>Output a message.</p> * * @param author outputting author. * @param message message. */ public void message(final String author, final Message message) { // Output the type followed by any contents or records. final Type type = message.getType(); final StringBuilder text = new StringBuilder(type.toString()); if (type.hasContents()) { text.append(System.lineSeparator() + message.getContents()); } else if (type.hasRecords()) { for (final String record : message.getRecords()) text.append(System.lineSeparator() + record); } out(author, text.toString()); } /** * <p>Output an error header.</p> * * @param author outputting author. * @param error error header. */ public void error(final String author, final ErrorHeader error) { // Extract sender. String sender; try { sender = error.getEntityAuthenticationData().getIdentity(); } catch (final MslCryptoException e) { sender = e.getMessage(); } // Build error string. final String userMessage = error.getUserMessage(); final String text = "Sender[" + sender + "]" + error.getErrorCode() + " (" + error.getInternalCode() + ") " + error.getErrorMessage() + ((userMessage != null) ? " | " + userMessage : ""); // Output error. out(author, text); } /** * <p>Output some text to the console.</p> * * @param author outputting author. * @param text text to output. */ public void out(final String author, final String text) { io.lock(); try { final String s = "[" + author + "] " + text; output.add(s); work.signal(); } finally { io.unlock(); } } /** * <p>Request some text from the console.</p> * * @param author requesting author. * @param text text prompt. * @return the entered text. * @throws InterruptedException if interrupted while waiting for input. */ public String in(final String author, final String text) throws InterruptedException { io.lock(); try { // Prompt for input. prompt = "[" + author + "] " + text + ": "; work.signal(); // Grab captured input. while (input == null) captured.await(); final String entry = input; prompt = null; input = null; return entry; } finally { io.unlock(); } } @Override public void run() { io.lock(); try { while (true) { // Wait for work. while (output.size() == 0 && prompt == null) work.await(); // Dump all queued output. for (final String s : output) System.out.println(s); System.out.flush(); output.clear(); // Prompt for any input. if (prompt != null) { System.out.print(prompt); final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); input = br.readLine(); captured.signal(); } } } catch (final InterruptedException e) { e.printStackTrace(System.err); } catch (final IOException e) { e.printStackTrace(System.err); } finally { io.unlock(); } } /** Queued output. */ private final List<String> output = new ArrayList<String>(); /** Input prompt. */ private String prompt = null; /** Captured input. */ private String input = null; /** I/O lock. */ private final Lock io = new ReentrantLock(); /** Queued output or an input prompt. */ private final Condition work = io.newCondition(); /** Captured input. */ private final Condition captured = io.newCondition(); }
2,037
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/util/KanmusuMslContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.util; import kancolle.crypto.KanColleCryptoContext; import kancolle.entityauth.KanmusuAuthenticationData; import kancolle.entityauth.KanmusuDatabase; import kancolle.entityauth.NavalPortDatabase; import kancolle.userauth.OfficerDatabase; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslInternalException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationData; /** * <p>MSL context for Kanmusu ships.</p> * * @author Wesley Miaw <[email protected]> */ public class KanmusuMslContext extends KanColleMslContext { /** MSL crypto context key derivation secret suffix. */ private static final String KEY_DERIVATION_SECRET = "KanColleKanmusuSecret"; /** * Create a new Kanmusu MSL context for the specified ship. * * @param type the ship type. * @param name the ship name. * @param ships Kanmusu ships database. * @param ports naval ports database. * @param officers officers database. * @throws MslCryptoException if there is an error accessing the entity * authentication data identity. * @throws MslInternalException if the type or name are invalid. */ public KanmusuMslContext(final String type, final String name, final KanmusuDatabase ships, final NavalPortDatabase ports, final OfficerDatabase officers) throws MslCryptoException { super(ships, ports, officers); // Entity authentication data. try { this.entityAuthData = new KanmusuAuthenticationData(type, name); } catch (final IllegalArgumentException e) { throw new MslInternalException("Invalid Kanmusu ship.", e); } // MSL crypto context individualized to this entity. final String identity = entityAuthData.getIdentity(); final String secret = identity + ":" + KEY_DERIVATION_SECRET; this.mslCryptoContext = new KanColleCryptoContext(this, identity, secret); } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getMslCryptoContext() */ @Override public ICryptoContext getMslCryptoContext() throws MslCryptoException { return mslCryptoContext; } /* (non-Javadoc) * @see com.netflix.msl.util.MslContext#getEntityAuthenticationData(com.netflix.msl.util.MslContext.ReauthCode) */ @Override public EntityAuthenticationData getEntityAuthenticationData(final ReauthCode reauthCode) { // We cannot provide new entity authentication data. if (reauthCode == ReauthCode.ENTITYDATA_REAUTH) return null; return entityAuthData; } /** Entity authentication data. */ private final EntityAuthenticationData entityAuthData; /** MSL crypto context. */ private final ICryptoContext mslCryptoContext; }
2,038
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/util/KanColleAuthenticationUtils.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.util; import kancolle.KanColleMslError; import kancolle.entityauth.KanColleEntityAuthenticationScheme; import kancolle.entityauth.KanmusuAuthenticationData; import kancolle.entityauth.KanmusuDatabase; import kancolle.entityauth.NavalPortDatabase; import kancolle.userauth.OfficerDatabase; import kancolle.userauth.OfficerDatabase.Status; import com.netflix.msl.MslError; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.userauth.UserAuthenticationScheme; import com.netflix.msl.util.AuthenticationUtils; /** * <p>KanColle authentication utilities.</p> * * @author Wesley Miaw <[email protected]> */ public class KanColleAuthenticationUtils implements AuthenticationUtils { /** * Create a new KanColle authentication utilities instance with the * provided entity and user databases. * * @param ships Kanmusu ships database. * @param ports naval ports database. * @param officers officer database. */ public KanColleAuthenticationUtils(final KanmusuDatabase ships, final NavalPortDatabase ports, final OfficerDatabase officers) { this.ships = ships; this.ports = ports; this.officers = officers; } /** * If the provided entity identity is a Kanmusu ship then check if it's * authentication has been revoked. A ship is revoked if it is unknown or * has been confirmed destroyed. * * @param identity the Kanmusu ship identity. * @return a {@code MslError} if the identity identifies a Kanmusu ship * that is revoked or {@code null} if it is not revoked or does not * identify a Kanmusu ship. */ public MslError isKanmusuRevoked(final String identity) { // Attempt to reconstruct the authentication data. This provides access // to the ship type and name. final KanmusuAuthenticationData kanmusu; try { kanmusu = new KanmusuAuthenticationData(identity); } catch (final IllegalArgumentException e) { // Not a Kanmusu. Not revoked. return null; } // Only revoke unknown or destroyed ships. final String type = kanmusu.getType(); final String name = kanmusu.getName(); final KanmusuDatabase.Status state = ships.getStatus(type, name); if (state == null) return KanColleMslError.KANMUSU_REVOKED_UNKNOWN; switch (state) { case DESTROYED: return KanColleMslError.KANMUSU_REVOKED_DESTROYED; default: return null; } } /** * Check if the identified naval port's authentication should be revoked. A * naval port is revoked if it is unknown or confirmed destroyed. * * @param callsign the naval port callsign. * @return a {@code MslError} if the naval port identified by the callsign * is revokved or unknown, {@code null} otherwise. */ public MslError isNavalPortRevoked(final String callsign) { // Only revoke unknown or destroyed ports. final NavalPortDatabase.Status state = ports.getStatus(callsign); if (state == null) return KanColleMslError.NAVALPORT_REVOKED_UNKNOWN; switch (state) { case INACTIVE: return KanColleMslError.NAVALPORT_REVOKED_INACTIVE; case DESTROYED: return KanColleMslError.NAVALPORT_REVOKED_DESTROYED; default: return null; } } /** * Check if the specified officer's authentication should be revoked. An * officer is revoked if it is unknown, discharged, court martialed, or * dead. * * @param name the officer name. * @return a {@code MslError} if the officer identified by the given name * is revoked or unknown, {@code null} otherwise. */ public MslError isOfficerRevoked(final String name) { // Revoke unknown or inactive officers. final Status status = officers.getStatus(name); if (status == null) return KanColleMslError.OFFICER_REVOKED_UNKNOWN; switch (status) { case DISCHARGED: return KanColleMslError.OFFICER_REVOKED_DISCHARGED; case COURT_MARTIALED: return KanColleMslError.OFFICER_REVOKED_COURT_MARTIALED; case KIA: return KanColleMslError.OFFICER_REVOKED_KIA; case DECEASED: return KanColleMslError.OFFICER_REVOKED_DECEASED; default: return null; } } /* (non-Javadoc) * @see com.netflix.msl.util.AuthenticationUtils#isEntityRevoked(java.lang.String) */ @Override public boolean isEntityRevoked(final String identity) { // Check for revocation. It may be a ship or a naval port. final MslError kanmusuRevoked = isKanmusuRevoked(identity); if (kanmusuRevoked != null) return true; final MslError navalPortRevoked = isNavalPortRevoked(identity); if (navalPortRevoked != null) return true; return false; } /* (non-Javadoc) * @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.entityauth.EntityAuthenticationScheme) */ @Override public boolean isSchemePermitted(final String identity, final EntityAuthenticationScheme scheme) { // Attempt to reconstruct the authentication data. This provides access // to the ship type and name. try { new KanmusuAuthenticationData(identity); return (KanColleEntityAuthenticationScheme.KANMUSU.equals(scheme)); } catch (final IllegalArgumentException e) { // Not a Kanmusu. A ship. Fall through. } return KanColleEntityAuthenticationScheme.NAVAL_PORT.equals(scheme); } /* (non-Javadoc) * @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.userauth.UserAuthenticationScheme) */ @Override public boolean isSchemePermitted(final String identity, final UserAuthenticationScheme scheme) { // All configured user authentication schemes are permitted. return true; } /* (non-Javadoc) * @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.tokens.MslUser, com.netflix.msl.userauth.UserAuthenticationScheme) */ @Override public boolean isSchemePermitted(final String identity, final MslUser user, final UserAuthenticationScheme scheme) { // All configured user authentication schemes are permitted. return true; } /* (non-Javadoc) * @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.keyx.KeyExchangeScheme) */ @Override public boolean isSchemePermitted(final String identity, final KeyExchangeScheme scheme) { // All configured exchange schemes are permitted. return true; } /** Kanmusu ships. */ private final KanmusuDatabase ships; /** Naval ports. */ private final NavalPortDatabase ports; /** Officers. */ private final OfficerDatabase officers; }
2,039
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/msg/Message.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.msg; import java.util.Collections; import java.util.List; /** * <p>A message is identified by a type and some contents. Some types of * messages have no contents (e.g. ping) while other types may contain multiple * records for the contents (e.g. report).</p> * * @author Wesley Miaw <[email protected]> */ public class Message { /** * Message type strings. */ public static enum Type { /** Acknowledgement message identifier. */ ACK("ACK", false, false), /** Ping message identifier. */ PING("PING", false, false), /** Report message identifier. */ REPORT("REPORT", false, true), /** Critical report message identifier. */ CRITICAL("CRITICAL", false, true), /** Requesting orders message identifier. */ ORDER_REQUEST("REQUESTING ORDERS", false, false), /** Issued orders message identifier. */ ORDER_RESPONSE("ISSUED ORDERS", true, false), /** Error message identifier. */ ERROR("ERROR", true, false); ; /** * Create a new message type with the specified properties. * * @param s the string representation. * @param contents true if the message type has contents. * @param records true if the message type has records. */ private Type(final String s, final boolean contents, final boolean records) { this.s = s; this.contents = contents; this.records = records; } /** * @return true if the message type has contents. */ public boolean hasContents() { return contents; } /** * @return true if the message type has records. */ public boolean hasRecords() { return records; } /** * @return the string representation of this type. */ public String toString() { return s; } /** Message type string representation. */ private final String s; /** Message type has contents. */ private final boolean contents; /** Message type has records. */ private final boolean records; } /** * Create a new message of the specified type. * * @param type message type. * @throws IllegalArgumentException if the type indicates the message must * have contents or records. */ Message(final Type type) { if (type.hasContents() || type.hasRecords()) throw new IllegalArgumentException("Type " + type + " must have contents or records."); this.type = type; this.contents = null; this.records = null; } /** * Create a new message with the specified type and contents. Records will * be {@code null}. * * @param type message type. * @param contents message contents. * @throws IllegalArgumentException if the type indicates the message * should not have contents. */ Message(final Type type, final String contents) { if (!type.hasContents()) throw new IllegalArgumentException("Type " + type + " does not have contents."); this.type = type; this.contents = contents; this.records = null; } /** * Create a new message with the specified type and records. Contents will * be {@code null]. * * @param type message type. * @param records message records. May be empty. * @throws IllegalArgumentException if the type indicates the message * should not have records. */ Message(final Type type, final List<String> records) { if (!type.hasRecords()) throw new IllegalArgumentException("Type " + type + " must does not have records."); this.type = type; this.contents = null; this.records = Collections.unmodifiableList(records); } /** * @return the message type. */ public Type getType() { return type; } /** * Return the message contents for issued orders. * * @return the message contents, which may be the empty string, or * {@code null} if this type of message does not contain records. */ public String getContents() { return contents; } /** * Return the message records for reports and critical reports. * * @return the message records, which may be empty, or {@code null} if this * type of message does not contain records. */ public List<String> getRecords() { return records; } /** Type. */ private final Type type; /** Contents. */ private final String contents; /** Records. */ private final List<String> records; }
2,040
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/msg/AckMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.msg; import java.io.IOException; import com.netflix.msl.msg.MessageOutputStream; /** * <p>A simple message acknowledgement sent in response to various requests.</p> * * @author Wesley Miaw <[email protected]> */ public class AckMessageContext extends KanColleMessageContext { public AckMessageContext() { super(null, null, null); } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#write(com.netflix.msl.msg.MessageOutputStream) */ @Override public void write(final MessageOutputStream output) throws IOException { MessageProcessor.acknowledge(output); } }
2,041
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/msg/OrderResponseMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.msg; import java.io.IOException; import com.netflix.msl.msg.MessageOutputStream; /** * <p>Issue orders.</p> * * @author Wesley Miaw <[email protected]> */ public class OrderResponseMessageContext extends KanColleMessageContext { /** * <p>Create a new issued orders response message with the provided * orders.</p> * * @param orders the orders. */ public OrderResponseMessageContext(final String orders) { super(null, null, null); this.orders = orders; } @Override public boolean isNonReplayable() { return true; } @Override public void write(final MessageOutputStream output) throws IOException { MessageProcessor.issueOrders(output, orders); } /** Orders. */ private final String orders; }
2,042
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/msg/KanColleMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.msg; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import kancolle.keyx.DiffieHellmanManager; import kancolle.userauth.OfficerAuthenticationData; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.keyx.KeyRequestData; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MessageDebugContext; import com.netflix.msl.msg.MessageServiceTokenBuilder; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.userauth.UserAuthenticationData; /** * <p>Base message context with default security properties.</p> * * <p>By default messages are encrypted and integrity-protected, but replayable * and not requesting tokens. No recipient is specified.</p> * * @author Wesley Miaw <[email protected]> */ public abstract class KanColleMessageContext implements MessageContext { /** * <p>Create a new KanColle message context.</p> * * <p>If the officer name is null then the message will not be associated * with a user.</p> * * <p>If the key exchange manager is null then key request data will not be * included.</p> * * @param name reporting officer name. May be null. * @param fingerprint reporting officer fingerprint. May be null if the * officer is already authenticated (a user ID token exists). * @param keyxManager key exchange manager. May be null. */ public KanColleMessageContext(final String name, final byte[] fingerprint, final DiffieHellmanManager keyxManager) { this.name = name; this.fingerprint = fingerprint; this.keyxManager = keyxManager; } /** * <p>No service token crypto contexts are provided.</p> * * @return the empty map. * @see com.netflix.msl.msg.MessageContext#getCryptoContexts() */ @Override public Map<String, ICryptoContext> getCryptoContexts() { return Collections.emptyMap(); } /** * <p>No recipient is specified.</p> * * @return {@code null}. * @see com.netflix.msl.msg.MessageContext#getRemoteEntityIdentity() */ @Override public String getRemoteEntityIdentity() { return null; } /** * <p>Messages are encrypted.</p> * * @return {@code true}. * @see com.netflix.msl.msg.MessageContext#isEncrypted() */ @Override public boolean isEncrypted() { return true; } /** * <p>Messages are integrity-protected.</p> * * @return {@code true}. * @see com.netflix.msl.msg.MessageContext#isIntegrityProtected() */ @Override public boolean isIntegrityProtected() { return true; } /** * <p>Messages are replayable.</p> * * @return {@code false}. * @see com.netflix.msl.msg.MessageContext#isNonReplayable() */ @Override public boolean isNonReplayable() { return false; } /** * <p>Messages are not requesting tokens.</p> * * @return {@code false}. * @see com.netflix.msl.msg.MessageContext#isRequestingTokens() */ @Override public boolean isRequestingTokens() { return false; } /** * <p>Messages may be associated with a user depending on what was passed * in at construction.</p> * * @return the officer name or {@code null} if the message is not * associated with a user. * @see com.netflix.msl.msg.MessageContext#getUserId() */ @Override public String getUserId() { return name; } /** * <p>If an officer was specified at construction, returns user * authentication data if required is {@code true} and a fingerprint was * also provided at construction. Otherwise {@code null} is returned.</p> * * @return the user authentication data or {@code null}. * @see com.netflix.msl.msg.MessageContext#getUserAuthData(com.netflix.msl.msg.MessageContext.ReauthCode, boolean, boolean) */ @Override public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required) { // If no officer is specified then return null. if (name == null) return null; // If a reauth code is provided then return null indicating failure; // we don't have a different officer. if (reauthCode != null) return null; // If required and we have the fingerprint then return the user // authentication data. if (required && fingerprint != null) return new OfficerAuthenticationData(name, fingerprint); // Otherwise don't return the user authentication data. Maybe a user ID // token exists. return null; } /** * <p>Messages do not have a user assigned.</p> * * @return {@code null}. * @see com.netflix.msl.msg.MessageContext#getUser() */ @Override public MslUser getUser() { return null; } /** * <p>Messages may include key request data if a key exchange manager was * provided at construction.</p> * * @return the key request data, which may be the empty set. * @see com.netflix.msl.msg.MessageContext#getKeyRequestData() */ @Override public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException { // If a key exchange manager was provided then return key request data. if (keyxManager != null) return new HashSet<KeyRequestData>(Arrays.asList(keyxManager.getRequestData())); return Collections.emptySet(); } /** * <p>Service tokens are not modified.</p> * * @see com.netflix.msl.msg.MessageContext#updateServiceTokens(com.netflix.msl.msg.MessageServiceTokenBuilder, boolean) */ @Override public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) { } /** * <p>No message debug context is provided.</p> * * @return {@code null}. * @see com.netflix.msl.msg.MessageContext#getDebugContext() */ @Override public MessageDebugContext getDebugContext() { return null; } /** Reporting officer name. */ private final String name; /** Reporting officer fingerprint. */ private final byte[] fingerprint; /** Key exchange manager. */ private final DiffieHellmanManager keyxManager; }
2,043
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/msg/OrderRequestMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.msg; import java.io.IOException; import kancolle.keyx.DiffieHellmanManager; import com.netflix.msl.msg.MessageOutputStream; /** * <p>Request orders.</p> * * @author Wesley Miaw <[email protected]> */ public class OrderRequestMessageContext extends KanColleMessageContext { /** * Create a new order request message sent by the specified officer. * * @param name reporting officer name. * @param fingerprint reporting officer fingerprint. May be null if the * officer is already authenticated (a user ID token exists). * @param keyxManager key exchange manager. */ public OrderRequestMessageContext(final String name, final byte[] fingerprint, final DiffieHellmanManager keyxManager) { super(name, fingerprint, keyxManager); if (name == null) throw new NullPointerException("Reports must specify an officer name."); } @Override public boolean isEncrypted() { return false; } @Override public void write(final MessageOutputStream output) throws IOException { // TODO Auto-generated method stub } }
2,044
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/msg/CriticalMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.msg; import java.io.IOException; import java.util.List; import kancolle.keyx.DiffieHellmanManager; import com.netflix.msl.msg.MessageOutputStream; /** * <p>Send a critical report to a specific port.</p> * * @author Wesley Miaw <[email protected]> */ public class CriticalMessageContext extends ReportMessageContext { /** * Create a new critical report message sent by the specified officer. * * @param name reporting officer name. * @param fingerprint reporting officer fingerprint. May be null if the * officer is already authenticated (a user ID token exists). * @param callsign the intended naval port recipient. * @param records report records. * @param keyxManager key exchange manager. */ public CriticalMessageContext(final String name, final byte[] fingerprint, final String callsign, final List<String> records, final DiffieHellmanManager keyxManager) { super(name, fingerprint, records, keyxManager); if (callsign == null) throw new NullPointerException("Critical reports must specify a naval port recipient."); this.callsign = callsign; this.records = records; } @Override public String getRemoteEntityIdentity() { return callsign; } @Override public boolean isNonReplayable() { return true; } @Override public void write(final MessageOutputStream output) throws IOException { MessageProcessor.critical(output, records); } /** Recipient naval port callsign. */ private final String callsign; /** Report records. */ private final List<String> records; }
2,045
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/msg/ReportMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.msg; import java.io.IOException; import java.util.List; import kancolle.keyx.DiffieHellmanManager; import com.netflix.msl.msg.MessageOutputStream; /** * <p>Report the accumulated ship's log to a port.</p> * * @author Wesley Miaw <[email protected]> */ public class ReportMessageContext extends KanColleMessageContext { /** * Create a new report message sent by the specified officer. * * @param name reporting officer name. * @param fingerprint reporting officer fingerprint. May be null if the * officer is already authenticated (a user ID token exists). * @param records report records. * @param keyxManager key exchange manager. */ public ReportMessageContext(final String name, final byte[] fingerprint, final List<String> records, final DiffieHellmanManager keyxManager) { super(name, fingerprint, keyxManager); if (name == null) throw new NullPointerException("Reports must specify an officer name."); this.records = records; } @Override public void write(final MessageOutputStream output) throws IOException { MessageProcessor.report(output, records); } /** Report records. */ private final List<String> records; }
2,046
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/msg/ReceiveMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.msg; import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.Set; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.keyx.KeyRequestData; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MessageDebugContext; import com.netflix.msl.msg.MessageOutputStream; import com.netflix.msl.msg.MessageServiceTokenBuilder; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.userauth.UserAuthenticationData; /** * <p>The receive message context is used when receiving messages. Since no * data will be returned this context does not specify any security * requirements.</p> * * @author Wesley Miaw <[email protected]> */ public class ReceiveMessageContext implements MessageContext { @Override public Map<String, ICryptoContext> getCryptoContexts() { return Collections.emptyMap(); } @Override public String getRemoteEntityIdentity() { return null; } @Override public boolean isEncrypted() { return false; } @Override public boolean isIntegrityProtected() { return false; } @Override public boolean isNonReplayable() { return false; } @Override public boolean isRequestingTokens() { return false; } @Override public String getUserId() { return null; } @Override public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required) { return null; } @Override public MslUser getUser() { return null; } @Override public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException { return Collections.emptySet(); } @Override public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) { } @Override public void write(final MessageOutputStream output) throws IOException { output.close(); } @Override public MessageDebugContext getDebugContext() { return null; } }
2,047
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/msg/MessageProcessor.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.msg; import java.io.IOException; import java.util.ArrayList; import java.util.List; import kancolle.KanColleMslError; import com.netflix.msl.MslConstants; import com.netflix.msl.MslMessageException; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.msg.MessageOutputStream; /** * <p>Read and write application messages.</p> * * @author Wesley Miaw <[email protected]> */ public class MessageProcessor { /** Newline character. */ private static final String NEWLINE = System.lineSeparator(); /** Space character. */ private static final char SPACE = ' '; /** * <p>Acknowledgements are identifed by the string "ACK".</p> * * <p>The message output stream is closed.</p> * * @param output message output stream. * @throws IOException if there is an error writing the message. */ public static void acknowledge(final MessageOutputStream output) throws IOException { output.write(Message.Type.ACK.toString().getBytes(MslConstants.DEFAULT_CHARSET)); output.close(); } /** * <p>Pings are identified by the string "PING".</p> * * <p>The message output stream is closed.</p> * * @param output message output stream. * @throws IOException if there is an error writing the message. */ public static void ping(final MessageOutputStream output) throws IOException { output.write(Message.Type.PING.toString().getBytes(MslConstants.DEFAULT_CHARSET)); output.close(); } /** * <p>Reports are identified by the string "REPORT" followed by the number of * records. Each record in the log is sent on its own line prefixed by the line * number. e.g. * <pre> * REPORT 2 * 1: Set heading 80&deg; at 15 knots. * 2: Sighted potential enemy on the horizon and slowed to 10 knots. * </pre></p> * * <p>The message output stream is closed.</p> * * @param output message output stream. * @param records report records. * @throws IOException if there is an error writing the message. */ public static void report(final MessageOutputStream output, final List<String> records) throws IOException { final String header = Message.Type.REPORT + Integer.toString(records.size()) + NEWLINE; output.write(header.getBytes(MslConstants.DEFAULT_CHARSET)); for (int i = 0; i < records.size(); ++i) { final String record = Integer.toString(i+1) + ": " + records.get(i) + NEWLINE; final byte[] b = record.getBytes(MslConstants.DEFAULT_CHARSET); output.write(b); } output.close(); } /** * <p>Critical reports are identified by the string "CRITICAL" followed by the * number of records. Each record in the log is sent on its own line prefixed * by the line number. e.g. * <pre> * CRITICAL 3 * 1: Engaged enemy at 0746 hours. * 2: Enemy destroyed at 0813 hours. * 3: 12 casualties: 3 dead, 8 wounded, 1 missing. * </pre></p> * * <p>The message output stream is closed.</p> * * @param output message output stream. * @param records critical report records. * @throws IOException if there is an error writing the message. */ public static void critical(final MessageOutputStream output, final List<String> records) throws IOException { final String header = Message.Type.CRITICAL + Integer.toString(records.size()) + NEWLINE; output.write(header.getBytes(MslConstants.DEFAULT_CHARSET)); for (int i = 0; i < records.size(); ++i) { final String record = Integer.toString(i+1) + ": " + records.get(i) + NEWLINE; final byte[] b = record.getBytes(MslConstants.DEFAULT_CHARSET); output.write(b); } output.close(); } /** * <p>Order requests are identified by the string "REQUESTING ORDERS".</p> * * <p>The message output stream is closed.</p> * * @param output message output stream. * @throws IOException if there is an error writing the message. */ public static void requestOrders(final MessageOutputStream output) throws IOException { output.write(Message.Type.ORDER_REQUEST.toString().getBytes(MslConstants.DEFAULT_CHARSET)); output.close(); } /** * <p>Issued orders are identified by the string "ISSUED ORDERS" followed * by the orders. e.g * <pre> * ISSUED ORDERS * Proceed to sector 17 and patrol until further orders are received. * </pre></p> * * <p>The message output stream is closed.</p> * * @param output message output stream. * @param orders the orders. * @throws IOException if there is an error writing the message. */ public static void issueOrders(final MessageOutputStream output, final String orders) throws IOException { final String header = Message.Type.ORDER_RESPONSE + NEWLINE; output.write(header.getBytes(MslConstants.DEFAULT_CHARSET)); output.write(orders.getBytes(MslConstants.DEFAULT_CHARSET)); output.close(); } /** * <p>Errors are identified by the string "ERROR" followed by an error * message.</p> * * <p>The message output stream is closed.</p> * * @param output message output stream. * @param message the error message. * @throws IOException if there is an error writing the message. */ public static void error(final MessageOutputStream output, final String message) throws IOException { final String header = Message.Type.ERROR + NEWLINE; output.write(header.getBytes(MslConstants.DEFAULT_CHARSET)); output.write(message.getBytes(MslConstants.DEFAULT_CHARSET)); output.close(); } /** * <p>Reads a message off the provided message input stream.</p> * * @param in message input stream. * @return the parsed message. * @throws MslMessageException if the message type is not recognized. * @throws IOException if there is an error reading the message. */ public static Message parse(final MessageInputStream in) throws MslMessageException, IOException { // Read everything off the input stream. final StringBuffer messageBuffer = new StringBuffer(); while (true) { final byte[] buffer = new byte[4096]; final int bytesRead = in.read(buffer); if (bytesRead == -1) { in.close(); break; } messageBuffer.append(new String(buffer, 0, bytesRead, MslConstants.DEFAULT_CHARSET)); } final String message = messageBuffer.toString(); // Figure out the message type. Message.Type type = null; for (final Message.Type t : Message.Type.values()) { if (message.startsWith(t.toString())) { type = t; break; } } if (type == null) throw new MslMessageException(KanColleMslError.MSG_TYPE_UNKNOWN); // Parse any contents. if (type.hasContents()) { // Split on the first line. final int newlineIndex = message.indexOf(NEWLINE); final String contents = message.substring(newlineIndex+1); return new Message(type, contents); } // Parse any records. if (type.hasRecords()) { // Split on newlines. final String[] lines = message.split(NEWLINE); // The number of records should appear after the type string. final int recordsOffset = type.toString().length() + 1; final String countString = lines[0].substring(recordsOffset); final int count; try { count = Integer.parseInt(countString); } catch (final NumberFormatException e) { throw new MslMessageException(KanColleMslError.MSG_RECORD_COUNT_INVALID, countString, e); } // Make sure we have enough records. Extra records are discarded. if (lines.length - 1 < count) throw new MslMessageException(KanColleMslError.MSG_RECORDS_TRUNCATED, "expected " + count + "; received " + (lines.length - 1)); // Read each record. final List<String> records = new ArrayList<String>(); for (int i = 1; i <= count; ++i) { // Grab the record number. final String record = lines[i]; final int spaceIndex = record.indexOf(SPACE); final int number; try { number = Integer.parseInt(record.substring(0, spaceIndex)); } catch (final NumberFormatException e) { throw new MslMessageException(KanColleMslError.MSG_RECORD_NUMBER_MISSING, Integer.toString(i), e); } // Make sure the record number is correct. if (number != i) throw new MslMessageException(KanColleMslError.MSG_RECORD_NUMBER_MISMATCH, "expected " + i + "; found " + number); // Add the record. records.add(record); } // Return the message. return new Message(type, records); } // Return messages without contents or records. return new Message(type); } }
2,048
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/msg/ErrorMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.msg; import java.io.IOException; import com.netflix.msl.msg.MessageOutputStream; /** * <p>An error message sent in response to failed requests.</p> * * @author Wesley Miaw <[email protected]> */ public class ErrorMessageContext extends KanColleMessageContext { /** * <p>Create a new error message context.</p> * * @param message the error message. */ public ErrorMessageContext(final String message) { super(null, null, null); this.message = message; } /* (non-Javadoc) * @see com.netflix.msl.msg.MessageContext#write(com.netflix.msl.msg.MessageOutputStream) */ @Override public void write(final MessageOutputStream output) throws IOException { MessageProcessor.error(output, message); } /** Error message. */ private final String message; }
2,049
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/msg/PingMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.msg; import java.io.IOException; import com.netflix.msl.msg.MessageOutputStream; /** * <p>Pings are periodically sent from Kanmusu to naval ports.</p> * * @author Wesley Miaw <[email protected]> */ public class PingMessageContext extends KanColleMessageContext { /** * <p>Create a new ping message context.</p> */ public PingMessageContext() { super(null, null, null); } @Override public boolean isEncrypted() { return false; } @Override public void write(final MessageOutputStream output) throws IOException { MessageProcessor.ping(output); } }
2,050
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/keyx/KanColleKeyxComparator.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.keyx; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import com.netflix.msl.keyx.KeyExchangeFactory; import com.netflix.msl.keyx.KeyExchangeScheme; /** * Key exchange factory comparator. * * @author Wesley Miaw <[email protected]> */ public class KanColleKeyxComparator implements Comparator<KeyExchangeFactory> { /** Scheme priorities. Lower values are higher priority. */ private final Map<KeyExchangeScheme,Integer> schemePriorities = new HashMap<KeyExchangeScheme,Integer>(); /** * Create a new key exchange factory comparator. */ public KanColleKeyxComparator() { schemePriorities.put(KeyExchangeScheme.DIFFIE_HELLMAN, 0); schemePriorities.put(KeyExchangeScheme.ASYMMETRIC_WRAPPED, 1); } /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(KeyExchangeFactory a, KeyExchangeFactory b) { final KeyExchangeScheme schemeA = a.getScheme(); final KeyExchangeScheme schemeB = b.getScheme(); final Integer priorityA = schemePriorities.get(schemeA); final Integer priorityB = schemePriorities.get(schemeB); return priorityA.compareTo(priorityB); } }
2,051
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/keyx/DiffieHellmanManager.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.keyx; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import com.netflix.msl.MslInternalException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.keyx.DiffieHellmanExchange.RequestData; import com.netflix.msl.keyx.DiffieHellmanParameters; /** * <p>Shared Diffie-Hellman instance to minimize key exchange overhead. New key * request data should be generated after every successful key exchange.</p> * * <p>This class is thread-safe.</p> * * @author Wesley Miaw <[email protected]> */ public class DiffieHellmanManager { /** * @param params Diffie-Hellman parameters. * @param paramId the ID of the Diffie-Hellman parameters to use. */ public DiffieHellmanManager(DiffieHellmanParameters params, final String paramId) { this.params = params; this.paramId = paramId; } /** * <p>Return the current Diffie-Hellman key exchange request data. If no * request data exists new data is generated.</p> * * @return the Diffie-Hellman request data. * @throws MslKeyExchangeException if there is an error accessing the * Diffie-Hellman parameters. * @see #clearRequest() */ public synchronized RequestData getRequestData() throws MslKeyExchangeException { // Generate new request data if necessary. if (request == null) { final DHParameterSpec paramSpec = params.getParameterSpec(paramId); final KeyPairGenerator generator; try { generator = KeyPairGenerator.getInstance("DH"); generator.initialize(paramSpec); } catch (final NoSuchAlgorithmException e) { throw new MslInternalException("Diffie-Hellman algorithm not found.", e); } catch (final InvalidAlgorithmParameterException e) { throw new MslInternalException("Diffie-Hellman algorithm parameters rejected by Diffie-Hellman key agreement.", e); } final KeyPair requestKeyPair = generator.generateKeyPair(); final BigInteger publicKey = ((DHPublicKey)requestKeyPair.getPublic()).getY(); final DHPrivateKey privateKey = (DHPrivateKey)requestKeyPair.getPrivate(); request = new RequestData(KanColleDiffieHellmanParameters.PARAM_ID, publicKey, privateKey); } return request; } /** * <p>Clear the current Diffie-Hellman key exchange request data. The next * call to {@link #getRequestData()} will generate new request data.</p> * * @see #getRequestData() */ public synchronized void clearRequest() { request = null; } /** The Diffie-Hellman parameters. */ private final DiffieHellmanParameters params; /** The Diffie-Hellman parameters ID to use. */ private final String paramId; /** The current request data. */ private RequestData request; }
2,052
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/keyx/KanColleDiffieHellmanParameters.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.keyx; import java.math.BigInteger; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.crypto.spec.DHParameterSpec; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.keyx.DiffieHellmanParameters; /** * <p>KanColle Diffie-Hellman parameters.</p> * * <p>Currently only one set of parameters is supported, and this is hard-coded * into the class.</p> * * @author Wesley Miaw <[email protected]> */ public class KanColleDiffieHellmanParameters implements DiffieHellmanParameters { /** Default parameters. */ private static BigInteger p = new BigInteger("C2048E076B268761DB1427BA3AD98473D32B0ABDEE98C0827923426F294EDA3392BF0032A1D8092055B58BAA07586A7D3E271C39A8C891F5CEEA4DEBDFA6B023", 16); private static BigInteger g = new BigInteger("02", 16); /** Diffie-Hellman parameter ID. */ public static final String PARAM_ID = "KanColle"; /** Diffie-Hellman parameter specification. */ private static final DHParameterSpec paramSpec = new DHParameterSpec(p, g); /* (non-Javadoc) * @see com.netflix.msl.keyx.DiffieHellmanParameters#getParameterSpecs() */ @Override public Map<String,DHParameterSpec> getParameterSpecs() throws MslKeyExchangeException { final Map<String,DHParameterSpec> params = new HashMap<String,DHParameterSpec>(); params.put(PARAM_ID, paramSpec); return Collections.unmodifiableMap(params); } /* (non-Javadoc) * @see com.netflix.msl.keyx.DiffieHellmanParameters#getParameterSpec(java.lang.String) */ @Override public DHParameterSpec getParameterSpec(final String id) throws MslKeyExchangeException { if (PARAM_ID.equals(id)) return paramSpec; return null; } }
2,053
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/userauth/KanColleUserAuthenticationScheme.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.userauth; import com.netflix.msl.userauth.UserAuthenticationScheme; /** * <p>KanColle user authentication schemes.</p> * * @author Wesley Miaw <[email protected]> */ public class KanColleUserAuthenticationScheme extends UserAuthenticationScheme { /** Officer entity authentication scheme. */ public static final UserAuthenticationScheme OFFICER = new KanColleUserAuthenticationScheme("OFFICER"); /** * Define a KanColle user authentication scheme with the specified name. * * @param name the user authentication scheme name. */ protected KanColleUserAuthenticationScheme(final String name) { super(name); } }
2,054
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/userauth/OfficerDatabase.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.userauth; /** * Provides access to officer data. * * @author Wesley Miaw <[email protected]> */ public interface OfficerDatabase { /** Officer status. */ public static enum Status { /** Active. */ ACTIVE, /** Honorably discharged. */ DISCHARGED, /** Court martialed. */ COURT_MARTIALED, /** Presumed prisoner of war. */ POW, /** Presumed missing in action. */ MIA, /** Confirmed killed in action. */ KIA, /** Confirmed deceased. */ DECEASED, } /** * Return the current status of the specified officer. * * @param name the officer name. * @return the officer's current status or {@code null} if the officer * is not recognized. */ public Status getStatus(final String name); /** * Return the fingerprint SHA-256 hash of the named officer. * * @param name officer name. * @return the fingerprint hash or {@code null} if the officer name is * not recognized. */ public byte[] getFingerprint(final String name); }
2,055
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/userauth/SimpleOfficerDatabase.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.userauth; import java.util.HashMap; import java.util.Map; /** * <p>A simple in-memory officer database.</p> * * @author Wesley Miaw <[email protected]> */ public class SimpleOfficerDatabase implements OfficerDatabase { /** * <p>Create a new simple officer database instance that is unaware of any * existing officers.</p> */ public SimpleOfficerDatabase() { } /** * <p>Set the officer data. This adds the officer if previously * unknown.</p> * * @param name officer name. * @param state officer state. */ public void setOfficer(final String name, final Status state, final byte[] fingerprint) { if (state == null) throw new IllegalArgumentException("Officer state cannot be null."); if (fingerprint == null) throw new IllegalArgumentException("Officer fingerprint cannot be null."); states.put(name, state); fingerprints.put(name, fingerprint); } /** * <p>Set the officer state. The officer must already be known.</p> * * @param name officer name. * @param state officer state. * @throws IllegalStateException if the ship is not known. */ public void setState(final String name, final Status state) { if (state == null) throw new IllegalArgumentException("Officer state cannot be null."); if (!states.containsKey(name)) throw new IllegalStateException("Officer " + name + " is not known."); states.put(name, state); } /* (non-Javadoc) * @see kancolle.userauth.OfficerDatabase#getStatus(java.lang.String) */ @Override public Status getStatus(final String name) { return states.get(name); } @Override public byte[] getFingerprint(final String name) { return fingerprints.get(name); } /** Officer states by name. */ private final Map<String,Status> states = new HashMap<String,Status>(); /** Officer fingerprints by name. */ private final Map<String,byte[]> fingerprints = new HashMap<String,byte[]>(); }
2,056
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/userauth/OfficerAuthenticationData.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.userauth; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslError; import com.netflix.msl.io.MslEncoderException; import com.netflix.msl.io.MslEncoderFactory; import com.netflix.msl.io.MslEncoderFormat; import com.netflix.msl.io.MslObject; import com.netflix.msl.userauth.UserAuthenticationData; /** * <p>Officers are identified by their name and fingerprint hash.</p> * * <p> * {@code { * "#mandatory" : [ "name", "fingerprint" ], * "name" : "string", * "fingerprint" : "binary" * }} where: * <ul> * <li>{@code name} is the officer's name</li> * <li>{@code fingerprint} is the SHA-256 hash of the officer's fingerprint</li> * </ul></p> * * @author Wesley Miaw <[email protected]> */ public class OfficerAuthenticationData extends UserAuthenticationData { /** Key name. */ private static final String KEY_NAME = "name"; /** Key fingerprint hash. */ private static final String KEY_FINGERPRINT = "fingerprint"; /** * <p>Create a new officer authentication data instance with the given name * and fingerprint SHA-256 hash.</p> * * @param name the officer's name. * @param fingerprint the SHA-256 hash of the officer's fingerprint. */ public OfficerAuthenticationData(final String name, final byte[] fingerprint) { super(KanColleUserAuthenticationScheme.OFFICER); this.name = name; this.fingerprint = fingerprint; } /** * Construct a new officer authentication data instance from the provided * MSL object. * * @param officerMo the authentication data MSL object. * @throws MslEncodingException if there is an error parsing the user * authentication data. */ public OfficerAuthenticationData(final MslObject officerMo) throws MslEncodingException { super(KanColleUserAuthenticationScheme.OFFICER); try { this.name = officerMo.getString(KEY_NAME); this.fingerprint = officerMo.getBytes(KEY_FINGERPRINT); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "officer authdata " + officerMo.toString(), e); } } /** * @return the officer's name. */ public String getName() { return name; } /** * @return the SHA-256 hash of the officer's fingerprint. */ public byte[] getFingerprint() { return fingerprint; } /* (non-Javadoc) * @see com.netflix.msl.userauth.UserAuthenticationData#getAuthData(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat) */ @Override public MslObject getAuthData(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException { final MslObject mo = encoder.createObject(); mo.put(KEY_NAME, name); mo.put(KEY_FINGERPRINT, fingerprint); return mo; } /** Officer name. */ private final String name; /** Fingerprint hash. */ private final byte[] fingerprint; }
2,057
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/userauth/OfficerAuthenticationFactory.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.userauth; import java.util.Arrays; import kancolle.KanColleMslError; import kancolle.userauth.OfficerDatabase.Status; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslError; import com.netflix.msl.MslInternalException; import com.netflix.msl.MslUserAuthException; import com.netflix.msl.io.MslObject; import com.netflix.msl.tokens.MasterToken; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.tokens.UserIdToken; import com.netflix.msl.userauth.UserAuthenticationData; import com.netflix.msl.userauth.UserAuthenticationFactory; import com.netflix.msl.util.MslContext; /** * <p>Each officer has an associated fingerprint SHA-256 hash that is used to * authenticate the officer.</p> * * @author Wesley Miaw <[email protected]> */ public class OfficerAuthenticationFactory extends UserAuthenticationFactory { /** * <p>Create a new officer authentication factory with the given officer * database.</p> * * @param officers the officer database. */ public OfficerAuthenticationFactory(final OfficerDatabase officers) { super(KanColleUserAuthenticationScheme.OFFICER); this.officers = officers; } /* (non-Javadoc) * @see com.netflix.msl.userauth.UserAuthenticationFactory#createData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject) */ @Override public UserAuthenticationData createData(final MslContext ctx, final MasterToken masterToken, final MslObject userAuthMo) throws MslEncodingException { return new OfficerAuthenticationData(userAuthMo); } /* (non-Javadoc) * @see com.netflix.msl.userauth.UserAuthenticationFactory#authenticate(com.netflix.msl.util.MslContext, java.lang.String, com.netflix.msl.userauth.UserAuthenticationData, com.netflix.msl.tokens.UserIdToken) */ @Override public MslUser authenticate(final MslContext ctx, final String identity, final UserAuthenticationData data, final UserIdToken userIdToken) throws MslUserAuthException { // Make sure we have the right kind of user authentication data. if (!(data instanceof OfficerAuthenticationData)) throw new MslInternalException("Incorrect authentication data type " + data.getClass().getName() + "."); final OfficerAuthenticationData oad = (OfficerAuthenticationData)data; // Check the officer status. final String name = oad.getName(); final Status state = officers.getStatus(name); if (state == null) throw new MslUserAuthException(KanColleMslError.OFFICER_NOT_FOUND).setUserAuthenticationData(oad); switch (state) { case DISCHARGED: throw new MslUserAuthException(KanColleMslError.USERAUTH_OFFICER_DISCHARGED).setUserAuthenticationData(oad); case COURT_MARTIALED: throw new MslUserAuthException(KanColleMslError.USERAUTH_OFFICER_COURT_MARTIALED).setUserAuthenticationData(oad); case KIA: throw new MslUserAuthException(KanColleMslError.USERAUTH_OFFICER_KIA).setUserAuthenticationData(oad); case DECEASED: throw new MslUserAuthException(KanColleMslError.USERAUTH_OFFICER_DECEASED).setUserAuthenticationData(oad); default: break; } // Verify the fingerprint. final byte[] fingerprint = oad.getFingerprint(); final byte[] expectedFingerprint = officers.getFingerprint(name); if (expectedFingerprint == null || !Arrays.equals(fingerprint, expectedFingerprint)) throw new MslUserAuthException(KanColleMslError.OFFICER_FINGERPRINT_INCORRECT).setUserAuthenticationData(oad); final MslUser user = new Officer(name); // If a user ID token was provided validate the user identities. if (userIdToken != null) { final MslUser uitUser = userIdToken.getUser(); if (!user.equals(uitUser)) throw new MslUserAuthException(MslError.USERIDTOKEN_USERAUTH_DATA_MISMATCH, "uad user " + user + "; uit user " + uitUser); } // Return the user. return user; } /** Officer database. */ private final OfficerDatabase officers; }
2,058
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/userauth/Officer.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.userauth; import com.netflix.msl.tokens.MslUser; /** * <p>An officer is identified by a name.</p> * * @author Wesley Miaw <[email protected]> */ public class Officer implements MslUser { /** * Create an officer with the given name. * * @param name officer name. */ public Officer(final String name) { this.name = name; } /** * @return the officer name. */ public String getName() { return name; } /** * @return the officer name. * @see com.netflix.msl.tokens.MslUser#getEncoded() */ @Override public String getEncoded() { return name; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return name.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (obj == this) return true; if (!(obj instanceof Officer)) return false; final Officer that = (Officer)obj; return this.name.equals(that.name); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return name; } /** Officer name. */ private final String name; }
2,059
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/tokens/KanColleTokenFactory.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.tokens; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.crypto.SecretKey; import kancolle.userauth.Officer; import kancolle.util.KanColleAuthenticationUtils; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslError; import com.netflix.msl.MslException; import com.netflix.msl.MslInternalException; import com.netflix.msl.MslMasterTokenException; import com.netflix.msl.MslUserIdTokenException; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.io.MslEncoderException; import com.netflix.msl.io.MslEncoderUtils; import com.netflix.msl.io.MslObject; import com.netflix.msl.tokens.MasterToken; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.tokens.TokenFactory; import com.netflix.msl.tokens.UserIdToken; import com.netflix.msl.util.MslContext; import com.netflix.msl.util.MslUtils; /** * <p>The KanColle token factory.</p> * * @author Wesley Miaw <[email protected]> */ public class KanColleTokenFactory implements TokenFactory { // The master token renewal window is how often a ship or port may acquire // new session keys. The expiration specifies when new session keys must be // acquired. // // Ship or port revocation is checked separately. /** Master token renewal window offset in seconds. */ private static final int mtRenewalOffset = 3600; // 1 hour /** Master token expiration offset in seconds. */ private static final int mtExpirationOffset = 24 * 3600; // 24 hours // The user ID token renewal window is how often a user may have its user // data or state checked and updated. The expiration specifies when the // user data must be checked and updated. // // Officer revocation is checked separately. /** User ID token renewal window offset in seconds. */ private static final int uitRenewalOffset = 600; // 10 minutes /** User ID token expiration offset in seconds. */ private static final int uitExpirationOffset = 3600; // 1 hour /** Non-replayable ID acceptance window. */ private static final long NON_REPLAYABLE_ID_WINDOW = 65536; /** * <p>Create a KanColle token factory with the provided authentication * utilities.</p> * * @param utils KanColle utilities. */ public KanColleTokenFactory(final KanColleAuthenticationUtils utils) { this.utils = utils; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isMasterTokenRevoked(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken) */ @Override public MslError isMasterTokenRevoked(final MslContext ctx, final MasterToken masterToken) throws MslMasterTokenException { // Fail if the master token is not decrypted. if (!masterToken.isDecrypted()) throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken); // Extract the entity identity. It may be a ship or a naval port. final String identity = masterToken.getIdentity(); // Check for revocation. final MslError kanmusuRevoked = utils.isKanmusuRevoked(identity); if (kanmusuRevoked != null) return kanmusuRevoked; return utils.isNavalPortRevoked(identity); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#acceptNonReplayableId(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, long) */ @Override public MslError acceptNonReplayableId(final MslContext ctx, final MasterToken masterToken, final long nonReplayableId) throws MslException { // Fail if the master token is not decrypted. if (!masterToken.isDecrypted()) throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken); // Fail if the non-replayable ID is out of range. if (nonReplayableId < 0 || nonReplayableId > MslConstants.MAX_LONG_VALUE) throw new MslException(MslError.NONREPLAYABLE_ID_OUT_OF_RANGE, "nonReplayableId " + nonReplayableId); // Pull the last-seen non-replayable ID. final String identity = masterToken.getIdentity(); final long serialNumber = masterToken.getSerialNumber(); final String key = identity + "+" + Long.toString(serialNumber); final Long lastSeenId = nonReplayableIds.get(key); // If we've never seen a non-replayable ID then accept and remember // this one. if (lastSeenId == null) { nonReplayableIds.put(key, Long.valueOf(nonReplayableId)); return null; } // Reject if the non-replayable ID is equal or just a few messages // behind. The sender can recover by incrementing. final long catchupWindow = MslConstants.MAX_MESSAGES / 2; if (nonReplayableId <= lastSeenId && nonReplayableId > lastSeenId - catchupWindow) { return MslError.MESSAGE_REPLAYED; } // Reject if the non-replayable ID is larger by more than the // acceptance window. The sender cannot recover quickly. if (nonReplayableId - NON_REPLAYABLE_ID_WINDOW > lastSeenId) return MslError.MESSAGE_REPLAYED_UNRECOVERABLE; // If the non-replayable ID is smaller reject it if it is outside the // wrap-around window. The sender cannot recover quickly. if (nonReplayableId < lastSeenId) { final long cutoff = lastSeenId - MslConstants.MAX_LONG_VALUE + NON_REPLAYABLE_ID_WINDOW; if (nonReplayableId >= cutoff) return MslError.MESSAGE_REPLAYED_UNRECOVERABLE; } // Accept the non-replayable ID. nonReplayableIds.put(key, Long.valueOf(nonReplayableId)); return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.entityauth.EntityAuthenticationData, javax.crypto.SecretKey, javax.crypto.SecretKey, com.netflix.msl.io.MslObject) */ @Override public MasterToken createMasterToken(final MslContext ctx, final EntityAuthenticationData entityAuthData, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException { final Date renewal = new Date(ctx.getTime() + mtRenewalOffset); final Date expiration = new Date(ctx.getTime() + mtExpirationOffset); final long sequenceNumber = 0; final long serialNumber = MslUtils.getRandomLong(ctx); final String identity = entityAuthData.getIdentity(); return new MasterToken(ctx, renewal, expiration, sequenceNumber, serialNumber, issuerData, identity, encryptionKey, hmacKey); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isMasterTokenRenewable(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken) */ @Override public MslError isMasterTokenRenewable(final MslContext ctx, final MasterToken masterToken) throws MslMasterTokenException { // Fail if the master token is not decrypted. if (!masterToken.isDecrypted()) throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken); // Check sequence number. final String identity = masterToken.getIdentity(); final long oldSequenceNumber = masterToken.getSequenceNumber(); final Long lastSequenceNumber = sequenceNumbers.get(identity); if (lastSequenceNumber != null && lastSequenceNumber.longValue() != oldSequenceNumber) return MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC; // Renewable. return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#renewMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, javax.crypto.SecretKey, javax.crypto.SecretKey, com.netflix.msl.io.MslObject) */ @Override public MasterToken renewMasterToken(final MslContext ctx, final MasterToken masterToken, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslMasterTokenException, MslEncodingException, MslCryptoException { // Fail if the master token is not decrypted. if (!masterToken.isDecrypted()) throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken); // Check sequence number. final String identity = masterToken.getIdentity(); final long oldSequenceNumber = masterToken.getSequenceNumber(); final Long lastSequenceNumber = sequenceNumbers.get(identity); if (lastSequenceNumber != null && lastSequenceNumber.longValue() != oldSequenceNumber) throw new MslMasterTokenException(MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC, masterToken); final long sequenceNumber = (oldSequenceNumber == MslConstants.MAX_LONG_VALUE) ? 0 : oldSequenceNumber + 1; // Renew master token. final Date renewal = new Date(ctx.getTime() + mtRenewalOffset); final Date expiration = new Date(ctx.getTime() + mtExpirationOffset); final long serialNumber = masterToken.getSerialNumber(); final MslObject mtIssuerData = masterToken.getIssuerData(); final MslObject mergedIssuerData; try { mergedIssuerData = MslEncoderUtils.merge(mtIssuerData, issuerData); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MASTERTOKEN_ISSUERDATA_ENCODE_ERROR, "mt issuerdata " + mtIssuerData + "; issuerdata " + issuerData, e); } return new MasterToken(ctx, renewal, expiration, sequenceNumber, serialNumber, mergedIssuerData, identity, encryptionKey, hmacKey); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isUserIdTokenRevoked(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken) */ @Override public MslError isUserIdTokenRevoked(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken) throws MslMasterTokenException, MslUserIdTokenException { // Verify the master token and user ID token. if (!masterToken.isDecrypted()) throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken); if (!userIdToken.isDecrypted()) throw new MslUserIdTokenException(MslError.USERIDTOKEN_NOT_DECRYPTED, userIdToken); // Check for revocation. final MslUser user = userIdToken.getUser(); if (!(user instanceof Officer)) throw new MslInternalException("The user ID token MSL user is not an instance of " + Officer.class.getName() + "."); final Officer officer = (Officer)user; return utils.isOfficerRevoked(officer.getName()); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MslUser, com.netflix.msl.tokens.MasterToken) */ @Override public UserIdToken createUserIdToken(final MslContext ctx, final MslUser user, final MasterToken masterToken) throws MslEncodingException, MslCryptoException { final long now = ctx.getTime(); final Date renewal = new Date(now + uitRenewalOffset); final Date expiration = new Date(now + uitExpirationOffset); final long serialNumber = MslUtils.getRandomLong(ctx); final MslObject issuerData = null; return new UserIdToken(ctx, renewal, expiration, masterToken, serialNumber, issuerData, user); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#renewUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.UserIdToken, com.netflix.msl.tokens.MasterToken) */ @Override public UserIdToken renewUserIdToken(final MslContext ctx, final UserIdToken userIdToken, final MasterToken masterToken) throws MslUserIdTokenException, MslEncodingException, MslCryptoException { // Fail if the user ID token is not decrypted. if (!userIdToken.isDecrypted()) throw new MslUserIdTokenException(MslError.USERIDTOKEN_NOT_DECRYPTED, userIdToken).setMasterToken(masterToken); final long now = ctx.getTime(); final Date renewal = new Date(now + uitRenewalOffset); final Date expiration = new Date(now + uitExpirationOffset); final long serialNumber = userIdToken.getSerialNumber(); final MslObject issuerData = null; final MslUser user = userIdToken.getUser(); return new UserIdToken(ctx, renewal, expiration, masterToken, serialNumber, issuerData, user); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createUser(com.netflix.msl.util.MslContext, String) */ @Override public MslUser createUser(final MslContext ctx, final String userdata) { return new Officer(userdata); } /** Latest master token sequence numbers by entity identity. */ private final Map<String,Long> sequenceNumbers = new HashMap<String,Long>(); /** Last-seen non-replayable IDs by entity identity + serial number. */ private final Map<String,Long> nonReplayableIds = new HashMap<String,Long>(); /** KanColle utilities. */ private final KanColleAuthenticationUtils utils; }
2,060
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/entityauth/KanmusuDatabase.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.entityauth; /** * Provides access to Kanmusu data. * * @author Wesley Miaw <[email protected]> */ public interface KanmusuDatabase { /** Kanmusu status. */ public static enum Status { /** Active. */ ACTIVE, /** Presumed captured. */ CAPTURED, /** Presumed missing. */ MISSING, /** Confirmed destroyed. */ DESTROYED } /** * Return the current status of the specified Kanmusu ship. * * @param type ship type. * @param name ship name. * @return the ship's current status or {@code null} if the ship is not * recognized. */ public Status getStatus(final String type, final String name); /** * Return the passphrase for the specified Kanmusu ship. * * @param type ship type. * @param name ship name. * @return the generated passphrase or {@code null} if the ship is not * recognized or accepted. */ public String getPassphrase(final String type, final String name); }
2,061
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/entityauth/SimpleNavalPortDatabase.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.entityauth; import java.util.HashMap; import java.util.Map; /** * <p>A simple in-memory naval port database.</p> * * @author Wesley Miaw <[email protected]> */ public class SimpleNavalPortDatabase implements NavalPortDatabase { /** * <p>Create a new simple naval port database instance that is unaware of * any existing ports.</p> */ public SimpleNavalPortDatabase() { } /** * <p>Set the naval port data. This adds the port if previously * unknown.</p> * * @param callsign port callsign. * @param state port state. * @param book port codebook. */ public void setNavalPort(final String callsign, final Status state, final CodeBook book) { if (state == null) throw new IllegalArgumentException("Naval port state cannot be null."); if (book == null) throw new IllegalArgumentException("Naval port code book cannot be null."); states.put(callsign, state); books.put(callsign, book); } /** * <p>Set the naval port state. The naval port must already been known.</p> * * @param callsign port callsign. * @param state port state. */ public void setStatus(final String callsign, final Status state) { if (state == null) throw new IllegalArgumentException("Naval port state cannot be null."); if (!states.containsKey(callsign)) throw new IllegalStateException("Naval port " + callsign + " is not known."); states.put(callsign, state); } /* (non-Javadoc) * @see kancolle.entityauth.NavalPortDatabase#getStatus(java.lang.String) */ @Override public Status getStatus(final String callsign) { return states.get(callsign); } /* (non-Javadoc) * @see kancolle.entityauth.NavalPortDatabase#getCodeBook(java.lang.String) */ @Override public CodeBook getCodeBook(final String callsign) { return books.get(callsign); } /** Naval port states by callsign. */ private final Map<String,Status> states = new HashMap<String,Status>(); /** Naval port code books by callsign. */ private final Map<String,CodeBook> books = new HashMap<String,CodeBook>(); }
2,062
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/entityauth/KanColleEntityAuthenticationScheme.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.entityauth; import com.netflix.msl.entityauth.EntityAuthenticationScheme; /** * <p>KanColle entity authentication schemes.</p> * * @author Wesley Miaw <[email protected]> */ public class KanColleEntityAuthenticationScheme extends EntityAuthenticationScheme { /** Kanmusu entity authentication scheme. */ public static final EntityAuthenticationScheme KANMUSU = new KanColleEntityAuthenticationScheme("KANMUSU", true, true); /** Naval port entity authentication scheme. */ public static final EntityAuthenticationScheme NAVAL_PORT = new KanColleEntityAuthenticationScheme("NAVAL_PORT", true, true); /** * Define a KanColle entity authentication scheme with the specified name. * * @param name the entity authentication scheme name. * @param encrypts true if the scheme encrypts message data. * @param protects true if the scheme protects message integrity. */ protected KanColleEntityAuthenticationScheme(final String name, final boolean encrypts, final boolean protects) { super(name, encrypts, protects); } }
2,063
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/entityauth/SimpleKanmusuDatabase.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.entityauth; import java.util.HashMap; import java.util.Map; /** * <p>A simple in-memory Kanmusu ship database.</p> * * @author Wesley Miaw <[email protected]> */ public class SimpleKanmusuDatabase implements KanmusuDatabase { /** * @param type ship type. * @param name ship name. * @return the constructed ship identity for internal use. */ private static String getIdentity(final String type, final String name) { return type + ":" + name; } /** * <p>Create a new simple Kanmusu ship database instance that is unaware of * any existing ships.</p> */ public SimpleKanmusuDatabase() { } /** * <p>Set the Kanmusu ship data. This adds the ship if previously * unknown.</p> * * @param type ship type. * @param name ship name. * @param state ship state. * @param passphrase ship passphrase. */ public void setKanmusu(final String type, final String name, final Status state, final String passphrase) { if (state == null) throw new IllegalArgumentException("Kanmusu ship state cannot be null."); if (passphrase == null) throw new IllegalArgumentException("Kanmusu ship passphrase cannot be null."); final String identity = getIdentity(type, name); states.put(identity, state); passphrases.put(identity, passphrase); } /** * <p>Set the Kanmusu ship state. The ship must already be known.</p> * * @param type ship type. * @param name ship name. * @param state ship state. * @throws IllegalStateException if the ship is not known. */ public void setStatus(final String type, final String name, final Status state) { if (state == null) throw new IllegalArgumentException("Kanmusu ship state cannot be null."); final String identity = getIdentity(type, name); if (!states.containsKey(identity)) throw new IllegalStateException("Kanmusu ship " + identity + " is not known."); states.put(identity, state); } /* (non-Javadoc) * @see kancolle.entityauth.KanmusuDatabase#getStatus(java.lang.String, java.lang.String) */ @Override public Status getStatus(final String type, final String name) { final String identity = getIdentity(type, name); return states.get(identity); } /* (non-Javadoc) * @see kancolle.entityauth.KanmusuDatabase#getPassphrase(java.lang.String, java.lang.String) */ @Override public String getPassphrase(final String type, final String name) { final String identity = getIdentity(type, name); return passphrases.get(identity); } /** Kanmusu ship states by identity. */ private final Map<String,Status> states = new HashMap<String,Status>(); /** Kanmusu ship passphrases by identity. */ private final Map<String,String> passphrases = new HashMap<String,String>(); }
2,064
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/entityauth/KanmusuAuthenticationData.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.entityauth; import kancolle.KanColleMslError; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslEntityAuthException; import com.netflix.msl.MslError; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.io.MslEncoderException; import com.netflix.msl.io.MslEncoderFactory; import com.netflix.msl.io.MslEncoderFormat; import com.netflix.msl.io.MslObject; /** * <p>Each Kanmusu ship is identified by a type and name. The unique identity * of a ship is equal to the type and name concatenated in that order by a * single colon ":" character.</p> * * <p> * {@code { * "#mandatory" : [ "type", "name" ], * "type" : "string", * "name" : "name", * }} where: * <ul> * <li>{@code type} is the ship type</li> * <li>{@code name} is the ship name</li> * </ul></p> * * @author Wesley Miaw <[email protected]> */ public class KanmusuAuthenticationData extends EntityAuthenticationData { /** Key ship type. */ private static final String KEY_TYPE = "type"; /** Key ship name. */ private static final String KEY_NAME = "name"; /** Colon character. */ private static final String CHAR_COLON = ":"; /** * Construct a new Kanmusu authentication data instance with the specified * type and name. Colons are not permitted in the type or name. * * @param type the ship type. * @param name the ship name. * @throws IllegalArgumentException if the type or name contains a colon. */ public KanmusuAuthenticationData(final String type, final String name) { super(KanColleEntityAuthenticationScheme.KANMUSU); // Colons are not permitted in the type or name. if (type.contains(CHAR_COLON) || name.contains(CHAR_COLON)) throw new IllegalArgumentException("Colons are not permitted in the type [" + type + "] or name [" + name + "]."); this.type = type; this.name = name; } /** * Construct a new Kanmusu authentication data instance from the provided * identity. * * @param identity the ship identity. * @throws IllegalArgumentException if the identity does not consist of a * type and name separated by a single colon. * @see #getIdentity() */ public KanmusuAuthenticationData(final String identity) { super(KanColleEntityAuthenticationScheme.KANMUSU); // Split on the colon. final String[] parts = identity.split(CHAR_COLON); if (parts.length != 2) throw new IllegalArgumentException("Identity must consist of a type and name separated by a single colon."); this.type = parts[0]; this.name = parts[1]; } /** * Construct a new Kanmusu authentication data instance from the provided * MSL object. * * @param kanmusuMo the authentication data MSL object. * @throws MslEncodingException if there is an error parsing the entity * authentication data. * @throws MslEntityAuthException if the type or name includes a colon. */ public KanmusuAuthenticationData(final MslObject kanmusuMo) throws MslEncodingException, MslEntityAuthException { super(KanColleEntityAuthenticationScheme.KANMUSU); try { type = kanmusuMo.getString(KEY_TYPE); name = kanmusuMo.getString(KEY_NAME); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "kanmusu authdata " + kanmusuMo.toString(), e); } // Colons are not permitted in the type or name. if (type.contains(CHAR_COLON) || name.contains(CHAR_COLON)) throw new MslEntityAuthException(KanColleMslError.KANMUSU_ILLEGAL_IDENTITY, "kanmusu authdata " + kanmusuMo.toString()); } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationData#getIdentity() */ @Override public String getIdentity() { return type + ":" + name; } /** * @return the ship type. */ public String getType() { return type; } /** * @return the ship name. */ public String getName() { return name; } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationData#getAuthData(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat) */ @Override public MslObject getAuthData(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException { final MslObject mo = encoder.createObject(); mo.put(KEY_TYPE, type); mo.put(KEY_NAME, name); return mo; } /** Ship type. */ private final String type; /** Ship name. */ private final String name; }
2,065
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/entityauth/NavalPortAuthenticationData.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.entityauth; import kancolle.KanColleMslError; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslError; import com.netflix.msl.MslException; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.io.MslEncoderException; import com.netflix.msl.io.MslEncoderFactory; import com.netflix.msl.io.MslEncoderFormat; import com.netflix.msl.io.MslObject; /** * <p>Each naval port is identified by a callsign. The callsign may not contain * a colon ":" character.</p> * * <p>In order to authenticate a port uses a secret word from its associated * codebook identified by a page and word number. The page and word number * should be randomly chosen.</p> * * <p> * {@code { * "#mandatory" : [ "callsign", "page", "word" ], * "callsign" : "string", * "page" : "number", * "word" : "number", * }} where: * <ul> * <li>{@code callsign} is the port callsign</li> * <li>{@code page} is a page number from the port codebook</li> * <li>{@code word} is a word number from the identified page of the port codebook</li> * </ul></p> * * @author Wesley Miaw <[email protected]> */ public class NavalPortAuthenticationData extends EntityAuthenticationData { /** Colon character. */ private static final String CHAR_COLON = ":"; /** Key callsign. */ private static final String KEY_CALLSIGN = "callsign"; /** Key page number. */ private static final String KEY_PAGE = "page"; /** Key word number. */ private static final String KEY_WORD = "word"; /** * Construct a new naval port authentication data instance with the * specified callsign and given page and word number. * * @param callsign the port callsign. * @param page the codebook page number. * @param word the codebook word number. * @throws IllegalArgumentException if the callsign contains a colon. */ public NavalPortAuthenticationData(final String callsign, final int page, final int word) { super(KanColleEntityAuthenticationScheme.NAVAL_PORT); // Colons are not permitted in the callsign. if (callsign.contains(CHAR_COLON)) throw new IllegalArgumentException("Colons are not permitted in the callsign [" + callsign + "]."); this.callsign = callsign; this.page = page; this.word = word; } /** * Construct a new naval port authentication data instance from the * provided MSL object. * * @param navalPortMo the authentication data MSL object. * @throws MslEncodingException if there is an error parsing the entity * authentication data. * @throws MslException if the callsign contains a colon. */ public NavalPortAuthenticationData(final MslObject navalPortMo) throws MslEncodingException, MslException { super(KanColleEntityAuthenticationScheme.NAVAL_PORT); try { callsign = navalPortMo.getString(KEY_CALLSIGN); page = navalPortMo.getInt(KEY_PAGE); word = navalPortMo.getInt(KEY_WORD); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "naval port authdata " + navalPortMo.toString(), e); } // Colons are not permitted in the callsign. if (callsign.contains(CHAR_COLON)) throw new MslException(KanColleMslError.NAVALPORT_ILLEGAL_IDENTITY, "naval port authdata " + navalPortMo.toString()); } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationData#getIdentity() */ @Override public String getIdentity() { return callsign; } /** * @return the codebook page number. */ public int getPage() { return page; } /** * @return the codebook word number. */ public int getWord() { return word; } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationData#getAuthData(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat) */ @Override public MslObject getAuthData(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException { final MslObject mo = encoder.createObject(); mo.put(KEY_CALLSIGN, callsign); mo.put(KEY_PAGE, page); mo.put(KEY_WORD, word); return mo; } /** Port callsign. */ private final String callsign; /** Codebook page number. */ private final int page; /** Codebook word number. */ private final int word; }
2,066
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/entityauth/KanmusuAuthenticationFactory.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.entityauth; import kancolle.KanColleMslError; import kancolle.crypto.KanColleCryptoContext; import kancolle.entityauth.KanmusuDatabase.Status; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslEntityAuthException; import com.netflix.msl.MslError; import com.netflix.msl.MslInternalException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.EntityAuthenticationFactory; import com.netflix.msl.io.MslObject; import com.netflix.msl.util.MslContext; /** * <p>Each Kanmusu ship is associated with a passphrase. The passphrase is used * with a {@link KanColleCryptoContext}.</p> * * @author Wesley Miaw <[email protected]> */ public class KanmusuAuthenticationFactory extends EntityAuthenticationFactory { /** * Create a new Kanmusu authentication factory with the provided database. * * @param database Kanmusu database. */ public KanmusuAuthenticationFactory(final KanmusuDatabase database) { super(KanColleEntityAuthenticationScheme.KANMUSU); this.database = database; } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationFactory#createData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject) */ @Override public EntityAuthenticationData createData(final MslContext ctx, final MslObject entityAuthMo) throws MslEncodingException, MslEntityAuthException { return new KanmusuAuthenticationData(entityAuthMo); } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.entityauth.EntityAuthenticationData) */ @Override public ICryptoContext getCryptoContext(final MslContext ctx, final EntityAuthenticationData authdata) throws MslEntityAuthException { // Make sure we have the right kind of entity authentication data. if (!(authdata instanceof KanmusuAuthenticationData)) throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + "."); final KanmusuAuthenticationData kad = (KanmusuAuthenticationData)authdata; // Check ship status. final String type = kad.getType(); final String name = kad.getName(); final Status status = database.getStatus(type, name); if (status == null) throw new MslEntityAuthException(MslError.ENTITY_NOT_FOUND, "kanmusu " + kad.getIdentity()).setEntityAuthenticationData(kad); switch (status) { case DESTROYED: throw new MslEntityAuthException(KanColleMslError.ENTITYAUTH_KANMUSU_DESTROYED, "kanmusu " + kad.getIdentity()).setEntityAuthenticationData(kad); // We do not reject authentication for the other states. default: break; } // Return the crypto context. final String passphrase = database.getPassphrase(kad.getType(), kad.getName()); if (passphrase == null) throw new MslEntityAuthException(MslError.ENTITY_NOT_FOUND, "kanmusu " + kad.getIdentity()).setEntityAuthenticationData(kad); final String identity = kad.getIdentity(); return new KanColleCryptoContext(ctx, identity, passphrase); } /** Kanmusu database. */ private final KanmusuDatabase database; }
2,067
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/entityauth/FivePageCodeBook.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.entityauth; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * <p>A code book that considers one page to consist of five lines of text.</p> * * @author Wesley Miaw <[email protected]> */ public class FivePageCodeBook implements CodeBook { /** Five lines per page. */ private static final int LINES_PER_PAGE = 5; /** * <p>Create a new code book from the given input stream.</p> * * @param in code book input stream. * @throws IOException if there is an error reading the code book. */ public FivePageCodeBook(final InputStream in) throws IOException { // Convert the raw bytes to a string. final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final byte[] b = new byte[4096]; do { final int read = in.read(b); if (read == -1) break; baos.write(b, 0, read); } while (true); final String text = baos.toString(); // Add words to the page until we hit the fifth newline. final StringTokenizer tokenizer = new StringTokenizer(text, " \t\n\r\f", true); List<String> page = new ArrayList<String>(); int lineNumber = 1; while (tokenizer.hasMoreTokens()) { final String token = tokenizer.nextToken(); // Skip spaces, tabs, and form feeds. if (" \t\f".indexOf(token) != -1) continue; // On newlines, add the current page (if not empty) and move // forward. if ("\n\r".indexOf(token) != -1) { ++lineNumber; if (lineNumber % LINES_PER_PAGE == 0 && page.size() > 0) { pages_words.add(page); page = new ArrayList<String>(); } continue; } // Add word. page.add(token); } // Add the final page (if not empty). if (page.size() > 0) pages_words.add(page); } /* (non-Javadoc) * @see kancolle.entityauth.CodeBook#getPageCount() */ @Override public int getPageCount() { return pages_words.size(); } /* (non-Javadoc) * @see kancolle.entityauth.CodeBook#getWordCount(int) */ @Override public int getWordCount(final int page) { if (page > pages_words.size()) throw new IllegalArgumentException("The page number " + page + " exceeds the code book page count."); final List<String> words = pages_words.get(page - 1); return words.size(); } /* (non-Javadoc) * @see kancolle.entityauth.CodeBook#getWord(int, int) */ @Override public String getWord(final int page, final int word) { if (page > pages_words.size()) throw new IllegalArgumentException("The page number " + page + " exceeds the code book page count."); final List<String> words = pages_words.get(page - 1); if (word > words.size()) throw new IllegalArgumentException("The word number " + word + " exceeds the code book word count on page " + page + "."); return words.get(word - 1); } /** Pages and words. */ private final List<List<String>> pages_words = new ArrayList<List<String>>(); }
2,068
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/entityauth/NavalPortAuthenticationFactory.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.entityauth; import kancolle.KanColleMslError; import kancolle.crypto.KanColleCryptoContext; import kancolle.entityauth.NavalPortDatabase.Status; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslEntityAuthException; import com.netflix.msl.MslError; import com.netflix.msl.MslException; import com.netflix.msl.MslInternalException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.EntityAuthenticationFactory; import com.netflix.msl.io.MslObject; import com.netflix.msl.util.MslContext; /** * <p>Each naval port is associated with a codebook. The codebook is used to * look up a secret word based off a page and word number. The word is used * with a {@link KanColleCryptoContext}.</p> * * @author Wesley Miaw <[email protected]> */ public class NavalPortAuthenticationFactory extends EntityAuthenticationFactory { /** * Create a new naval port authentication factory with the provided * database. * * @param database naval port database. */ public NavalPortAuthenticationFactory(final NavalPortDatabase database) { super(KanColleEntityAuthenticationScheme.NAVAL_PORT); this.database = database; } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationFactory#createData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject) */ @Override public EntityAuthenticationData createData(final MslContext ctx, final MslObject entityAuthJO) throws MslEncodingException, MslEntityAuthException { try { return new NavalPortAuthenticationData(entityAuthJO); } catch (final MslException e) { throw new MslEntityAuthException(KanColleMslError.NAVALPORT_ILLEGAL_IDENTITY, e); } } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.entityauth.EntityAuthenticationData) */ @Override public ICryptoContext getCryptoContext(final MslContext ctx, final EntityAuthenticationData authdata) throws MslEntityAuthException { // Make sure we have the right kind of entity authentication data. if (!(authdata instanceof NavalPortAuthenticationData)) throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + "."); final NavalPortAuthenticationData npad = (NavalPortAuthenticationData)authdata; // Check port status. final String identity = npad.getIdentity(); final Status status = database.getStatus(identity); if (status == null) throw new MslEntityAuthException(MslError.ENTITY_NOT_FOUND, "naval port " + npad.getIdentity()).setEntityAuthenticationData(npad); switch (status) { case INACTIVE: throw new MslEntityAuthException(KanColleMslError.ENTITYAUTH_NAVALPORT_INACTIVE, "naval port " + npad.getIdentity()); case DESTROYED: throw new MslEntityAuthException(KanColleMslError.ENTITYAUTH_NAVALPORT_DESTROYED, "naval port " + npad.getIdentity()).setEntityAuthenticationData(npad); // We do not reject authentication for the other states. default: break; } // Return the crypto context. final int page = npad.getPage(); final int word = npad.getWord(); final CodeBook book = database.getCodeBook(identity); final String secret = book.getWord(page, word); if (secret == null) throw new MslEntityAuthException(MslError.ENTITY_NOT_FOUND, "naval port " + npad.getIdentity()).setEntityAuthenticationData(npad); return new KanColleCryptoContext(ctx, identity, secret); } /** Naval port database. */ private final NavalPortDatabase database; }
2,069
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/entityauth/NavalPortDatabase.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.entityauth; /** * Provides access to naval port data. * * @author Wesley Miaw <[email protected]> */ public interface NavalPortDatabase { /** Kanmusu status. */ public static enum Status { /** Active. */ ACTIVE, /** Inactive. */ INACTIVE, /** Presumed captured. */ CAPTURED, /** Confirmed destroyed. */ DESTROYED } /** * Return the current status of the specified naval port. * * @param callsign the naval port callsign. * @return the port's current status or {@code null} if the port is not * recognized. */ public Status getStatus(final String callsign); /** * Return the code book for the specified naval port. * * @param callsign the naval port callsign. * @return the port's code book or {@code null} if the port is not * recognized. */ public CodeBook getCodeBook(final String callsign); }
2,070
0
Create_ds/msl/examples/kancolle/src/main/java/kancolle
Create_ds/msl/examples/kancolle/src/main/java/kancolle/entityauth/CodeBook.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kancolle.entityauth; /** * A naval port's secret code book used to authentication. * * @author Wesley Miaw <[email protected]> */ public interface CodeBook { /** * @return the number of pages in the code book. */ public int getPageCount(); /** * @param page the page number, 1-based. * @return the number of words on the given page. * @throws IllegalArgumentException if the page number is invalid. */ public int getWordCount(int page) throws IllegalArgumentException; /** * Returns the word located at the specified page and word. * * @param page the page number, 1-based. * @param word the word number, 1-based. * @return the specified word. * @throws IllegalArgumentException if the page and word number combination * is invalid. */ public String getWord(int page, int word) throws IllegalArgumentException; }
2,071
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/ClientConfiguration.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.client.configuration.entityauth.TestEccAuthenticationFactory; import com.netflix.msl.client.configuration.entityauth.TestPresharedAuthenticationFactory; import com.netflix.msl.client.configuration.entityauth.TestRsaAuthenticationFactory; import com.netflix.msl.client.configuration.entityauth.TestX509AuthenticationFactory; import com.netflix.msl.client.configuration.msg.ClientMessageContext; import com.netflix.msl.client.configuration.msg.InvalidUserAuthScheme; import com.netflix.msl.client.configuration.util.ClientMslContext; import com.netflix.msl.entityauth.EccAuthenticationData; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.EntityAuthenticationFactory; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.entityauth.PresharedAuthenticationData; import com.netflix.msl.entityauth.RsaAuthenticationData; import com.netflix.msl.entityauth.UnauthenticatedAuthenticationData; import com.netflix.msl.entityauth.UnauthenticatedAuthenticationFactory; import com.netflix.msl.entityauth.X509AuthenticationData; import com.netflix.msl.io.JavaUrl; import com.netflix.msl.io.Url; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.MslControl; import com.netflix.msl.userauth.EmailPasswordAuthenticationData; import com.netflix.msl.userauth.MockEmailPasswordAuthenticationFactory; import com.netflix.msl.userauth.UserAuthenticationData; import com.netflix.msl.userauth.UserAuthenticationScheme; import com.netflix.msl.util.AuthenticationUtils; import com.netflix.msl.util.MockAuthenticationUtils; /** * User: skommidi * Date: 7/25/14 */ public class ClientConfiguration { public static final String input = "Hello"; public static final String serverError = "Error"; private MslControl mslControl; private ClientMslContext mslContext; private ClientMessageContext messageContext; private Url remoteEntity; private String scheme = "http"; private String remoteHost = "localhost"; private String path = ""; private String remoteEntityIdentity = null; private String userId = null; private boolean isPeerToPeer = false; private EntityAuthenticationScheme entityAuthenticationScheme = EntityAuthenticationScheme.PSK; private UserAuthenticationScheme userAuthenticationScheme = UserAuthenticationScheme.EMAIL_PASSWORD; private KeyExchangeScheme keyExchangeScheme = KeyExchangeScheme.SYMMETRIC_WRAPPED; private boolean nonReplayable = false; private int entityAuthRetryCount = 0; private boolean resetEntityAuthRetryCount = false; private int userAuthRetryCount = 0; private boolean resetUserAuthRetryCount = false; private InvalidUserAuthScheme setInvalidUserAuthData = null; private boolean setInvalidEntityAuthData = false; private boolean isNullCryptoContext = false; private boolean isMessageEncrypted = true; private boolean setNullUserAuthData = false; private boolean isIntegrityProtected = true; private boolean clearKeyRequestData = false; public ClientConfiguration setEntityAuthenticationScheme(final EntityAuthenticationScheme scheme) { entityAuthenticationScheme = scheme; return this; } public ClientConfiguration setRemoteEntityIdentity(final String identity) { remoteEntityIdentity = identity; return this; } public ClientConfiguration setUserAuthenticationScheme(final UserAuthenticationScheme scheme) { userAuthenticationScheme = scheme; return this; } public ClientConfiguration setUserId(final String userId) { this.userId = userId; return this; } public ClientConfiguration setIsMessageEncrypted(final boolean messageEncrypted) { this.isMessageEncrypted = messageEncrypted; return this; } public ClientConfiguration setIsIntegrityProtected(final boolean integrityProtected) { this.isIntegrityProtected = integrityProtected; return this; } public ClientConfiguration setKeyRequestData(final KeyExchangeScheme scheme) { keyExchangeScheme = scheme; return this; } /* * Test utility function to get different corrupted entityAuthSchemes */ public ClientConfiguration setInvalidEntityAuthData() { setInvalidEntityAuthData = true; return this; } public ClientConfiguration setInvalidUserAuthData(final InvalidUserAuthScheme scheme) { setInvalidUserAuthData = scheme; return this; } public ClientConfiguration setMaxEntityAuthRetryCount(final int value) { this.entityAuthRetryCount = value; return this; } public ClientConfiguration resetCurrentEntityAuthRetryCount() { this.resetEntityAuthRetryCount = true; return this; } public ClientConfiguration setMaxUserAuthRetryCount(final int value) { this.userAuthRetryCount = value; return this; } public ClientConfiguration resetCurrentUserAuthRetryCount() { this.resetUserAuthRetryCount = true; return this; } public ClientConfiguration setScheme(final String scheme) { this.scheme = scheme; return this; } public ClientConfiguration setHost(final String remoteHost) { this.remoteHost = remoteHost; return this; } public ClientConfiguration setPath(final String path) { this.path = path; return this; } public ClientConfiguration setIsPeerToPeer(final boolean isPeerToPeer) { this.isPeerToPeer = isPeerToPeer; return this; } public ClientConfiguration setMessageNonReplayable(final boolean nonReplayable) { this.nonReplayable = nonReplayable; return this; } public ClientConfiguration setIsNullCryptoContext(final boolean isNullCryptoContext) { this.isNullCryptoContext = isNullCryptoContext; return this; } public void commitConfiguration() throws URISyntaxException, IOException, MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException { remoteEntity = new JavaUrl(new URL(scheme + "://" + remoteHost + path)); /** create msl context and configure */ mslContext = new ClientMslContext(entityAuthenticationScheme, isPeerToPeer, isNullCryptoContext); //Setting the maxRetryCount for mslContext mslContext.setMaxRetryCount(this.entityAuthRetryCount); if(this.resetEntityAuthRetryCount) { mslContext.resetCurrentRetryCount(); } if(setInvalidEntityAuthData) { mslContext.removeEntityAuthenticationFactory(entityAuthenticationScheme); final AuthenticationUtils authutils = new MockAuthenticationUtils(); EntityAuthenticationFactory entityAuthenticationFactory; if (EntityAuthenticationScheme.PSK.equals(entityAuthenticationScheme)) entityAuthenticationFactory = new TestPresharedAuthenticationFactory(); else if (EntityAuthenticationScheme.X509.equals(entityAuthenticationScheme)) entityAuthenticationFactory = new TestX509AuthenticationFactory(); else if (EntityAuthenticationScheme.RSA.equals(entityAuthenticationScheme)) entityAuthenticationFactory = new TestRsaAuthenticationFactory(); else if (EntityAuthenticationScheme.ECC.equals(entityAuthenticationScheme)) entityAuthenticationFactory = new TestEccAuthenticationFactory(); else if (EntityAuthenticationScheme.NONE.equals(entityAuthenticationScheme)) entityAuthenticationFactory = new UnauthenticatedAuthenticationFactory(authutils); else throw new IllegalArgumentException("Unsupported authentication type: " + entityAuthenticationScheme.name()); mslContext.addEntityAuthenticationFactory(entityAuthenticationFactory); EntityAuthenticationData entityAuthenticationData; if (EntityAuthenticationScheme.PSK.equals(entityAuthenticationScheme)) entityAuthenticationData = new PresharedAuthenticationData(TestPresharedAuthenticationFactory.PSK_ESN); else if (EntityAuthenticationScheme.X509.equals(entityAuthenticationScheme)) entityAuthenticationData = new X509AuthenticationData(TestX509AuthenticationFactory.X509_CERT); else if (EntityAuthenticationScheme.RSA.equals(entityAuthenticationScheme)) entityAuthenticationData = new RsaAuthenticationData(TestRsaAuthenticationFactory.RSA_ESN, TestRsaAuthenticationFactory.RSA_PUBKEY_ID); else if (EntityAuthenticationScheme.ECC.equals(entityAuthenticationScheme)) entityAuthenticationData = new EccAuthenticationData(TestEccAuthenticationFactory.ECC_ESN, TestEccAuthenticationFactory.ECC_PUBKEY_ID); else if (EntityAuthenticationScheme.NONE.equals(entityAuthenticationScheme)) entityAuthenticationData = new UnauthenticatedAuthenticationData("identity-test"); else throw new IllegalArgumentException("Unsupported authentication type: " + entityAuthenticationScheme.name()); mslContext.setEntityAuthenticationData(entityAuthenticationData); } /** create message context and configure */ messageContext = new ClientMessageContext(mslContext, userId, userAuthenticationScheme, isMessageEncrypted, isIntegrityProtected); if (remoteEntityIdentity != null) messageContext.setRemoteEntityIdentity(remoteEntityIdentity); messageContext.resetKeyRequestData(keyExchangeScheme); if(this.clearKeyRequestData) { messageContext.clearKeyRequestData(); } messageContext.setBuffer(input.getBytes(MslConstants.DEFAULT_CHARSET)); messageContext.setNonReplayable(nonReplayable); //Setting the maxRetryCount for msgContext messageContext.setMaxRetryCount(this.userAuthRetryCount); if(this.resetUserAuthRetryCount) { messageContext.resetCurrentRetryCount(); } if(setNullUserAuthData) { messageContext.setUserAuthData(null); } if(setInvalidUserAuthData != null) { UserAuthenticationData userAuthenticationData = null; if(UserAuthenticationScheme.EMAIL_PASSWORD.equals(userAuthenticationScheme)) { switch (setInvalidUserAuthData) { case INVALID_EMAIL: userAuthenticationData = new EmailPasswordAuthenticationData(MockEmailPasswordAuthenticationFactory.EMAIL + "Test", MockEmailPasswordAuthenticationFactory.PASSWORD); break; case INVALID_PASSWORD: userAuthenticationData = new EmailPasswordAuthenticationData(MockEmailPasswordAuthenticationFactory.EMAIL, MockEmailPasswordAuthenticationFactory.PASSWORD + "Test"); break; case EMPTY_EMAIL: userAuthenticationData = new EmailPasswordAuthenticationData("", MockEmailPasswordAuthenticationFactory.PASSWORD); break; case EMPTY_PASSWORD: userAuthenticationData = new EmailPasswordAuthenticationData(MockEmailPasswordAuthenticationFactory.EMAIL, ""); break; default: throw new IllegalArgumentException("Unsupported user auth error type "); } } messageContext.setUserAuthData(userAuthenticationData); } } public ClientConfiguration setNumThreads(final int numThreads) { mslControl = new MslControl(numThreads); //mslControl.setFilterFactory(new TestConsoleFilterStreamFactory()); return this; } public MslControl getMslControl() { return mslControl; } public ClientMslContext getMslContext() { return mslContext; } public ClientMessageContext getMessageContext() { return messageContext; } public Url getRemoteEntity() { return remoteEntity; } public ClientConfiguration setNullUserAuthData() { this.setNullUserAuthData = true; return this; } public boolean isSetNullUserAuthData() { return setNullUserAuthData; } public ClientConfiguration clearKeyRequestData() { this.clearKeyRequestData = true; return this; } }
2,072
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/ServerConfiguration.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.netflix.msl.client.configuration.tokens.TokenFactoryType; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.userauth.UserAuthenticationScheme; /** * User: skommidi * Date: 7/25/14 */ public class ServerConfiguration { private static class NameValuePair { public NameValuePair(final String name, final String value) { try { this.name = URLEncoder.encode(name, "UTF-8"); this.value = URLEncoder.encode(value, "UTF-8"); } catch (final UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 encoding not supported.", e); } } private final String name; private final String value; } private final String scheme = "http"; private String path; private String host; private int numThreads; private EntityAuthenticationScheme entityAuthScheme; private TokenFactoryType tokenFactoryType; private long initialSequenceNum; private boolean isMessageEncrypted; private boolean isIntegrityProtected; private boolean isNullCryptoContext; private boolean setConsoleFilterStreamFactory; private List<EntityAuthenticationScheme> unSupportedEntityAuthFactories; private List<UserAuthenticationScheme> unSupportedUserAuthFactories; private List<KeyExchangeScheme> unSupportedKeyxFactories; private final List<NameValuePair> nvps; private static final String NUM_THREADS = "numthreads"; private static final String ENTITY_AUTH_SCHEME = "entityauthscheme"; private static final String TOKEN_FACTORY_TYPE = "tokenfactorytype"; private static final String INITIAL_SEQUENCE_NUM = "initialseqnum"; private static final String ENCRYPTED = "encrypted"; private static final String NULL_CRYPTO_CONTEXT = "nullCryptoContext"; private static final String CONSOLE_FILTER_STREAM_FACTORY = "consoleFilterStreamFactory"; private static final String UNSUPPORTED_ENTITY_SCHEMES = "unsupentityauthfact"; private static final String UNSUPPORTED_USER_SCHEMES = "unsupuserauthfact"; private static final String UNSUPPORTED_KEY_EXCHANGE_SCHEMES = "unsupkeyexfact"; private static final String INTEGRITY_PROTECTED = "intProtected"; public ServerConfiguration() { nvps = new ArrayList<NameValuePair>(); } public ServerConfiguration resetDefaultConfig() { this.numThreads = 0; this.entityAuthScheme = EntityAuthenticationScheme.NONE; this.tokenFactoryType = TokenFactoryType.NOT_ACCEPT_NON_REPLAYABLE_ID; this.initialSequenceNum = 8L; this.isMessageEncrypted = true; this.isIntegrityProtected = true; this.unSupportedEntityAuthFactories = null; this.unSupportedUserAuthFactories = null; this.unSupportedKeyxFactories = null; this.isNullCryptoContext = false; this.setConsoleFilterStreamFactory = false; this.setNameValuePairs(); return this; } private void setNameValuePairs() { nvps.add(new NameValuePair(NUM_THREADS, String.valueOf(numThreads))); nvps.add(new NameValuePair(ENTITY_AUTH_SCHEME, String.valueOf(entityAuthScheme))); nvps.add(new NameValuePair(TOKEN_FACTORY_TYPE, String.valueOf(tokenFactoryType))); nvps.add(new NameValuePair(INITIAL_SEQUENCE_NUM, String.valueOf(initialSequenceNum))); nvps.add(new NameValuePair(ENCRYPTED, String.valueOf(isMessageEncrypted))); nvps.add(new NameValuePair(INTEGRITY_PROTECTED, String.valueOf(isIntegrityProtected))); nvps.add(new NameValuePair(NULL_CRYPTO_CONTEXT, String.valueOf(isNullCryptoContext))); nvps.add(new NameValuePair(CONSOLE_FILTER_STREAM_FACTORY, String.valueOf(setConsoleFilterStreamFactory))); if(unSupportedEntityAuthFactories!=null) { for(final EntityAuthenticationScheme scheme : unSupportedEntityAuthFactories) { nvps.add(new NameValuePair(UNSUPPORTED_ENTITY_SCHEMES, String.valueOf(scheme))); } } if(unSupportedUserAuthFactories!=null) { for(final UserAuthenticationScheme scheme : unSupportedUserAuthFactories) { nvps.add(new NameValuePair(UNSUPPORTED_USER_SCHEMES, String.valueOf(scheme))); } } if(unSupportedKeyxFactories!=null) { for(final KeyExchangeScheme scheme : unSupportedKeyxFactories) { nvps.add(new NameValuePair(UNSUPPORTED_KEY_EXCHANGE_SCHEMES, String.valueOf(scheme))); } } } public ServerConfiguration isMessageEncrypted(final boolean isMessageEncrypted) { this.isMessageEncrypted = isMessageEncrypted; setParameter(ENCRYPTED, String.valueOf(this.isMessageEncrypted)); return this; } public ServerConfiguration isIntegrityProtected(final boolean isIntegrityProtected) { this.isIntegrityProtected = isIntegrityProtected; setParameter(INTEGRITY_PROTECTED, String.valueOf(this.isIntegrityProtected)); return this; } public ServerConfiguration setHost(final String host) { this.host = host; return this; } public ServerConfiguration setPath(final String path) { this.path = path; return this; } public ServerConfiguration setIsNullCryptoContext(final boolean isNullCryptoContext) { this.isNullCryptoContext = isNullCryptoContext; setParameter(NULL_CRYPTO_CONTEXT, String.valueOf(this.isNullCryptoContext)); return this; } public ServerConfiguration setInitialSequenceNumber(final long initialSequenceNumber) { this.initialSequenceNum = initialSequenceNumber; setParameter(INITIAL_SEQUENCE_NUM, String.valueOf(this.initialSequenceNum)); return this; } public ServerConfiguration setSetConsoleFilterStreamFactory(final boolean setConsoleFilterStreamFactory) { this.setConsoleFilterStreamFactory = setConsoleFilterStreamFactory; setParameter(CONSOLE_FILTER_STREAM_FACTORY, String.valueOf(this.setConsoleFilterStreamFactory)); return this; } public ServerConfiguration setUnsupportedEntityAuthenticationSchemes(final List<EntityAuthenticationScheme> unSupportedEntityAuthFactories) { this.unSupportedEntityAuthFactories = unSupportedEntityAuthFactories; clearParameter(UNSUPPORTED_ENTITY_SCHEMES); if(this.unSupportedEntityAuthFactories!=null) { for(final EntityAuthenticationScheme scheme : this.unSupportedEntityAuthFactories) { nvps.add(new NameValuePair(UNSUPPORTED_ENTITY_SCHEMES, String.valueOf(scheme))); } } return this; } public ServerConfiguration setUnsupportedUserAuthenticationSchemes(final List<UserAuthenticationScheme> unSupportedUserAuthFactories) { this.unSupportedUserAuthFactories = unSupportedUserAuthFactories; clearParameter(UNSUPPORTED_USER_SCHEMES); if(this.unSupportedUserAuthFactories!=null) { for(final UserAuthenticationScheme scheme : this.unSupportedUserAuthFactories) { nvps.add(new NameValuePair(UNSUPPORTED_USER_SCHEMES, String.valueOf(scheme))); } } return this; } public ServerConfiguration setUnsupportedKeyExchangeSchemes(final List<KeyExchangeScheme> unSupportedKeyxFactories) { this.unSupportedKeyxFactories = unSupportedKeyxFactories; clearParameter(UNSUPPORTED_KEY_EXCHANGE_SCHEMES); if(this.unSupportedKeyxFactories != null) { for(final KeyExchangeScheme scheme : this.unSupportedKeyxFactories) { nvps.add(new NameValuePair(UNSUPPORTED_KEY_EXCHANGE_SCHEMES, String.valueOf(scheme))); } } return this; } public ServerConfiguration clearParameters() { nvps.clear(); return this; } public ServerConfiguration clearParameter(final String name) { if (!nvps.isEmpty()) { for (final Iterator<NameValuePair> it = nvps.iterator(); it.hasNext(); ) { final NameValuePair nvp = it.next(); if (nvp.name.equals(name)) { it.remove(); } } } return this; } public ServerConfiguration setParameter(final String name, final String value) { clearParameter(name); nvps.add(new NameValuePair(name, value)); return this; } public void commitToServer() throws URISyntaxException, IOException { final StringBuilder urlBuilder = new StringBuilder(scheme + "://" + host + path + "?"); for (final NameValuePair pair : nvps) urlBuilder.append(pair.name + "=" + pair.value + "&"); final URL url = new URL(urlBuilder.toString()); final HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.getResponseCode(); } }
2,073
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/util/ClientMslContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration.util; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.crypto.JcaAlgorithm; import com.netflix.msl.crypto.NullCryptoContext; import com.netflix.msl.crypto.SymmetricCryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.entityauth.MockPresharedAuthenticationFactory; import com.netflix.msl.entityauth.MockRsaAuthenticationFactory; import com.netflix.msl.entityauth.MockEccAuthenticationFactory; import com.netflix.msl.entityauth.MockX509AuthenticationFactory; import com.netflix.msl.entityauth.PresharedAuthenticationData; import com.netflix.msl.entityauth.RsaAuthenticationData; import com.netflix.msl.entityauth.EccAuthenticationData; import com.netflix.msl.entityauth.UnauthenticatedAuthenticationData; import com.netflix.msl.entityauth.X509AuthenticationData; import com.netflix.msl.util.MockMslContext; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * User: skommidi * Date: 7/25/14 */ public class ClientMslContext extends MockMslContext { /** MSL encryption key. */ private static final byte[] CLIENT_MSL_ENCRYPTION_KEY = { (byte)0x2d, (byte)0x58, (byte)0xf3, (byte)0xb8, (byte)0xf7, (byte)0x47, (byte)0xd1, (byte)0x6a, (byte)0xb1, (byte)0x93, (byte)0xc4, (byte)0xc0, (byte)0xa6, (byte)0x24, (byte)0xea, (byte)0xcf, }; /** MSL HMAC key. */ private static final byte[] CLIENT_MSL_HMAC_KEY = { (byte)0xe7, (byte)0xae, (byte)0xbf, (byte)0xd5, (byte)0x87, (byte)0x9b, (byte)0xb0, (byte)0xe0, (byte)0xad, (byte)0x01, (byte)0x6a, (byte)0x4c, (byte)0xf3, (byte)0xcb, (byte)0x39, (byte)0x82, (byte)0xf5, (byte)0xba, (byte)0x26, (byte)0x0d, (byte)0xa5, (byte)0x20, (byte)0x24, (byte)0x5b, (byte)0xb4, (byte)0x22, (byte)0x75, (byte)0xbd, (byte)0x79, (byte)0x47, (byte)0x37, (byte)0x0c, }; /** MSL wrapping key. */ private static final byte[] CLIENT_MSL_WRAPPING_KEY = { (byte)0x93, (byte)0xb6, (byte)0x9a, (byte)0x15, (byte)0x80, (byte)0xd3, (byte)0x23, (byte)0xa2, (byte)0xe7, (byte)0x9d, (byte)0xd9, (byte)0xb2, (byte)0x26, (byte)0x26, (byte)0xb3, (byte)0xf6, }; private final EntityAuthenticationScheme schemeUsed; private int currentRetryCount; private int maxRetryCount; /** * Create a new test MSL context. * * * @param scheme entity authentication scheme. * @param peerToPeer true if the context should operate in peer-to-peer mode. * @param nullCryptoContext true if the crypto context is supposed to be set to NullCryptoContext * @throws MslCryptoException * if there is an error signing or creating the * entity authentication data. * @throws MslEncodingException * if there is an error creating the entity * authentication data. */ public ClientMslContext(EntityAuthenticationScheme scheme, boolean peerToPeer, boolean nullCryptoContext) throws MslEncodingException, MslCryptoException { super(scheme, peerToPeer); final SecretKey mslEncryptionKey = new SecretKeySpec(CLIENT_MSL_ENCRYPTION_KEY, JcaAlgorithm.AES); final SecretKey mslHmacKey = new SecretKeySpec(CLIENT_MSL_HMAC_KEY, JcaAlgorithm.HMAC_SHA256); final SecretKey mslWrappingKey = new SecretKeySpec(CLIENT_MSL_WRAPPING_KEY, JcaAlgorithm.AESKW); if(nullCryptoContext) { mslCryptoContext = new NullCryptoContext(); } else { mslCryptoContext = new SymmetricCryptoContext(this, "TestMslKeys", mslEncryptionKey, mslHmacKey, mslWrappingKey); } setClientCryptoContext(); pskAuthData = new PresharedAuthenticationData(MockPresharedAuthenticationFactory.PSK_ESN); x509AuthData = new X509AuthenticationData(MockX509AuthenticationFactory.X509_CERT); rsaAuthData = new RsaAuthenticationData(MockRsaAuthenticationFactory.RSA_ESN, MockRsaAuthenticationFactory.RSA_PUBKEY_ID); eccAuthData = new EccAuthenticationData(MockEccAuthenticationFactory.ECC_ESN, MockEccAuthenticationFactory.ECC_PUBKEY_ID); noneAuthData = new UnauthenticatedAuthenticationData("MOCKUNAUTH-ESN-TEST"); // Server is with NONE entity authentication, to be different from server. if(EntityAuthenticationScheme.NONE.equals(scheme)) { super.setEntityAuthenticationData(noneAuthData); } schemeUsed = scheme; maxRetryCount = 0; currentRetryCount = 0; } public void setClientCryptoContext() { super.setMslCryptoContext(mslCryptoContext); } @Override public EntityAuthenticationData getEntityAuthenticationData(final ReauthCode reauthCode) { if(reauthCode == ReauthCode.ENTITYDATA_REAUTH) { if(currentRetryCount++ == maxRetryCount) { final EntityAuthenticationData entityAuthData; if (EntityAuthenticationScheme.PSK.equals(schemeUsed)) entityAuthData = pskAuthData; else if (EntityAuthenticationScheme.X509.equals(schemeUsed)) entityAuthData = x509AuthData; else if (EntityAuthenticationScheme.RSA.equals(schemeUsed)) entityAuthData = rsaAuthData; else if (EntityAuthenticationScheme.ECC.equals(schemeUsed)) entityAuthData = eccAuthData; else if (EntityAuthenticationScheme.NONE.equals(schemeUsed)) entityAuthData = noneAuthData; else throw new IllegalArgumentException("Unsupported authentication type: " + schemeUsed.name()); super.setEntityAuthenticationData(entityAuthData); } } return super.getEntityAuthenticationData(reauthCode); } /** MSL crypto context. */ private ICryptoContext mslCryptoContext; /** Entity Authentication Data */ private EntityAuthenticationData pskAuthData, x509AuthData, rsaAuthData, noneAuthData, eccAuthData; public void setMaxRetryCount(int retryCount) { maxRetryCount = retryCount; } public void resetCurrentRetryCount() { currentRetryCount = 0; } }
2,074
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/msg/TestConsoleFilterStreamFactory.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration.msg; import com.netflix.msl.msg.FilterStreamFactory; import java.io.FilterInputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * User: skommidi * Date: 8/27/14 */ public class TestConsoleFilterStreamFactory implements FilterStreamFactory { /** * A filter input stream that outputs read data to stdout. A new line is * output when the stream is closed. */ private static class ConsoleInputStream extends FilterInputStream { /** * Create a new console input stream backed by the provided input * stream. * * @param in the backing input stream. */ protected ConsoleInputStream(final InputStream in) { super(in); } /* (non-Javadoc) * @see java.io.FilterInputStream#close() */ @Override public void close() throws IOException { System.out.println(); System.out.flush(); super.close(); } /* (non-Javadoc) * @see java.io.FilterInputStream#read() */ @Override public int read() throws IOException { int c = super.read(); System.out.write(c); System.out.flush(); return c; } /* (non-Javadoc) * @see java.io.FilterInputStream#read(byte[], int, int) */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { System.out.println("==================== Client Read ===================="); int r = super.read(b, off, len); System.out.write(b, off,len); System.out.flush(); return r; } } /** * A filter output stream that outputs written data to stdout. A newline is * output when the stream is closed. */ private static class ConsoleOutputStream extends FilterOutputStream { /** * Create a new console output stream backed by the provided output * stream. * * @param out the backing output stream. */ public ConsoleOutputStream(final OutputStream out) { super(out); } /* (non-Javadoc) * @see java.io.FilterOutputStream#close() */ @Override public void close() throws IOException { System.out.println(); System.out.flush(); super.close(); } /* (non-Javadoc) * @see java.io.FilterOutputStream#write(byte[], int, int) */ @Override public void write(final byte[] b, final int off, final int len) throws IOException { System.out.println("==================== Client Write ===================="); System.out.write(b, off, len); System.out.flush(); super.write(b, off, len); } /* (non-Javadoc) * @see java.io.FilterOutputStream#write(int) */ @Override public void write(final int b) throws IOException { System.out.write(b); System.out.flush(); super.write(b); } } @Override public InputStream getInputStream(InputStream in) { return new ConsoleInputStream(in); } @Override public OutputStream getOutputStream(OutputStream out) { return new ConsoleOutputStream(out); } }
2,075
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/msg/InvalidUserAuthScheme.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration.msg; /** * User: skommidi * Date: 8/28/14 */ public enum InvalidUserAuthScheme { INVALID_EMAIL, INVALID_PASSWORD, EMPTY_EMAIL, EMPTY_PASSWORD }
2,076
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/msg/ClientMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration.msg; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.util.HashSet; import java.util.Set; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.keyx.AsymmetricWrappedExchange; import com.netflix.msl.keyx.DiffieHellmanExchange; import com.netflix.msl.keyx.DiffieHellmanParameters; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.keyx.KeyRequestData; import com.netflix.msl.keyx.MockDiffieHellmanParameters; import com.netflix.msl.keyx.SymmetricWrappedExchange; import com.netflix.msl.msg.MessageOutputStream; import com.netflix.msl.msg.MockMessageContext; import com.netflix.msl.userauth.EmailPasswordAuthenticationData; import com.netflix.msl.userauth.MockEmailPasswordAuthenticationFactory; import com.netflix.msl.userauth.UserAuthenticationData; import com.netflix.msl.userauth.UserAuthenticationScheme; import com.netflix.msl.util.MslContext; /** * User: skommidi * Date: 7/25/14 */ public class ClientMessageContext extends MockMessageContext { private final UserAuthenticationScheme schemeUsed; private int currentRetryCount; private byte[] buffer; private int maxRetryCount; private static final String RSA_KEYPAIR_ID = "rsaKeypairId"; /** * Create a new test message context. * <p/> * The message will not be encrypted or non-replayable. * * * * @param ctx MSL context. * @param userId user ID. * @param scheme user authentication scheme. * @param isMessageEncrypted * @param isIntegrityProtected * @throws NoSuchAlgorithmException * if a key generation algorithm is not * found. * @throws InvalidAlgorithmParameterException * if key generation parameters * are invalid. * @throws MslCryptoException * if the service token crypto context keys are * the wrong length. * @throws MslKeyExchangeException * if there is an error accessing Diffie- * Hellman parameters. */ public ClientMessageContext(final MslContext ctx, final String userId, final UserAuthenticationScheme scheme, final boolean isMessageEncrypted, final boolean isIntegrityProtected) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MslCryptoException, MslKeyExchangeException { super(ctx, userId, scheme); super.setEncrypted(isMessageEncrypted); super.setIntegrityProtected(isIntegrityProtected); schemeUsed = scheme; maxRetryCount = 0; currentRetryCount = 0; } public void setBuffer(final byte[] dataToWrite) { buffer = dataToWrite; } /* (non-Javadoc) * @see com.netflix.msl.msg.MockMessageContext#write(com.netflix.msl.msg.MessageOutputStream) */ @Override public void write(final MessageOutputStream output) throws IOException { output.write(buffer); output.close(); } public void setMaxRetryCount(final int maxRetryCount) { this.maxRetryCount = maxRetryCount; } public void resetCurrentRetryCount() { currentRetryCount = 0; } /* public void setInvalidUserAuthData(InvalidUserAuthScheme tags) { final UserAuthenticationData userAuthData; switch (tags) { case invalidEmail: //Invalid email userAuthData = new EmailPasswordAuthenticationData(MockEmailPasswordAuthenticationFactory.EMAIL + "test", MockEmailPasswordAuthenticationFactory.PASSWORD); break; case invalidPasswd: //Invalid passwd userAuthData = new EmailPasswordAuthenticationData(MockEmailPasswordAuthenticationFactory.EMAIL, MockEmailPasswordAuthenticationFactory.PASSWORD + "test"); break; case emptyStrEmail: //Empty str email userAuthData = new EmailPasswordAuthenticationData("", MockEmailPasswordAuthenticationFactory.PASSWORD); break; case emptyStrPasswd: //Empty str passwd userAuthData = new EmailPasswordAuthenticationData(MockEmailPasswordAuthenticationFactory.EMAIL, ""); break; default: throw new IllegalArgumentException("Unsupported user auth error type "); } super.setUserAuthData(userAuthData); } */ @Override public UserAuthenticationData getUserAuthData(final ReauthCode reauth, final boolean renewable, final boolean required) { if(reauth == ReauthCode.USERDATA_REAUTH) { if(currentRetryCount++ == maxRetryCount) { final UserAuthenticationData userAuthData; if (UserAuthenticationScheme.EMAIL_PASSWORD.equals(schemeUsed)) { userAuthData = new EmailPasswordAuthenticationData(MockEmailPasswordAuthenticationFactory.EMAIL, MockEmailPasswordAuthenticationFactory.PASSWORD); } else { throw new IllegalArgumentException("Unsupported authentication type: " + schemeUsed.name()); } super.setUserAuthData(userAuthData); } } return super.getUserAuthData(reauth, renewable, required); } public void clearKeyRequestData() { final Set<KeyRequestData> keyRequestData = new HashSet<KeyRequestData>(); super.setKeyRequestData(keyRequestData); } /** * Remove all entries and set to the specified key exchange scheme. * * @param scheme . * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException * @throws MslCryptoException */ public void resetKeyRequestData(final KeyExchangeScheme scheme) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MslCryptoException, MslKeyExchangeException { final Set<KeyRequestData> keyRequestData = new HashSet<KeyRequestData>(); // Not intending to send key request data if(scheme == null) { super.setKeyRequestData(keyRequestData); return; } if(KeyExchangeScheme.DIFFIE_HELLMAN.equals(scheme)) { final DiffieHellmanParameters params = MockDiffieHellmanParameters.getDefaultParameters(); final DHParameterSpec paramSpec = params.getParameterSpec(MockDiffieHellmanParameters.DEFAULT_ID); final KeyPairGenerator generator = KeyPairGenerator.getInstance("DH"); generator.initialize(paramSpec); final KeyPair requestKeyPair = generator.generateKeyPair(); final BigInteger publicKey = ((DHPublicKey)requestKeyPair.getPublic()).getY(); final DHPrivateKey privateKey = (DHPrivateKey)requestKeyPair.getPrivate(); keyRequestData.add(new DiffieHellmanExchange.RequestData(MockDiffieHellmanParameters.DEFAULT_ID, publicKey, privateKey)); } else if(KeyExchangeScheme.ASYMMETRIC_WRAPPED.equals(scheme)) { final KeyPairGenerator rsaGenerator = KeyPairGenerator.getInstance("RSA"); final KeyPair rsaKeyPair = rsaGenerator.generateKeyPair(); final PublicKey publicKey = rsaKeyPair.getPublic(); final PrivateKey privateKey = rsaKeyPair.getPrivate(); keyRequestData.add(new AsymmetricWrappedExchange.RequestData(RSA_KEYPAIR_ID, AsymmetricWrappedExchange.RequestData.Mechanism.JWE_RSA, publicKey, privateKey)); } else if(KeyExchangeScheme.SYMMETRIC_WRAPPED.equals(scheme)) { keyRequestData.add(new SymmetricWrappedExchange.RequestData(SymmetricWrappedExchange.KeyId.PSK)); } else { throw new IllegalArgumentException("Unsupported key exchange scheme: " + scheme.name()); } super.setKeyRequestData(keyRequestData); } }
2,077
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/keyx/TestKeyExchangeScheme.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration.keyx; import com.netflix.msl.keyx.KeyExchangeScheme; /** * User: skommidi * Date: 9/2/14 */ public class TestKeyExchangeScheme extends KeyExchangeScheme { public static final KeyExchangeScheme NULL_KEYX_SCHEME = new TestKeyExchangeScheme("NULL_KEYX_SCHEME"); /** * Define a key exchange scheme with the specified name. * * @param name the key exchange scheme name. */ protected TestKeyExchangeScheme(String name) { super(name); } }
2,078
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/tokens/TokenFactoryType.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration.tokens; /** * User: skommidi * Date: 7/21/14 */ public enum TokenFactoryType { ACCEPT_NON_REPLAYABLE_ID, NOT_ACCEPT_NON_REPLAYABLE_ID; }
2,079
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/entityauth/TestRsaAuthenticationFactory.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration.entityauth; import com.netflix.msl.MslEntityAuthException; import com.netflix.msl.MslError; import com.netflix.msl.MslInternalException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.crypto.RsaCryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.MockRsaAuthenticationFactory; import com.netflix.msl.entityauth.RsaAuthenticationData; import com.netflix.msl.util.MslContext; /** * User: skommidi * Date: 7/29/14 */ public class TestRsaAuthenticationFactory extends MockRsaAuthenticationFactory { /** RSA public key ID. */ public static final String RSA_PUBKEY_ID = "mockRSAKeyId-test"; @Override public ICryptoContext getCryptoContext(final MslContext ctx, final EntityAuthenticationData authdata) throws MslEntityAuthException { // Make sure we have the right kind of entity authentication data. if (!(authdata instanceof RsaAuthenticationData)) throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + "."); final RsaAuthenticationData rad = (RsaAuthenticationData)authdata; // Try to return the test crypto context. final String pubkeyid = rad.getPublicKeyId(); if (RSA_PUBKEY_ID.equals(pubkeyid)) { final String identity = rad.getIdentity(); return new RsaCryptoContext(ctx, identity, RSA_PRIVKEY, RSA_PUBKEY, RsaCryptoContext.Mode.SIGN_VERIFY); } if (MockRsaAuthenticationFactory.RSA_PUBKEY_ID.equals(pubkeyid)) { final String identity = rad.getIdentity(); return new RsaCryptoContext(ctx, identity, RSA_PRIVKEY, RSA_PUBKEY, RsaCryptoContext.Mode.SIGN_VERIFY); } // Entity not found. throw new MslEntityAuthException(MslError.RSA_PUBLICKEY_NOT_FOUND, pubkeyid).setEntityAuthenticationData(rad); } }
2,080
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/entityauth/TestEccAuthenticationFactory.java
/** * Copyright (c) 2016 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration.entityauth; import com.netflix.msl.MslEntityAuthException; import com.netflix.msl.MslError; import com.netflix.msl.MslInternalException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.crypto.EccCryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.MockEccAuthenticationFactory; import com.netflix.msl.entityauth.EccAuthenticationData; import com.netflix.msl.util.MslContext; public class TestEccAuthenticationFactory extends MockEccAuthenticationFactory { /** ECC public key ID. */ public static final String ECC_PUBKEY_ID = "mockECCKeyId-test"; @Override public ICryptoContext getCryptoContext(final MslContext ctx, final EntityAuthenticationData authdata) throws MslEntityAuthException { // Make sure we have the right kind of entity authentication data. if (!(authdata instanceof EccAuthenticationData)) throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + "."); final EccAuthenticationData rad = (EccAuthenticationData)authdata; // Try to return the test crypto context. final String pubkeyid = rad.getPublicKeyId(); if (ECC_PUBKEY_ID.equals(pubkeyid)) { final String identity = rad.getIdentity(); return new EccCryptoContext(identity, ECC_PRIVKEY, ECC_PUBKEY, EccCryptoContext.Mode.SIGN_VERIFY); } if (MockEccAuthenticationFactory.ECC_PUBKEY_ID.equals(pubkeyid)) { final String identity = rad.getIdentity(); return new EccCryptoContext(identity, ECC_PRIVKEY, ECC_PUBKEY, EccCryptoContext.Mode.SIGN_VERIFY); } // Entity not found. throw new MslEntityAuthException(MslError.ECC_PUBLICKEY_NOT_FOUND, pubkeyid).setEntityAuthenticationData(rad); } }
2,081
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/entityauth/ExtendedEntityAuthenticationScheme.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration.entityauth; import com.netflix.msl.entityauth.EntityAuthenticationScheme; /** * User: skommidi * Date: 7/29/14 */ public class ExtendedEntityAuthenticationScheme extends EntityAuthenticationScheme { /** * Define an entity authentication scheme with the specified name and * cryptographic properties. * * @param name the entity authentication scheme name. * @param encrypts true if the scheme encrypts message data. * @param protects true if the scheme protects message integrity. */ protected ExtendedEntityAuthenticationScheme(String name, boolean encrypts, boolean protects) { super(name, encrypts, protects); } }
2,082
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/entityauth/TestPresharedAuthenticationFactory.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration.entityauth; import com.netflix.msl.MslEntityAuthException; import com.netflix.msl.MslError; import com.netflix.msl.MslInternalException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.crypto.SymmetricCryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.entityauth.MockPresharedAuthenticationFactory; import com.netflix.msl.entityauth.PresharedAuthenticationData; import com.netflix.msl.util.MslContext; /** * User: skommidi * Date: 7/29/14 * * Test Preshared Entity Authentication Factory */ public class TestPresharedAuthenticationFactory extends MockPresharedAuthenticationFactory { /** PSK ESN. */ public static final String PSK_ESN = "PSK-ESN-TEST"; @Override public ICryptoContext getCryptoContext(final MslContext ctx, final EntityAuthenticationData authdata) throws MslEntityAuthException { // Make sure we have the right kind of entity authentication data. if (!(authdata instanceof PresharedAuthenticationData)) throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + "."); final PresharedAuthenticationData pad = (PresharedAuthenticationData)authdata; // Try to return the test crypto context. final String identity = pad.getIdentity(); if (PSK_ESN.equals(identity)) return new SymmetricCryptoContext(ctx, identity, KPE2, KPH2, KPW2); // Entity not found. throw new MslEntityAuthException(MslError.ENTITY_NOT_FOUND, "psk " + identity).setEntityAuthenticationData(pad); } }
2,083
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/configuration/entityauth/TestX509AuthenticationFactory.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.configuration.entityauth; import com.netflix.msl.entityauth.MockX509AuthenticationFactory; /** * User: skommidi * Date: 7/29/14 */ public class TestX509AuthenticationFactory extends MockX509AuthenticationFactory { /** X.509 private key. */ private static final String X509_PRIVATE_KEY = "entityauth/expired.key"; /** X.509 self-signed resource certificate. */ private static final String X509_SELF_SIGNED_CERT = "entityauth/expired.pem"; }
2,084
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/tests/UserIdTokenTests.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.tests; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.concurrent.ExecutionException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.client.common.BaseTestClass; import com.netflix.msl.client.configuration.ClientConfiguration; import com.netflix.msl.client.configuration.ServerConfiguration; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.io.MslEncoderException; import com.netflix.msl.io.Url; import com.netflix.msl.io.Url.Connection; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.tokens.MasterToken; import com.netflix.msl.tokens.UserIdToken; import com.netflix.msl.userauth.UserAuthenticationScheme; /** * User: skommidi * Date: 10/16/14 */ public class UserIdTokenTests extends BaseTestClass { private static final String PATH = "/test"; private static final int TIME_OUT = 60000; // 60 Seconds private static final String USER_ID = "userId"; @BeforeClass public void setup() throws IOException, URISyntaxException, MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException { super.loadProperties(); serverConfig = new ServerConfiguration() .resetDefaultConfig() .setHost(getRemoteEntityUrl()) .setPath(PATH); serverConfig.commitToServer(); clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.SYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); super.setServerMslCryptoContext(); } @AfterMethod public void afterTest() throws IOException { if(out != null) { out.close(); out = null;} if(in != null) { in.close(); out = null; } clientConfig.getMslContext().getMslStore().clearCryptoContexts(); } @BeforeMethod public void beforeTest() throws IOException, ExecutionException, InterruptedException { try { final Url remoteEntity = clientConfig.getRemoteEntity(); remoteEntity.setTimeout(TIME_OUT); final Connection connection = remoteEntity.openConnection(); out = connection.getOutputStream(); in = connection.getInputStream(); } catch (final IOException e) { if(out != null) out.close(); if(in != null) in.close(); throw e; } } @Test(testName = "userIdtoken happy case") public void validUserIdToken() throws InterruptedException, ExecutionException, MslException, IOException, MslEncoderException { final MasterToken masterToken = getInitialMasterToken(TIME_OUT); final Date renewalWindow = new Date(System.currentTimeMillis() + 10000); final Date expiration = new Date(System.currentTimeMillis() + 20000); final UserIdToken userIdToken = getUserIdToken(masterToken, renewalWindow, expiration, TIME_OUT); final MessageInputStream message = sendReceive(out, in, masterToken, userIdToken, null, true /*isRenewable*/, false /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final UserIdToken newUserIdToken = message.getMessageHeader().getUserIdToken(); validateUserIdTokenEqual(userIdToken, newUserIdToken, masterToken); } @Test(testName = "expired userIdToken with renewable flag set true, expect renewed userIdToken") public void expiredUserIdTokenWithRenewableTrue() throws ExecutionException, InterruptedException, MslException, IOException, MslEncoderException { final MasterToken masterToken = getInitialMasterToken(TIME_OUT); final Date renewalWindow = new Date(System.currentTimeMillis() - 20000); final Date expiration = new Date(System.currentTimeMillis() - 10000); final UserIdToken userIdToken = getUserIdToken(masterToken, renewalWindow, expiration, TIME_OUT); final MessageInputStream message = sendReceive(out, in, masterToken, userIdToken, null, true /*isRenewable*/, false /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final UserIdToken newUserIdToken = message.getMessageHeader().getUserIdToken(); validateUserIdTokenNotEqual(userIdToken, newUserIdToken, masterToken); } @Test(testName = "expired userIdToken with renewable flag set false, expect renewed userIdToken") public void expiredUserIdTokenWithRenewableFalse() throws ExecutionException, InterruptedException, MslException, IOException, MslEncoderException { final MasterToken masterToken = getInitialMasterToken(TIME_OUT); final Date renewalWindow = new Date(System.currentTimeMillis() - 20000); final Date expiration = new Date(System.currentTimeMillis() - 10000); final UserIdToken userIdToken = getUserIdToken(masterToken, renewalWindow, expiration, TIME_OUT); final MessageInputStream message = sendReceive(out, in, masterToken, userIdToken, null, false /*isRenewable*/, false /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final UserIdToken newUserIdToken = message.getMessageHeader().getUserIdToken(); validateUserIdTokenNotEqual(userIdToken, newUserIdToken, masterToken); } @Test(testName = "renewable userIdToken with renewable flag set true, expect renewed userIdToken") public void renewableUserIdTokenWithRenewableTrue() throws ExecutionException, InterruptedException, MslException, IOException, MslEncoderException { final MasterToken masterToken = getInitialMasterToken(TIME_OUT); final Date renewalWindow = new Date(System.currentTimeMillis() - 10000); final Date expiration = new Date(System.currentTimeMillis() + 10000); final UserIdToken userIdToken = getUserIdToken(masterToken, renewalWindow, expiration, TIME_OUT); final MessageInputStream message = sendReceive(out, in, masterToken, userIdToken, null, true /*isRenewable*/, false /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final UserIdToken newUserIdToken = message.getMessageHeader().getUserIdToken(); validateUserIdTokenNotEqual(userIdToken, newUserIdToken, masterToken); } @Test(testName = "renewable userIdToken with renewable flag set false, expect renewed userIdToken") public void renewableUserIdTokenWithRenewableFalse() throws ExecutionException, InterruptedException, MslException, IOException, MslEncoderException { final MasterToken masterToken = getInitialMasterToken(TIME_OUT); final Date renewalWindow = new Date(System.currentTimeMillis() - 10000); final Date expiration = new Date(System.currentTimeMillis() + 10000); final UserIdToken userIdToken = getUserIdToken(masterToken, renewalWindow, expiration, TIME_OUT); final MessageInputStream message = sendReceive(out, in, masterToken, userIdToken, null, false /*isRenewable*/, false /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final UserIdToken newUserIdToken = message.getMessageHeader().getUserIdToken(); validateUserIdTokenEqual(userIdToken, newUserIdToken, masterToken); } private void validateUserIdTokenEqual(final UserIdToken userIdToken, final UserIdToken newUserIdToken, final MasterToken masterToken) { final Date now = new Date(); assertEquals(newUserIdToken.getSerialNumber(), userIdToken.getSerialNumber()); assertEquals(newUserIdToken.getMasterTokenSerialNumber(), userIdToken.getMasterTokenSerialNumber()); assertTrue(newUserIdToken.getExpiration().after(newUserIdToken.getRenewalWindow())); assertEquals(newUserIdToken.getRenewalWindow(), userIdToken.getRenewalWindow()); assertEquals(newUserIdToken.getExpiration(), userIdToken.getExpiration()); assertTrue(newUserIdToken.isBoundTo(masterToken)); assertFalse(newUserIdToken.isVerified()); assertFalse(newUserIdToken.isDecrypted()); assertTrue(newUserIdToken.isExpired(now) == userIdToken.isExpired(now)); assertTrue(newUserIdToken.isRenewable(now) == userIdToken.isRenewable(now)); } private void validateUserIdTokenNotEqual(final UserIdToken userIdToken, final UserIdToken newUserIdToken, final MasterToken masterToken) { final Date now = new Date(); assertEquals(newUserIdToken.getSerialNumber(), userIdToken.getSerialNumber()); assertEquals(newUserIdToken.getMasterTokenSerialNumber(), userIdToken.getMasterTokenSerialNumber()); assertTrue(newUserIdToken.getExpiration().after(newUserIdToken.getRenewalWindow())); assertTrue(newUserIdToken.getRenewalWindow().after(userIdToken.getRenewalWindow())); assertTrue(newUserIdToken.getExpiration().compareTo(userIdToken.getExpiration()) > 0); assertTrue(newUserIdToken.isBoundTo(masterToken)); assertFalse(newUserIdToken.isVerified()); assertFalse(newUserIdToken.isDecrypted()); assertFalse(newUserIdToken.isExpired(now)); assertFalse(newUserIdToken.isRenewable(now)); //User is not able to decrypt the customer information } private ServerConfiguration serverConfig; private final int numThreads = 0; private OutputStream out; private InputStream in; }
2,085
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/tests/ServiceTokenTests.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.tests; import static org.testng.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.Set; import java.util.concurrent.ExecutionException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.client.common.BaseTestClass; import com.netflix.msl.client.configuration.ClientConfiguration; import com.netflix.msl.client.configuration.ServerConfiguration; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.io.MslEncoderException; import com.netflix.msl.io.Url; import com.netflix.msl.io.Url.Connection; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.tokens.MasterToken; import com.netflix.msl.tokens.ServiceToken; import com.netflix.msl.tokens.UserIdToken; import com.netflix.msl.userauth.UserAuthenticationScheme; import com.netflix.msl.util.MslStore; /** * User: skommidi * Date: 10/17/14 */ public class ServiceTokenTests extends BaseTestClass { private static final String PATH = "/test"; private static final int TIME_OUT = 60000; // 60 Seconds private static final String USER_ID = "userId"; @BeforeClass public void setup() throws IOException, URISyntaxException, MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException { super.loadProperties(); serverConfig = new ServerConfiguration() .resetDefaultConfig() .setHost(getRemoteEntityUrl()) .setPath(PATH); serverConfig.commitToServer(); clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.SYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); super.setServerMslCryptoContext(); } @AfterMethod public void afterTest() throws IOException { if(out != null) { out.close(); out = null;} if(in != null) { in.close(); out = null; } final MslStore store = clientConfig.getMslContext().getMslStore(); store.clearCryptoContexts(); store.clearServiceTokens(); store.clearUserIdTokens(); } @BeforeMethod public void beforeTest() throws IOException, ExecutionException, InterruptedException { try { final Url remoteEntity = clientConfig.getRemoteEntity(); remoteEntity.setTimeout(TIME_OUT); final Connection connection = remoteEntity.openConnection(); out = connection.getOutputStream(); in = connection.getInputStream(); } catch (final IOException e) { if(out != null) out.close(); if(in != null) in.close(); throw e; } } @DataProvider(name = "ServiceTokenTypes") public Object[][] testDataServiceTokenTypes() { return new Object[][] { {ServiceTokenType.BOTH, true}, {ServiceTokenType.MASTER_BOUND, true}, {ServiceTokenType.BOTH, false}, {ServiceTokenType.MASTER_BOUND, false}, }; } @Test(groups = "UnboundServiceTokenTests") public void unboundServiceTokenWithData() throws InterruptedException, ExecutionException, MslException, IOException, MslEncoderException { final MasterToken masterToken = getMasterToken(new Date(System.currentTimeMillis() + 10000) /*renewableWindow*/, new Date(System.currentTimeMillis() + 20000) /*expiration*/, TIME_OUT, 0 /*sequenceNumberOffset*/); // Create an expired userId token final UserIdToken userIdToken = getUserIdToken(masterToken, new Date(System.currentTimeMillis() + 10000) /*renewableWindow*/, new Date(System.currentTimeMillis() + 20000) /*expiration*/, TIME_OUT); final Set<ServiceToken> serviceTokens = getServiceToken(masterToken, userIdToken, ServiceTokenType.NONE, true); final MessageInputStream message = sendReceive(out, in, masterToken, userIdToken, serviceTokens, false /*isRenewable*/, false /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final Set<ServiceToken> returnedServiceTokens = message.getMessageHeader().getServiceTokens(); assertEquals(returnedServiceTokens.size(), 1, "Numner of returned service tokens != sent service tokens"); assertEquals(serviceTokens, returnedServiceTokens, "Retured service tokens are not the same as the sent"); } @Test(dependsOnMethods = "unboundServiceTokenWithData", groups = "UnboundServiceTokenTests") public void testUnboundServiceTokenWithoutData() throws InterruptedException, ExecutionException, MslException, IOException, MslEncoderException { final MasterToken masterToken = getMasterToken(new Date(System.currentTimeMillis() + 10000) /*renewableWindow*/, new Date(System.currentTimeMillis() + 20000) /*expiration*/, TIME_OUT, 0 /*sequenceNumberOffset*/); // Create an expired userId token final UserIdToken userIdToken = getUserIdToken(masterToken, new Date(System.currentTimeMillis() + 10000) /*renewableWindow*/, new Date(System.currentTimeMillis() + 20000) /*expiration*/, TIME_OUT); final Set<ServiceToken> serviceTokens = getServiceToken(masterToken, userIdToken, ServiceTokenType.NONE, false); final MessageInputStream message = sendReceive(out, in, masterToken, userIdToken, serviceTokens, false /*isRenewable*/, false /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final Set<ServiceToken> returnedServiceTokens = message.getMessageHeader().getServiceTokens(); assertEquals(returnedServiceTokens.size(), 1, "Numner of returned service tokens != sent service tokens"); assertEquals(serviceTokens, returnedServiceTokens, "Retured service tokens are not the same as the sent"); } @Test(testName = "service token test", dataProvider = "ServiceTokenTypes", dependsOnGroups = "UnboundServiceTokenTests") public void boundServiceToken(final ServiceTokenType serviceTokenType, final boolean withData) throws InterruptedException, ExecutionException, MslException, IOException, MslEncoderException { final MasterToken masterToken = getMasterToken(new Date(System.currentTimeMillis() + 10000) /*renewableWindow*/, new Date(System.currentTimeMillis() + 20000) /*expiration*/, TIME_OUT, 0 /*sequenceNumberOffset*/); // Create an expired userId token final UserIdToken userIdToken = getUserIdToken(masterToken, new Date(System.currentTimeMillis() + 10000) /*renewableWindow*/, new Date(System.currentTimeMillis() + 20000) /*expiration*/, TIME_OUT); final Set<ServiceToken> serviceTokens = getServiceToken(masterToken, userIdToken, serviceTokenType, withData); final MessageInputStream message = sendReceive(out, in, masterToken, userIdToken, serviceTokens, false /*isRenewable*/, false /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final Set<ServiceToken> returnedServiceTokens = message.getMessageHeader().getServiceTokens(); assertEquals(returnedServiceTokens.size(), 1, "Numner of returned service tokens != sent service tokens"); assertEquals(serviceTokens, returnedServiceTokens, "Retured service tokens are not the same as the sent"); } private ServerConfiguration serverConfig; private final int numThreads = 0; private OutputStream out; private InputStream in; }
2,086
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/tests/MasterTokenTests.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.tests; import static org.testng.Assert.assertTrue; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.concurrent.ExecutionException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.client.common.BaseTestClass; import com.netflix.msl.client.configuration.ClientConfiguration; import com.netflix.msl.client.configuration.ServerConfiguration; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.io.MslEncoderException; import com.netflix.msl.io.Url; import com.netflix.msl.io.Url.Connection; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.tokens.MasterToken; import com.netflix.msl.userauth.UserAuthenticationScheme; /** * User: skommidi * Date: 10/13/14 */ public class MasterTokenTests extends BaseTestClass { private static final String PATH = "/test"; private static final int TIME_OUT = 60000; // 60 Seconds private static final String USER_ID = "userId"; @BeforeClass public void setup() throws IOException, URISyntaxException, MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException { super.loadProperties(); serverConfig = new ServerConfiguration() .resetDefaultConfig() .setHost(getRemoteEntityUrl()) .setPath(PATH); serverConfig.commitToServer(); clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.SYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); super.setServerMslCryptoContext(); } @AfterMethod public void afterTest() throws IOException { if(out != null) { out.close(); out = null;} if(in != null) { in.close(); out = null; } clientConfig.getMslContext().getMslStore().clearCryptoContexts(); } @BeforeMethod public void beforeTest() throws IOException, ExecutionException, InterruptedException { try { final Url remoteEntity = clientConfig.getRemoteEntity(); remoteEntity.setTimeout(TIME_OUT); final Connection connection = remoteEntity.openConnection(); out = connection.getOutputStream(); in = connection.getInputStream(); } catch (final IOException e) { if(out != null) out.close(); if(in != null) in.close(); throw e; } } @Test(testName = "mastertoken happy case") public void validMasterToken() throws InterruptedException, ExecutionException, MslException, IOException, MslEncoderException { final Date renewalWindow = new Date(System.currentTimeMillis() + 10000); final Date expiration = new Date(System.currentTimeMillis() + 20000); final MasterToken masterToken = getMasterToken(renewalWindow, expiration, TIME_OUT, 0 /*sequenceNumberOffset*/); final MessageInputStream message = sendReceive(out, in, masterToken, null, null, true /*isRenewable*/, false /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final MasterToken newMasterToken = message.getMessageHeader().getMasterToken(); validateMasterTokenEquals(masterToken, newMasterToken); } @Test(testName = "expired master token, with renewable set true, expect renewed master token") public void expiredMasterTokenRenewable() throws InterruptedException, ExecutionException, MslException, IOException, MslEncoderException { final Date renewalWindow = new Date(System.currentTimeMillis() - 20000); final Date expiration = new Date(System.currentTimeMillis() - 10000); final MasterToken masterToken = getMasterToken(renewalWindow, expiration, TIME_OUT, 0 /*sequenceNumberOffset*/); final MessageInputStream message = sendReceive(out, in, masterToken, null, null, true /*isRenewable*/, true /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final MasterToken newMasterToken = message.getMessageHeader().getKeyResponseData().getMasterToken(); validateMasterTokenNotEquals(masterToken, newMasterToken); } @Test(testName = "expired master token, with renewable flag set false") public void expiredMasterTokenNonRenewable() throws InterruptedException, ExecutionException, MslException, IOException, MslEncoderException { final Date renewalWindow = new Date(System.currentTimeMillis() - 20000); final Date expiration = new Date(System.currentTimeMillis() - 10000); final MasterToken masterToken = getMasterToken(renewalWindow, expiration, TIME_OUT, 0 /*sequenceNumberOffset*/); final MessageInputStream message = sendReceive(out, in, masterToken, null, null, false /*isRenewable*/, true /*addKeyRequestData*/); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.EXPIRED); } @Test(testName = "renewable master token, with sequence number out of range") public void renewableMasterTokenSequenceNumOutOfRangeError() throws InterruptedException, ExecutionException, MslException, IOException, MslEncoderException { final Date renewalWindow = new Date(System.currentTimeMillis() - 10000); final Date expiration = new Date(System.currentTimeMillis() + 10000); final MasterToken masterToken = getMasterToken(renewalWindow, expiration, TIME_OUT, 33 /*sequenceNumberOffset*/); final MessageInputStream message = sendReceive(out, in, masterToken, null, null, true /*isRenewable*/, true /*addKeyRequestData*/); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.ENTITY_REAUTH); } @Test(testName = "renewable master token") public void renewableMasterTokenWithRenewableTrue() throws InterruptedException, ExecutionException, MslException, IOException, MslEncoderException { final Date renewalWindow = new Date(System.currentTimeMillis() - 10000); final Date expiration = new Date(System.currentTimeMillis() + 10000); final MasterToken masterToken = getMasterToken(renewalWindow, expiration, TIME_OUT, 0 /*sequenceNumberOffset*/); final MessageInputStream message = sendReceive(out, in, masterToken, null, null, true /*isRenewable*/, true /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final MasterToken newMasterToken = message.getMessageHeader().getKeyResponseData().getMasterToken(); validateMasterTokenNotEquals(masterToken, newMasterToken); } @Test(testName = "renewable master token") public void renewableMasterTokenWithRenewableFalse() throws InterruptedException, ExecutionException, MslException, IOException, MslEncoderException { final Date renewalWindow = new Date(System.currentTimeMillis() - 10000); final Date expiration = new Date(System.currentTimeMillis() + 10000); final MasterToken masterToken = getMasterToken(renewalWindow, expiration, TIME_OUT, 0 /*sequenceNumberOffset*/); final MessageInputStream message = sendReceive(out, in, masterToken, null, null, false /*isRenewable*/, true /*addKeyRequestData*/); thenThe(message) .shouldHave().validBuffer(); final MasterToken newMasterToken = message.getMessageHeader().getMasterToken(); validateMasterTokenEquals(masterToken, newMasterToken); } //@Test(testName = "replayed master token") public void testReplayedMasterTokenWithoutKeyRequestData() throws InterruptedException, ExecutionException, MslException, NoSuchAlgorithmException, IOException, InvalidAlgorithmParameterException, URISyntaxException, MslEncoderException { clientConfig.setMessageNonReplayable(true) .commitConfiguration(); final Date renewalWindow = new Date(System.currentTimeMillis() + 10000); // Renewable in the past final Date expiration = new Date(System.currentTimeMillis() + 20000); // Expiration in the past final MasterToken masterToken = getMasterToken(renewalWindow, expiration, TIME_OUT, 0 /*sequenceNumberOffset*/); final MessageInputStream message = sendReceive(out, in, masterToken, null, null, true /*isRenewable*/, false /*addKeyRequestData*/); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.REPLAYED); } private void validateMasterTokenNotEquals(final MasterToken masterToken, final MasterToken newMasterToken) { assertTrue(newMasterToken.isNewerThan(masterToken), "New masterToken is not newer than old masterToken."); assertTrue(newMasterToken.getSequenceNumber() > masterToken.getSequenceNumber(), "New sequence number is not greater than old sequence number."); assertTrue(newMasterToken.getRenewalWindow().after(new Date(System.currentTimeMillis())), "New renewal window timestamp is not after current timestamp"); assertTrue(newMasterToken.getExpiration().after(new Date(System.currentTimeMillis())), "New expiration timestamp is not after current timestamp"); assertTrue(newMasterToken.getExpiration().after(newMasterToken.getRenewalWindow()), "New expiration timestamp is not after new renewal window timestamp"); } private void validateMasterTokenEquals(final MasterToken masterToken, final MasterToken newMasterToken) { assertTrue(newMasterToken.getSequenceNumber() == masterToken.getSequenceNumber(), "New sequence number is expected to be equal to old sequence number."); assertTrue(newMasterToken.getRenewalWindow().equals(masterToken.getRenewalWindow()), "New renewal window timestamp is expected to be equal to old renewal window timestamp"); assertTrue(newMasterToken.getExpiration().equals(masterToken.getExpiration()), "New expiration timestamp is expected to be equal to old expiration timestamp"); assertTrue(newMasterToken.getExpiration().after(newMasterToken.getRenewalWindow()), "New expiration timestamp is not after new renewal window timestamp"); } private final int numThreads = 0; private ServerConfiguration serverConfig; private OutputStream out; private InputStream in; }
2,087
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/tests/UserAuthTests.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.tests; import java.io.IOException; import java.net.URISyntaxException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.ExecutionException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.client.common.BaseTestClass; import com.netflix.msl.client.configuration.ClientConfiguration; import com.netflix.msl.client.configuration.ServerConfiguration; import com.netflix.msl.client.configuration.msg.InvalidUserAuthScheme; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.userauth.UserAuthenticationScheme; /** * User: skommidi * Date: 8/28/14 */ public class UserAuthTests extends BaseTestClass { private static final int TIME_OUT = 60000; // 60 Seconds private final int numThreads = 0; private ServerConfiguration serverConfig; private static final String PATH = "/test"; private static final String USER_ID = "userId"; @BeforeClass public void setup() throws IOException, URISyntaxException { super.loadProperties(); serverConfig = new ServerConfiguration() .setHost(getRemoteEntityUrl()) .setPath(PATH); serverConfig.commitToServer(); } @Test(testName = "Valid User Auth - EMAIL_PASSWORD") public void validUserAuthEmailPassword() throws MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, InvalidAlgorithmParameterException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.NONE) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.DIFFIE_HELLMAN); clientConfig.commitConfiguration(); final MessageInputStream message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validFirstEntityAuthNONEMsg() .shouldHave().validBuffer(); } @Test(testName = "Invalid Email User Auth - EMAIL_PASSWORD") public void invalidEmailUserAuthEmailPassword() throws MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, InvalidAlgorithmParameterException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setInvalidUserAuthData(InvalidUserAuthScheme.INVALID_EMAIL) .setMaxUserAuthRetryCount(5) .resetCurrentUserAuthRetryCount() .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); final MessageInputStream message = sendReceive(TIME_OUT); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.USERDATA_REAUTH); } @Test(testName = "Invalid Password User Auth - EMAIL_PASSWORD") public void invalidPasswordUserAuthEmailPassword() throws MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, InvalidAlgorithmParameterException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setInvalidUserAuthData(InvalidUserAuthScheme.INVALID_PASSWORD) .setMaxUserAuthRetryCount(5) .resetCurrentUserAuthRetryCount() .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); final MessageInputStream message = sendReceive(TIME_OUT); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.USERDATA_REAUTH); } @Test(testName = "Empty Email User Auth - EMAIL_PASSWORD") public void emptyEmailUserAuthEmailPassword() throws MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, InvalidAlgorithmParameterException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setInvalidUserAuthData(InvalidUserAuthScheme.EMPTY_EMAIL) .setMaxUserAuthRetryCount(5) .resetCurrentUserAuthRetryCount() .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); final MessageInputStream message = sendReceive(TIME_OUT); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.USERDATA_REAUTH); } @Test(testName = "Empty Password User Auth - EMAIL_PASSWORD") public void emptyPasswordUserAuthEmailPassword() throws MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, InvalidAlgorithmParameterException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setInvalidUserAuthData(InvalidUserAuthScheme.EMPTY_PASSWORD) .setMaxUserAuthRetryCount(5) .resetCurrentUserAuthRetryCount() .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); final MessageInputStream message = sendReceive(TIME_OUT); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.USERDATA_REAUTH); } @Test(testName = "Null User Auth - EMAIL_PASSWORD") public void nullUserAuthEmailPassword() throws MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, InvalidAlgorithmParameterException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.NONE) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.DIFFIE_HELLMAN) .setNullUserAuthData(); clientConfig.commitConfiguration(); MessageInputStream message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validFirstEntityAuthNONEMsg(clientConfig.isSetNullUserAuthData()) .shouldHave().validBuffer(); message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validateSecondMsg(clientConfig.isSetNullUserAuthData()) .shouldHave().validBuffer(); } @Test public void invalidUserAuthEmailPasswordBadToGood() throws MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, InvalidAlgorithmParameterException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.X509) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setInvalidUserAuthData(InvalidUserAuthScheme.INVALID_EMAIL) .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED) .setMaxUserAuthRetryCount(2) .resetCurrentUserAuthRetryCount(); clientConfig.commitConfiguration(); final MessageInputStream message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validFirstEntityAuthX509Msg() .shouldHave().validBuffer(); } }
2,088
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/tests/PushTests.java
/** * Copyright (c) 2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.tests; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.junit.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.netflix.msl.MslConstants; import com.netflix.msl.MslConstants.ResponseCode; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.client.common.BaseTestClass; import com.netflix.msl.client.configuration.ClientConfiguration; import com.netflix.msl.client.configuration.msg.ClientMessageContext; import com.netflix.msl.client.configuration.util.ClientMslContext; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.entityauth.UnauthenticatedAuthenticationData; import com.netflix.msl.io.Url; import com.netflix.msl.io.Url.Connection; import com.netflix.msl.msg.ConsoleFilterStreamFactory; import com.netflix.msl.msg.ErrorHeader; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.msg.MessageOutputStream; import com.netflix.msl.msg.MslControl; /** * <p>Tests of the {@link MslControl} push methods.</p> * * @author Wesley Miaw <[email protected]> */ public class PushTests extends BaseTestClass { /** Local entity identity. */ private static final String ENTITY_IDENTITY = "push-test"; /** Network timeout in milliseconds. */ private static final int TIMEOUT = 60000; public void init(final String path) throws URISyntaxException, IOException, MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(path) .setNumThreads(0) .setEntityAuthenticationScheme(EntityAuthenticationScheme.NONE); clientConfig.commitConfiguration(); super.setServerMslCryptoContext(); } @BeforeClass public void setup() throws IOException { super.loadProperties(); } @Test public void publicPush() throws MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException, URISyntaxException, IOException, InterruptedException, ExecutionException { // Initalize. init("/public-push"); // Prepare. final MslControl ctrl = clientConfig.getMslControl(); final ClientMslContext ctx = clientConfig.getMslContext(); ctx.setEntityAuthenticationData(new UnauthenticatedAuthenticationData(ENTITY_IDENTITY)); clientConfig .setIsMessageEncrypted(false) .setIsIntegrityProtected(false) .clearKeyRequestData() .commitConfiguration(); final ClientMessageContext msgCtx = clientConfig.getMessageContext(); final Url remoteEntity = clientConfig.getRemoteEntity(); // Open connection. final Connection conn = remoteEntity.openConnection(); final InputStream in = conn.getInputStream(); final OutputStream out = conn.getOutputStream(); // Send message. final byte[] output = new byte[16]; ctx.getRandom().nextBytes(output); msgCtx.setBuffer(output); final Future<MessageOutputStream> send = ctrl.send(ctx, msgCtx, in, out, TIMEOUT); final MessageOutputStream mos = send.get(); Assert.assertNotNull(mos); // Receive message. // // We expect to receive the output data back. final Future<MessageInputStream> receive = ctrl.receive(ctx, msgCtx, in, out, TIMEOUT); final MessageInputStream mis = receive.get(); Assert.assertNotNull(mis); Assert.assertNotNull(mis.getMessageHeader()); final ByteArrayOutputStream input = new ByteArrayOutputStream(); do { final byte[] b = new byte[output.length]; final int count = mis.read(b); if (count == -1) break; input.write(b, 0, count); } while (true); // Confirm data. Assert.assertArrayEquals(output, input.toByteArray()); } @Test public void secretPush() throws MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException, URISyntaxException, IOException, InterruptedException, ExecutionException { // Initalize. init("/secret-push"); // Prepare. final MslControl ctrl = clientConfig.getMslControl(); final ClientMslContext ctx = clientConfig.getMslContext(); ctx.setEntityAuthenticationData(new UnauthenticatedAuthenticationData(ENTITY_IDENTITY)); clientConfig .setIsMessageEncrypted(false) .setIsIntegrityProtected(false) .clearKeyRequestData() .commitConfiguration(); final ClientMessageContext msgCtx = clientConfig.getMessageContext(); final Url remoteEntity = clientConfig.getRemoteEntity(); // Open connection. final Connection conn = remoteEntity.openConnection(); final InputStream in = conn.getInputStream(); final OutputStream out = conn.getOutputStream(); // Send message. final byte[] output = new byte[16]; ctx.getRandom().nextBytes(output); msgCtx.setBuffer(output); final Future<MessageOutputStream> send = ctrl.send(ctx, msgCtx, in, out, TIMEOUT); final MessageOutputStream mos = send.get(); Assert.assertNotNull(mos); // Receive message. // // We expect to receive an error indicating key exchange is required. final Future<MessageInputStream> receive = ctrl.receive(ctx, msgCtx, in, out, TIMEOUT); final MessageInputStream mis = receive.get(); Assert.assertNotNull(mis); final ErrorHeader errorHeader = mis.getErrorHeader(); Assert.assertNotNull(errorHeader); final ResponseCode responseCode = errorHeader.getErrorCode(); Assert.assertEquals(MslConstants.ResponseCode.KEYX_REQUIRED, responseCode); } @Test public void multiPush() throws MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException, URISyntaxException, IOException, InterruptedException, ExecutionException { // Initalize. init("/multi-push"); // Prepare. final MslControl ctrl = clientConfig.getMslControl(); ctrl.setFilterFactory(new ConsoleFilterStreamFactory()); final ClientMslContext ctx = clientConfig.getMslContext(); ctx.setEntityAuthenticationData(new UnauthenticatedAuthenticationData(ENTITY_IDENTITY)); clientConfig .setIsMessageEncrypted(false) .setIsIntegrityProtected(false) .clearKeyRequestData() .commitConfiguration(); final ClientMessageContext msgCtx = clientConfig.getMessageContext(); final Url remoteEntity = clientConfig.getRemoteEntity(); // Open connection. final Connection conn = remoteEntity.openConnection(); final InputStream in = conn.getInputStream(); final OutputStream out = conn.getOutputStream(); // Send message. final byte[] output = new byte[16]; ctx.getRandom().nextBytes(output); msgCtx.setBuffer(output); final Future<MessageOutputStream> send = ctrl.send(ctx, msgCtx, in, out, TIMEOUT); final MessageOutputStream mos = send.get(); Assert.assertNotNull(mos); // Receive message. // // We expect to receive the output data back three times. for (int i = 0; i < 3; i++) { final Future<MessageInputStream> receive = ctrl.receive(ctx, msgCtx, in, out, TIMEOUT); final MessageInputStream mis = receive.get(); Assert.assertNotNull(mis); Assert.assertNotNull(mis.getMessageHeader()); final ByteArrayOutputStream input = new ByteArrayOutputStream(); do { final byte[] b = new byte[output.length]; final int count = mis.read(b); if (count == -1) break; input.write(b, 0, count); } while (true); // Confirm data. Assert.assertArrayEquals(output, input.toByteArray()); } } }
2,089
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/tests/EntityAuthTests.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.tests; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.io.IOException; import java.net.URISyntaxException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.ExecutionException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslError; import com.netflix.msl.MslException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.client.common.BaseTestClass; import com.netflix.msl.client.configuration.ClientConfiguration; import com.netflix.msl.client.configuration.ServerConfiguration; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.userauth.UserAuthenticationScheme; /** * User: skommidi * Date: 7/25/14 */ public class EntityAuthTests extends BaseTestClass { private final int numThreads = 0; private ServerConfiguration serverConfig = null; private static final int TIME_OUT = 60000; //60 seconds private static final String PATH = "/test"; private static final String USER_ID = "userId"; private static final String INVALID_ENTITY_IDENTITY = "invalidEntityIdentity"; @BeforeMethod public void setup() throws IOException, URISyntaxException { if (serverConfig == null) { super.loadProperties(); serverConfig = new ServerConfiguration() .setHost(getRemoteEntityUrl()) .setPath(PATH); serverConfig.commitToServer(); } } @Test(testName = "Correct Remote Entity Identity") public void correctRemoteEntityIdentity() throws MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException, URISyntaxException, IOException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setIsPeerToPeer(false) // FIXME There should be a better way to know the remote entity identity for this test. .setRemoteEntityIdentity("MOCKUNAUTH-ESN") .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.SYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); MessageInputStream message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validFirstEntityAuthPSKMsg() .shouldHave().validBuffer(); message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validateSecondMsg() .shouldHave().validBuffer(); } @Test(testName = "Incorrect Remote Entity Identity") public void incorrectRemoteEntityIdentity() throws MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException, URISyntaxException, IOException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setIsPeerToPeer(false) .setRemoteEntityIdentity(INVALID_ENTITY_IDENTITY) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.SYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); try { sendReceive(TIME_OUT); } catch (final ExecutionException e) { final Throwable cause = e.getCause(); assertTrue(cause instanceof MslException); final MslException me = (MslException)cause; assertEquals(MslError.MESSAGE_SENDER_MISMATCH, me.getError()); } } /** * * * @throws MslEncodingException * @throws InvalidAlgorithmParameterException * @throws NoSuchAlgorithmException * @throws MslCryptoException * @throws URISyntaxException * @throws ExecutionException * @throws InterruptedException * @throws IOException * @throws MslKeyExchangeException */ @Test(testName = "Valid Entity Auth - PSK") public void validEntityAuthPSK() throws MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslCryptoException, URISyntaxException, ExecutionException, InterruptedException, IOException, MslKeyExchangeException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.SYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); MessageInputStream message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validFirstEntityAuthPSKMsg() .shouldHave().validBuffer(); message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validateSecondMsg() .shouldHave().validBuffer(); } /** * * * @throws MslEncodingException * @throws InvalidAlgorithmParameterException * @throws NoSuchAlgorithmException * @throws MslCryptoException * @throws URISyntaxException * @throws ExecutionException * @throws InterruptedException * @throws IOException * @throws MslKeyExchangeException */ @Test(testName = "Invalid Entity Auth - PSK") public void invalidEntityAuthPSK() throws MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslCryptoException, URISyntaxException, ExecutionException, InterruptedException, IOException, MslKeyExchangeException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setInvalidEntityAuthData() .setMaxEntityAuthRetryCount(4) .resetCurrentEntityAuthRetryCount() .setIsPeerToPeer(false) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.SYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); final MessageInputStream message = sendReceive(TIME_OUT); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.FAIL); } /** * * * @throws InvalidAlgorithmParameterException * @throws MslEncodingException * @throws NoSuchAlgorithmException * @throws IOException * @throws MslCryptoException * @throws URISyntaxException * @throws MslKeyExchangeException * @throws ExecutionException * @throws InterruptedException */ @Test(testName = "Valid Entity Auth - RSA") public void validEntityAuthRSA() throws InvalidAlgorithmParameterException, MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.RSA) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); MessageInputStream message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validFirstEntityAuthRSAMsg() .shouldHave().validBuffer(); message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validateSecondMsg() .shouldHave().validBuffer(); } /** * * @throws InvalidAlgorithmParameterException * @throws MslEncodingException * @throws NoSuchAlgorithmException * @throws IOException * @throws MslCryptoException * @throws URISyntaxException * @throws MslKeyExchangeException * @throws ExecutionException * @throws InterruptedException */ @Test(testName = "Invalid Entity Auth - RSA") public void invalidEntityAuthRSA() throws InvalidAlgorithmParameterException, MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.RSA) .setInvalidEntityAuthData() .setMaxEntityAuthRetryCount(5) .resetCurrentEntityAuthRetryCount() .setIsPeerToPeer(false) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); final MessageInputStream message = sendReceive(TIME_OUT); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.ENTITYDATA_REAUTH); } /** * * @throws InvalidAlgorithmParameterException * @throws MslEncodingException * @throws NoSuchAlgorithmException * @throws IOException * @throws MslCryptoException * @throws URISyntaxException * @throws MslKeyExchangeException * @throws ExecutionException * @throws InterruptedException */ @Test(testName = "Entity Auth RSA, Bad -> Good") public void invalidEntityAuthRSABadToGood() throws InvalidAlgorithmParameterException, MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.RSA) .setInvalidEntityAuthData() //Retry Count after which it will send good entity auth data. .setMaxEntityAuthRetryCount(2) .resetCurrentEntityAuthRetryCount() .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); final MessageInputStream message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validFirstEntityAuthRSAMsg() .shouldHave().validBuffer(); } /** * * * @throws InvalidAlgorithmParameterException * @throws MslEncodingException * @throws NoSuchAlgorithmException * @throws IOException * @throws MslCryptoException * @throws URISyntaxException * @throws MslKeyExchangeException * @throws ExecutionException * @throws InterruptedException */ @Test(testName = "Valid Entity Auth - ECC") public void validEntityAuthECC() throws InvalidAlgorithmParameterException, MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.ECC) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); MessageInputStream message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validFirstEntityAuthECCMsg() .shouldHave().validBuffer(); message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validateSecondMsg() .shouldHave().validBuffer(); } /** * * @throws InvalidAlgorithmParameterException * @throws MslEncodingException * @throws NoSuchAlgorithmException * @throws IOException * @throws MslCryptoException * @throws URISyntaxException * @throws MslKeyExchangeException * @throws ExecutionException * @throws InterruptedException */ @Test(testName = "Invalid Entity Auth - ECC") public void invalidEntityAuthECC() throws InvalidAlgorithmParameterException, MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.ECC) .setInvalidEntityAuthData() .setMaxEntityAuthRetryCount(5) .resetCurrentEntityAuthRetryCount() .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); final MessageInputStream message = sendReceive(TIME_OUT); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.ENTITYDATA_REAUTH); } /** * * * @throws InvalidAlgorithmParameterException * @throws MslEncodingException * @throws NoSuchAlgorithmException * @throws IOException * @throws MslCryptoException * @throws URISyntaxException * @throws MslKeyExchangeException * @throws ExecutionException * @throws InterruptedException */ @Test(testName = "Valid Entity Auth - X509") public void validEntityAuthX509() throws InvalidAlgorithmParameterException, MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.X509) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.DIFFIE_HELLMAN); clientConfig.commitConfiguration(); MessageInputStream message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validFirstEntityAuthX509Msg() .shouldHave().validBuffer(); message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validateSecondMsg() .shouldHave().validBuffer(); } /** * * @throws InvalidAlgorithmParameterException * @throws MslEncodingException * @throws NoSuchAlgorithmException * @throws IOException * @throws MslCryptoException * @throws URISyntaxException * @throws MslKeyExchangeException * @throws ExecutionException * @throws InterruptedException */ //@Test(testName = "Invalid Entity Auth - X509") public void invalidEntityAuthX509() throws InvalidAlgorithmParameterException, MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.X509) .setInvalidEntityAuthData() .setMaxEntityAuthRetryCount(5) .resetCurrentEntityAuthRetryCount() .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); final MessageInputStream message = sendReceive(TIME_OUT); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.ENTITYDATA_REAUTH); } /** * * * @throws InvalidAlgorithmParameterException * @throws MslEncodingException * @throws NoSuchAlgorithmException * @throws IOException * @throws MslCryptoException * @throws URISyntaxException * @throws MslKeyExchangeException * @throws ExecutionException * @throws InterruptedException */ @Test(testName = "Valid Entity Auth - NONE") public void validEntityAuthNONE() throws InvalidAlgorithmParameterException, MslEncodingException, NoSuchAlgorithmException, IOException, MslCryptoException, URISyntaxException, MslKeyExchangeException, ExecutionException, InterruptedException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.NONE) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED); clientConfig.commitConfiguration(); MessageInputStream message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validFirstEntityAuthNONEMsg() .shouldHave().validBuffer(); message = sendReceive(TIME_OUT); thenThe(message) .shouldBe().validateSecondMsg() .shouldHave().validBuffer(); } @Test(testName = "clear key request data from request") public void keyRequestDataErr() throws ExecutionException, InterruptedException, IOException, MslEncodingException, NoSuchAlgorithmException, MslCryptoException, URISyntaxException, InvalidAlgorithmParameterException, MslKeyExchangeException { clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(numThreads) .setEntityAuthenticationScheme(EntityAuthenticationScheme.PSK) .setIsPeerToPeer(false) .setUserId(USER_ID) .setUserAuthenticationScheme(UserAuthenticationScheme.EMAIL_PASSWORD) .clearKeyRequestData(); clientConfig.commitConfiguration(); serverConfig.isMessageEncrypted(true) .commitToServer(); final MessageInputStream message = sendReceive(TIME_OUT); thenTheErr(message) .shouldBe().validateHdr() .shouldHave().validateErrCode(MslConstants.ResponseCode.KEYX_REQUIRED); } }
2,090
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/tests/SendTests.java
/** * Copyright (c) 2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.tests; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.client.common.BaseTestClass; import com.netflix.msl.client.configuration.ClientConfiguration; import com.netflix.msl.client.configuration.ServerConfiguration; import com.netflix.msl.client.configuration.msg.ClientMessageContext; import com.netflix.msl.client.configuration.util.ClientMslContext; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.entityauth.UnauthenticatedAuthenticationData; import com.netflix.msl.io.Url; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.MessageHeader; import com.netflix.msl.msg.MessageOutputStream; import com.netflix.msl.msg.MslControl; import com.netflix.msl.server.servlet.LogServlet; import com.netflix.msl.util.MslStore; /** * <p>Tests of the {@link MslControl} send methods.</p> * * @author Wesley Miaw <[email protected]> */ public class SendTests extends BaseTestClass { /** Local entity identity. */ private static final String ENTITY_IDENTITY = "send-test"; /** Server path. */ private static final String PATH = "/log"; /** Network timeout in milliseconds. */ private static final int TIMEOUT = 60000; @BeforeClass public void setup() throws IOException, URISyntaxException, MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException { super.loadProperties(); serverConfig = new ServerConfiguration() .resetDefaultConfig() .setHost(getRemoteEntityUrl()) .setPath(PATH); serverConfig.commitToServer(); clientConfig = new ClientConfiguration() .setScheme("http") .setHost(getRemoteEntityUrl()) .setPath(PATH) .setNumThreads(0) .setEntityAuthenticationScheme(EntityAuthenticationScheme.NONE); clientConfig.commitConfiguration(); super.setServerMslCryptoContext(); } @AfterMethod public void reset() { final MslStore store = clientConfig.getMslContext().getMslStore(); store.clearCryptoContexts(); store.clearUserIdTokens(); store.clearServiceTokens(); } /** * <p>Query the server for the reported string.</p> * * @return the string returned by a report query. * @throws IOException if there is an error making the query. */ public String report() throws IOException { // Prepare the request. final String uri = "http://" + getRemoteEntityUrl() + PATH + "?" + LogServlet.REPORT; final URL url = new URL(uri); final HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); // Read the response. final Reader in = new InputStreamReader(conn.getInputStream()); final StringBuffer content = new StringBuffer(); final char[] buffer = new char[16384]; while (true) { final int count = in.read(buffer); if (count == -1) break; content.append(buffer, 0, count); } return content.toString(); } @Test public void send() throws IOException, MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException, URISyntaxException { // Prepare. final String message = "fire-and-forget"; final MslControl ctrl = clientConfig.getMslControl(); final ClientMslContext ctx = clientConfig.getMslContext(); ctx.setEntityAuthenticationData(new UnauthenticatedAuthenticationData(ENTITY_IDENTITY)); clientConfig .setIsMessageEncrypted(false) .setIsIntegrityProtected(false) .clearKeyRequestData() .commitConfiguration(); final ClientMessageContext msgCtx = clientConfig.getMessageContext(); final Url remoteEntity = clientConfig.getRemoteEntity(); // Send message. msgCtx.setBuffer(message.getBytes(MslConstants.DEFAULT_CHARSET)); final Future<MessageOutputStream> future = ctrl.send(ctx, msgCtx, remoteEntity, TIMEOUT); MessageOutputStream mos = null; try { mos = future.get(); Assert.assertNotNull(mos); final MessageHeader messageHeader = mos.getMessageHeader(); Assert.assertNotNull(messageHeader); Assert.assertNull(messageHeader.getMasterToken()); } catch (final ExecutionException | InterruptedException | CancellationException e) { e.printStackTrace(System.err); return; } finally { if (mos != null) try { mos.close(); } catch (final IOException e) {} } // Query receipt. final String report = report(); Assert.assertEquals(report, message); } @Test public void handshakeSend() throws IOException, MslCryptoException, MslEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, MslKeyExchangeException, URISyntaxException { // Prepare. final String message = "handshake"; final MslControl ctrl = clientConfig.getMslControl(); final ClientMslContext ctx = clientConfig.getMslContext(); ctx.setEntityAuthenticationData(new UnauthenticatedAuthenticationData(ENTITY_IDENTITY)); clientConfig .setIsMessageEncrypted(true) .setIsIntegrityProtected(true) .setKeyRequestData(KeyExchangeScheme.ASYMMETRIC_WRAPPED) .commitConfiguration(); final ClientMessageContext msgCtx = clientConfig.getMessageContext(); final Url remoteEntity = clientConfig.getRemoteEntity(); // Send message. msgCtx.setBuffer(message.getBytes(MslConstants.DEFAULT_CHARSET)); final Future<MessageOutputStream> future = ctrl.send(ctx, msgCtx, remoteEntity, TIMEOUT); MessageOutputStream mos = null; try { mos = future.get(); Assert.assertNotNull(mos); final MessageHeader messageHeader = mos.getMessageHeader(); Assert.assertNotNull(messageHeader); Assert.assertNotNull(messageHeader.getMasterToken()); } catch (final ExecutionException | InterruptedException | CancellationException e) { e.printStackTrace(System.err); return; } finally { if (mos != null) try { mos.close(); } catch (final IOException e) {} } // Query receipt. final String report = report(); Assert.assertEquals(report, message); } /** Server configuration. */ private ServerConfiguration serverConfig; }
2,091
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/common/BaseTestClass.java
/** * Copyright (c) 2014-2018 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.common; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.HashSet; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import com.netflix.msl.MslException; import com.netflix.msl.client.assertable.ErrorHdrAssertable; import com.netflix.msl.client.assertable.MsgAssertable; import com.netflix.msl.client.configuration.ClientConfiguration; import com.netflix.msl.client.configuration.util.ClientMslContext; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.crypto.JcaAlgorithm; import com.netflix.msl.crypto.NullCryptoContext; import com.netflix.msl.crypto.SessionCryptoContext; import com.netflix.msl.crypto.SymmetricCryptoContext; import com.netflix.msl.entityauth.MockPresharedAuthenticationFactory; import com.netflix.msl.io.MslEncoderException; import com.netflix.msl.io.MslEncoderFactory; import com.netflix.msl.io.MslObject; import com.netflix.msl.keyx.KeyRequestData; import com.netflix.msl.msg.MessageBuilder; import com.netflix.msl.msg.MessageFactory; import com.netflix.msl.msg.MessageHeader; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.msg.MessageOutputStream; import com.netflix.msl.msg.MslControl; import com.netflix.msl.tokens.MasterToken; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.tokens.ServiceToken; import com.netflix.msl.tokens.UserIdToken; import com.netflix.msl.userauth.MockEmailPasswordAuthenticationFactory; import com.netflix.msl.util.MslTestUtils; /** * User: skommidi * Date: 7/25/14 */ public class BaseTestClass { private static final long SERIAL_NUMBER = 42; private static final String SERVICE_TOKEN_NAME = "serviceTokenName"; private static final ICryptoContext NULL_CRYPTO_CONTEXT = new NullCryptoContext(); private static MslObject ISSUER_DATA; protected static final String IDENTITY = MockPresharedAuthenticationFactory.PSK_ESN; protected static final SecretKey ENCRYPTION_KEY = MockPresharedAuthenticationFactory.KPE; protected static final SecretKey HMAC_KEY = MockPresharedAuthenticationFactory.KPH; private static final MslUser USER = MockEmailPasswordAuthenticationFactory.USER; /** MSL encryption key. */ private static final byte[] MSL_ENCRYPTION_KEY = { (byte)0x1d, (byte)0x58, (byte)0xf3, (byte)0xb8, (byte)0xf7, (byte)0x47, (byte)0xd1, (byte)0x6a, (byte)0xb1, (byte)0x93, (byte)0xc4, (byte)0xc0, (byte)0xa6, (byte)0x24, (byte)0xea, (byte)0xcf, }; /** MSL HMAC key. */ private static final byte[] MSL_HMAC_KEY = { (byte)0xd7, (byte)0xae, (byte)0xbf, (byte)0xd5, (byte)0x87, (byte)0x9b, (byte)0xb0, (byte)0xe0, (byte)0xad, (byte)0x01, (byte)0x6a, (byte)0x4c, (byte)0xf3, (byte)0xcb, (byte)0x39, (byte)0x82, (byte)0xf5, (byte)0xba, (byte)0x26, (byte)0x0d, (byte)0xa5, (byte)0x20, (byte)0x24, (byte)0x5b, (byte)0xb4, (byte)0x22, (byte)0x75, (byte)0xbd, (byte)0x79, (byte)0x47, (byte)0x37, (byte)0x0c, }; /** MSL wrapping key. */ private static final byte[] MSL_WRAPPING_KEY = { (byte)0x83, (byte)0xb6, (byte)0x9a, (byte)0x15, (byte)0x80, (byte)0xd3, (byte)0x23, (byte)0xa2, (byte)0xe7, (byte)0x9d, (byte)0xd9, (byte)0xb2, (byte)0x26, (byte)0x26, (byte)0xb3, (byte)0xf6, }; private String remoteEntityUrl; protected ClientConfiguration clientConfig; protected ICryptoContext serverMslCryptoContext; private static MessageFactory messageFactory = new MessageFactory(); public void setServerMslCryptoContext() { final SecretKey mslEncryptionKey = new SecretKeySpec(MSL_ENCRYPTION_KEY, JcaAlgorithm.AES); final SecretKey mslHmacKey = new SecretKeySpec(MSL_HMAC_KEY, JcaAlgorithm.HMAC_SHA256); final SecretKey mslWrappingKey = new SecretKeySpec(MSL_WRAPPING_KEY, JcaAlgorithm.AESKW); serverMslCryptoContext = new SymmetricCryptoContext(clientConfig.getMslContext(), "TestMslKeys", mslEncryptionKey, mslHmacKey, mslWrappingKey); } public void loadProperties() throws IOException { final Properties prop = new Properties(); prop.load(BaseTestClass.class.getResourceAsStream("/test.properties")); final String grettyHttpPort = System.getProperty("gretty.httpPort"); final String grettyContextPath = System.getProperty("gretty.contextPath"); if (grettyHttpPort != null && grettyContextPath != null) { // By definition, Gretty is localhost setRemoteEntityUrl("localhost:" + grettyHttpPort + grettyContextPath); } else { // Fallback to test.properties setRemoteEntityUrl(prop.getProperty("remoteEntityUrl")); } } public String getRemoteEntityUrl() { return remoteEntityUrl; } private void setRemoteEntityUrl(final String remoteEntityUrl) { this.remoteEntityUrl = remoteEntityUrl; } public static MsgAssertable thenThe(final MessageInputStream msg) { return new MsgAssertable(msg); } public static ErrorHdrAssertable thenTheErr(final MessageInputStream msg) { return new ErrorHdrAssertable(msg); } protected MasterToken getInitialMasterToken(final int timeOut) throws ExecutionException, InterruptedException { final MessageInputStream message = sendReceive(timeOut); final MasterToken initialMasterToken = message.getMessageHeader().getKeyResponseData().getMasterToken(); return initialMasterToken; } /** * get master token with given renewal window and expiration. */ protected MasterToken getMasterToken(final Date renewalWindow, final Date expiration, final int timeOut, final int sequenceNumberOffset) throws ExecutionException, InterruptedException, MslEncoderException, MslException { final MasterToken initialMasterToken = getInitialMasterToken(timeOut); final ClientMslContext mslContext = clientConfig.getMslContext(); // Temporarily switch to server crypto context to create master token mslContext.setMslCryptoContext(serverMslCryptoContext); // create master token with server crypto context; mocking server final MasterToken masterToken = new MasterToken(mslContext, renewalWindow, expiration, initialMasterToken.getSequenceNumber() + sequenceNumberOffset, SERIAL_NUMBER, ISSUER_DATA, IDENTITY, ENCRYPTION_KEY, HMAC_KEY); // Encode and parse the master token, to force it to use the server // crypto context. final MslEncoderFactory encoder = mslContext.getMslEncoderFactory(); final MslObject masterTokenMo = MslTestUtils.toMslObject(encoder, masterToken); final MasterToken parsedMasterToken = new MasterToken(mslContext, masterTokenMo); // Store corresponding session crypto context of the mastertoken final ICryptoContext sessionCryptoContext = new SessionCryptoContext(mslContext, parsedMasterToken); mslContext.getMslStore().setCryptoContext(parsedMasterToken, sessionCryptoContext); // switch back to client crypto context after creating master token mslContext.setClientCryptoContext(); return parsedMasterToken; } /** * get user id token with given renewal window and expiration. */ protected UserIdToken getUserIdToken(final MasterToken initialMasterToken, final Date renewalWindow, final Date expiration, final int timeOut) throws ExecutionException, InterruptedException, MslEncoderException, MslException { final ClientMslContext mslContext = clientConfig.getMslContext(); // Temporarily switch to server crypto context to create master token mslContext.setMslCryptoContext(serverMslCryptoContext); final UserIdToken userIdToken = new UserIdToken(mslContext, renewalWindow, expiration, initialMasterToken, SERIAL_NUMBER, ISSUER_DATA, USER); // Encode and parse the master token, to force it to use the server // crypto context. final MslEncoderFactory encoder = mslContext.getMslEncoderFactory(); final MslObject userIdTokenMo = MslTestUtils.toMslObject(encoder, userIdToken); final UserIdToken parsedUserIdToken = new UserIdToken(mslContext, userIdTokenMo, initialMasterToken); // switch back to client crypto context after creating master token mslContext.setClientCryptoContext(); return parsedUserIdToken; } /** * get service token bound to given master token and user id token */ protected Set<ServiceToken> getServiceToken(final MasterToken masterToken, final UserIdToken userIdToken, final ServiceTokenType serviceTokenType, final boolean withData) throws MslException { final Random random = new Random(); final Set<ServiceToken> serviceTokens = new HashSet<ServiceToken>(); final byte[] data; if(withData) { data = new byte[32]; random.nextBytes(data); } else { data = new byte[0]; } final ClientMslContext ctx = clientConfig.getMslContext(); switch(serviceTokenType) { case BOTH: serviceTokens.add(new ServiceToken(ctx, SERVICE_TOKEN_NAME + "Both", data, masterToken, userIdToken, false, null, NULL_CRYPTO_CONTEXT)); break; case MASTER_BOUND: serviceTokens.add(new ServiceToken(ctx, SERVICE_TOKEN_NAME + "Master", data, masterToken, null, false, null, NULL_CRYPTO_CONTEXT)); break; case NONE: serviceTokens.add(new ServiceToken(ctx, SERVICE_TOKEN_NAME + "None", data, null, null, false, null, NULL_CRYPTO_CONTEXT)); break; default: throw new IllegalArgumentException("Unexpected ServiceTokenType " + serviceTokenType); } return serviceTokens; } public MessageInputStream sendReceive(final int timeOut) throws ExecutionException, InterruptedException { final Future<MslControl.MslChannel> mslChannelFuture = clientConfig.getMslControl().request(clientConfig.getMslContext(), clientConfig.getMessageContext(), clientConfig.getRemoteEntity(), timeOut); if(mslChannelFuture.isDone()) { final MslControl.MslChannel mslChannel = mslChannelFuture.get(); return mslChannel.input; } return null; } public MessageInputStream sendReceive(final OutputStream out, final InputStream in, final MasterToken masterToken, final UserIdToken userIdToken, final Set<ServiceToken> serviceTokens, final boolean isRenewable, final boolean addKeyRequestData) throws MslException, IOException { final MessageBuilder builder = messageFactory.createRequest(clientConfig.getMslContext(), masterToken, userIdToken); builder.setRenewable(isRenewable); builder.setNonReplayable(clientConfig.getMessageContext().isNonReplayable()); if(addKeyRequestData) { final Set<KeyRequestData> keyRequestDataSet = clientConfig.getMessageContext().getKeyRequestData(); for(final KeyRequestData keyRequestData : keyRequestDataSet) { builder.addKeyRequestData(keyRequestData); } } if(serviceTokens != null) { for(final ServiceToken serviceToken : serviceTokens) { builder.addServiceToken(serviceToken); } } final MessageHeader requestHeader = builder.getHeader(); final MessageOutputStream request = new MessageOutputStream(clientConfig.getMslContext(), out, requestHeader, requestHeader.getCryptoContext()); clientConfig.getMessageContext().write(request); final MessageInputStream response = new MessageInputStream(clientConfig.getMslContext(), in, clientConfig.getMessageContext().getKeyRequestData(), clientConfig.getMessageContext().getCryptoContexts()); return response; } /** * Types of service token */ protected enum ServiceTokenType { MASTER_BOUND, BOTH, NONE } }
2,092
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/assertable/MsgAssertable.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.assertable; import com.netflix.msl.MslConstants; import com.netflix.msl.client.configuration.ClientConfiguration; import com.netflix.msl.msg.ErrorHeader; import com.netflix.msl.msg.MessageHeader; import com.netflix.msl.msg.MessageInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Date; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; /** * User: skommidi * Date: 7/25/14 */ public class MsgAssertable { private MessageInputStream msg; private MessageHeader msg_hdr; private ErrorHeader err_hdr; private boolean booleanExpectation; byte[] buffer = new byte[5]; public MsgAssertable(MessageInputStream message) { this.msg = message; } public MsgAssertable shouldBe() { this.booleanExpectation = true; return this; } public MsgAssertable shouldHave() { this.booleanExpectation = true; return this; } public MsgAssertable shouldNotBe() { this.booleanExpectation = false; return this; } public MsgAssertable validFirstEntityAuthPSKMsg() { Date now = new Date(); try { msg_hdr = msg.getMessageHeader(); err_hdr = msg.getErrorHeader(); assertNull(err_hdr); assertNotNull(msg_hdr); //First response for PSK contain key exchange data and master token assertNotNull(msg.getKeyExchangeCryptoContext()); assertNotNull(msg.getPayloadCryptoContext()); //MasterToken is not in the message header its in the keyResponseData assertNull(msg_hdr.getMasterToken()); assertNotNull(msg_hdr.getKeyResponseData().getMasterToken()); assertNotNull(msg_hdr.getKeyResponseData().getMasterToken().getRenewalWindow()); assertNotNull(msg_hdr.getKeyResponseData().getMasterToken().getSequenceNumber()); assertFalse(msg_hdr.getKeyResponseData().getMasterToken().isDecrypted()); assertFalse(msg_hdr.getKeyResponseData().getMasterToken().isVerified()); assertFalse(msg_hdr.getKeyResponseData().getMasterToken().isRenewable(now)); assertTrue(msg_hdr.getKeyRequestData().isEmpty()); assertNull(msg_hdr.getUserAuthenticationData()); assertNotNull(msg_hdr.getUserIdToken()); assertFalse(msg_hdr.getUserIdToken().isDecrypted()); assertFalse(msg_hdr.getUserIdToken().isVerified()); assertFalse(msg_hdr.getUserIdToken().isExpired(now)); assertEquals(msg_hdr.getUserIdToken().getMasterTokenSerialNumber(), msg_hdr.getKeyResponseData().getMasterToken().getSerialNumber()); assertNotNull(msg_hdr.getUserIdToken().getRenewalWindow()); assertFalse(msg_hdr.getUserIdToken().isRenewable(now)); } catch(AssertionError e) { if(this.booleanExpectation) { throw e; } } return this; } public MsgAssertable validFirstMsg(boolean user_auth_data_null) { Date now = new Date(); try { msg_hdr = msg.getMessageHeader(); err_hdr = msg.getErrorHeader(); assertNull(err_hdr); assertNotNull(msg_hdr); //First response for RSA does not contain key exchange data and master token assertNull(msg.getKeyExchangeCryptoContext()); assertNotNull(msg.getPayloadCryptoContext()); //MasterToken is in the message header its not in the keyResponseData, this is after handshake assertNotNull(msg_hdr.getMasterToken()); assertNull(msg_hdr.getKeyResponseData()); assertTrue(msg_hdr.getKeyRequestData().isEmpty()); assertNull(msg_hdr.getUserAuthenticationData()); //If userauthdata is null there is no userIdToken in response. if(!user_auth_data_null) { assertNotNull(msg_hdr.getUserIdToken()); assertFalse(msg_hdr.getUserIdToken().isDecrypted()); assertFalse(msg_hdr.getUserIdToken().isVerified()); assertFalse(msg_hdr.getUserIdToken().isExpired(now)); assertEquals(msg_hdr.getUserIdToken().getMasterTokenSerialNumber(), msg_hdr.getMasterToken().getSerialNumber()); assertNotNull(msg_hdr.getUserIdToken().getRenewalWindow()); assertFalse(msg_hdr.getUserIdToken().isRenewable(now)); } } catch(AssertionError e) { if(this.booleanExpectation) { throw e; } } return this; } public MsgAssertable validBuffer() throws IOException { do { final int bytesRead = msg.read(buffer); if (bytesRead == -1) break; } while (true); if(Arrays.equals(buffer, ClientConfiguration.serverError.getBytes(MslConstants.DEFAULT_CHARSET))) { fail("Buffer mis-match on server"); } assertEquals(this.booleanExpectation, Arrays.equals(buffer, ClientConfiguration.input.getBytes(MslConstants.DEFAULT_CHARSET))); return this; } public MsgAssertable validateSecondMsg() { validateSecondMsg(false); return this; } public MsgAssertable validateSecondMsg(boolean user_auth_data_null) { try { msg_hdr = msg.getMessageHeader(); assertNull(msg.getErrorHeader()); assertNotNull(msg_hdr); //Once MasterToken is received there should be no keyResponseData assertNull(msg.getKeyExchangeCryptoContext()); assertNotNull(msg.getPayloadCryptoContext()); assertNotNull(msg_hdr.getMasterToken()); assertTrue(msg_hdr.getKeyRequestData().isEmpty()); assertNull(msg_hdr.getUserAuthenticationData()); //If userauthdata is null there is no userIdToken in response. if(!user_auth_data_null) { assertNotNull(msg_hdr.getUserIdToken()); } } catch (AssertionError e) { if(this.booleanExpectation) { throw e; } } return this; } public MsgAssertable validFirstEntityAuthRSAMsg() { validFirstMsg(false); return this; } public MsgAssertable validFirstEntityAuthECCMsg() { validFirstMsg(false); return this; } public MsgAssertable validFirstEntityAuthX509Msg() { validFirstMsg(false); return this; } public MsgAssertable validFirstEntityAuthNONEMsg() { validFirstMsg(false); return this; } public MsgAssertable validFirstEntityAuthNONEMsg(boolean user_auth_data_null) { validFirstMsg(user_auth_data_null); return this; } }
2,093
0
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client
Create_ds/msl/integ-tests/src/test/java/com/netflix/msl/client/assertable/ErrorHdrAssertable.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.client.assertable; import com.netflix.msl.MslConstants; import com.netflix.msl.msg.ErrorHeader; import com.netflix.msl.msg.MessageInputStream; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; /** * User: skommidi * Date: 7/25/14 */ public class ErrorHdrAssertable { private MessageInputStream msg; private ErrorHeader err_hdr; private boolean booleanExpectation; public ErrorHdrAssertable(MessageInputStream msg) { this.msg = msg; } public ErrorHdrAssertable shouldBe() { this.booleanExpectation = true; return this; } public ErrorHdrAssertable shouldHave() { this.booleanExpectation = true; return this; } public ErrorHdrAssertable shouldNotBe() { this.booleanExpectation = false; return this; } public ErrorHdrAssertable validateHdr() { try { err_hdr = msg.getErrorHeader(); assertNull(msg.getMessageHeader()); assertNotNull(err_hdr); assertNull(msg.getKeyExchangeCryptoContext()); assertNull(msg.getPayloadCryptoContext()); assertTrue(err_hdr.getMessageId() >= 0); assertNotNull(err_hdr.getErrorMessage()); assertNotNull(err_hdr.getInternalCode()); } catch(AssertionError e) { if(this.booleanExpectation) { throw e; } } return this; } public ErrorHdrAssertable validateErrCode(MslConstants.ResponseCode respCode) { err_hdr = msg.getErrorHeader(); assertEquals(err_hdr.getErrorCode(), respCode); return this; } }
2,094
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/configuration
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/configuration/util/ServerMslContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.server.configuration.util; import java.util.List; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.crypto.NullCryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.server.configuration.tokens.ServerTokenFactory; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; import com.netflix.msl.tokens.MockTokenFactory; import com.netflix.msl.userauth.UserAuthenticationScheme; import com.netflix.msl.util.MockMslContext; /** * User: skommidi * Date: 7/21/14 */ public class ServerMslContext extends MockMslContext { /** * Create a new Server MSL context. * * @throws MslCryptoException if there is an error signing or creating the * entity authentication data. * @throws MslEncodingException if there is an error creating the entity * authentication data. */ public ServerMslContext(final EntityAuthenticationScheme entityAuthScheme, final boolean peerToPeer, final TokenFactoryType tokenFactoryType, final long initialSequenceNum, final List<EntityAuthenticationScheme> unSupportedEntityAuthFactories, final List<UserAuthenticationScheme> unSupportedUserAuthFactories, final List<KeyExchangeScheme> unSupportedKeyxFactories, final boolean isNullCryptoContext) throws MslEncodingException, MslCryptoException { super(entityAuthScheme, peerToPeer); //Set Server TokenFactory with initialSequenceNumber final MockTokenFactory tokenFactory = new ServerTokenFactory(tokenFactoryType); tokenFactory.setNewestMasterToken(initialSequenceNum); super.setTokenFactory(tokenFactory); if (isNullCryptoContext) { super.setMslCryptoContext(new NullCryptoContext()); } if (unSupportedEntityAuthFactories != null) { for (final EntityAuthenticationScheme scheme : unSupportedEntityAuthFactories) { super.removeEntityAuthenticationFactory(scheme); } } if (unSupportedUserAuthFactories != null) { for (final UserAuthenticationScheme scheme : unSupportedUserAuthFactories) { super.removeUserAuthenticationFactory(scheme); } } if (unSupportedKeyxFactories != null) { for (final KeyExchangeScheme scheme : unSupportedKeyxFactories) { super.removeKeyExchangeFactories(scheme); } } } }
2,095
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/configuration
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/configuration/msg/ServerMessageContext.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.server.configuration.msg; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.HashSet; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.keyx.KeyRequestData; import com.netflix.msl.msg.MessageOutputStream; import com.netflix.msl.msg.MockMessageContext; import com.netflix.msl.server.configuration.util.ServerMslContext; import com.netflix.msl.userauth.UserAuthenticationScheme; /** * User: skommidi * Date: 7/21/14 */ public class ServerMessageContext extends MockMessageContext { private byte[] buffer; /** * Create a new test message context. * * @param mslCtx MSL context. * @param payloadBytes application data to write. * @param messageEncrypted true if the message must be encrypted. * @throws NoSuchAlgorithmException if a key generation algorithm is not * found. * @throws InvalidAlgorithmParameterException if key generation parameters * are invalid. * @throws MslKeyExchangeException if there is an error accessing Diffie- * Hellman parameters. */ public ServerMessageContext(final ServerMslContext mslCtx, final byte[] payloadBytes, final boolean messageEncrypted) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MslKeyExchangeException { super(mslCtx, null, UserAuthenticationScheme.EMAIL_PASSWORD); super.setUserAuthData(null); super.setKeyRequestData(new HashSet<KeyRequestData>()); super.setEncrypted(messageEncrypted); this.buffer = payloadBytes; } public void setBuffer(final byte[] buffer) { this.buffer = buffer; } @Override public void write(final MessageOutputStream output) throws IOException { output.write(buffer); output.flush(); output.close(); } }
2,096
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/configuration
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/configuration/tokens/ServerTokenFactory.java
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.server.configuration.tokens; import java.sql.Date; import javax.crypto.SecretKey; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslError; import com.netflix.msl.MslException; import com.netflix.msl.MslMasterTokenException; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.io.MslObject; import com.netflix.msl.tokens.MasterToken; import com.netflix.msl.tokens.MockTokenFactory; import com.netflix.msl.util.MslContext; import com.netflix.msl.util.MslUtils; /** * User: skommidi * Date: 7/24/14 */ public class ServerTokenFactory extends MockTokenFactory { public ServerTokenFactory(final TokenFactoryType tokenFactoryType) { this.tokenFactoryType = tokenFactoryType; } @Override public MslError acceptNonReplayableId(final MslContext mslContext, final MasterToken masterToken, final long nonReplayableId) throws MslMasterTokenException, MslException { if (!masterToken.isDecrypted()) throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken); if (nonReplayableId < 0 || nonReplayableId > MslConstants.MAX_LONG_VALUE) throw new MslException(MslError.NONREPLAYABLE_ID_OUT_OF_RANGE, "nonReplayableId " + nonReplayableId); if(this.tokenFactoryType == TokenFactoryType.ACCEPT_NON_REPLAYABLE_ID) { return null; } else { return MslError.MESSAGE_REPLAYED; } } @Override public MasterToken renewMasterToken(final MslContext ctx, final MasterToken masterToken, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslMasterTokenException, MslCryptoException, MslEncodingException { if (!masterToken.isDecrypted()) throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken); final long oldSequenceNumber = masterToken.getSequenceNumber(); if(oldSequenceNumber > this.sequenceNumber + 30) { throw new MslMasterTokenException(MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_RANGE, masterToken); } this.sequenceNumber++; return super.renewMasterToken(ctx, masterToken, encryptionKey, hmacKey, issuerData); } @Override public MasterToken createMasterToken(final MslContext ctx, final EntityAuthenticationData entityAuthData, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException { final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET); final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET); this.sequenceNumber++; final long sequenceNumber = this.sequenceNumber; final long serialNumber = MslUtils.getRandomLong(ctx); final String identity = entityAuthData.getIdentity(); return new MasterToken(ctx, renewalWindow, expiration, sequenceNumber, serialNumber, null, identity, encryptionKey, hmacKey); } private final TokenFactoryType tokenFactoryType; }
2,097
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/configuration
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/configuration/tokens/TokenFactoryType.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.server.configuration.tokens; /** * User: skommidi * Date: 7/21/14 */ public enum TokenFactoryType { ACCEPT_NON_REPLAYABLE_ID, NOT_ACCEPT_NON_REPLAYABLE_ID; }
2,098
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/servlet/NullServlet.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.msl.server.servlet; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.server.common.RespondServlet; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; /** * User: skommidi * Date: 8/27/14 */ public class NullServlet extends RespondServlet { private static final long serialVersionUID = -2879936348232394823L; private static final long SEQUENCE_NUMBER = 8L; private static final int NUM_THREADS = 0; public NullServlet() throws Exception { super(NUM_THREADS, EntityAuthenticationScheme.NONE, TokenFactoryType.NOT_ACCEPT_NON_REPLAYABLE_ID, SEQUENCE_NUMBER, false, false, null, null, null, true, true); System.out.println("======================>> Null Servlet Initialization Ended <<======================"); } }
2,099