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/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/ErrorHeader.java
|
/**
* Copyright (c) 2012-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.msg;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
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.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
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.MslObject;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>The error data is represented as
* {@code
* errordata = {
* "#mandatory" : [ "messageid", "errorcode" ],
* "timestamp" : "int64(0,2^53^)",
* "messageid" : "int64(0,2^53^)",
* "errorcode" : "int32(0,-)",
* "internalcode" : "int32(0,-)",
* "errormsg" : "string",
* "usermsg" : "string",
* }} where:
* <ul>
* <li>{@code timestamp} is the sender time when the header is created in seconds since the UNIX epoch</li>
* <li>{@code messageid} is the message ID</li>
* <li>{@code errorcode} is the error code</li>
* <li>{@code internalcode} is an service-specific error code</li>
* <li>{@code errormsg} is a developer-consumable error message</li>
* <li>{@code usermsg} is a user-consumable localized error message</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class ErrorHeader extends Header {
/** Milliseconds per second. */
private static final long MILLISECONDS_PER_SECOND = 1000;
// Message error data.
/** Key timestamp. */
private static final String KEY_TIMESTAMP = "timestamp";
/** Key message ID. */
private static final String KEY_MESSAGE_ID = "messageid";
/** Key error code. */
private static final String KEY_ERROR_CODE = "errorcode";
/** Key internal code. */
private static final String KEY_INTERNAL_CODE = "internalcode";
/** Key error message. */
private static final String KEY_ERROR_MESSAGE = "errormsg";
/** Key user message. */
private static final String KEY_USER_MESSAGE = "usermsg";
/**
* <p>Construct a new error header with the provided error data.</p>
*
* @param ctx MSL context.
* @param entityAuthData the entity authentication data.
* @param messageId the message ID.
* @param errorCode the error code.
* @param internalCode the internal code. Negative to indicate no code.
* @param errorMsg the error message. May be null.
* @param userMsg the user message. May be null.
* @throws MslMessageException if no entity authentication data is
* provided.
*/
public ErrorHeader(final MslContext ctx, final EntityAuthenticationData entityAuthData, final long messageId, final ResponseCode errorCode, final int internalCode, final String errorMsg, final String userMsg) throws MslMessageException {
// Message ID must be within range.
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is out of range.");
// Message entity must be provided.
if (entityAuthData == null)
throw new MslMessageException(MslError.MESSAGE_ENTITY_NOT_FOUND);
this.ctx = ctx;
this.entityAuthData = entityAuthData;
this.timestamp = ctx.getTime() / MILLISECONDS_PER_SECOND;
this.messageId = messageId;
this.errorCode = errorCode;
this.internalCode = (internalCode >= 0) ? internalCode : -1;
this.errorMsg = errorMsg;
this.userMsg = userMsg;
// Construct the error data.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
errordata = encoder.createObject();
errordata.put(KEY_TIMESTAMP, this.timestamp);
errordata.put(KEY_MESSAGE_ID, this.messageId);
errordata.put(KEY_ERROR_CODE, this.errorCode.intValue());
if (this.internalCode > 0) errordata.put(KEY_INTERNAL_CODE, this.internalCode);
if (this.errorMsg != null) errordata.put(KEY_ERROR_MESSAGE, this.errorMsg);
if (this.userMsg != null) errordata.put(KEY_USER_MESSAGE, this.userMsg);
}
/**
* <p>Construct a new error header from the provided MSL object.</p>
*
* @param ctx MSL context.
* @param errordataBytes error data MSL encoding.
* @param entityAuthData the entity authentication data.
* @param signature the header signature.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException if there is an error decrypting or verifying
* the header.
* @throws MslEntityAuthException if the entity authentication data is not
* supported or erroneous.
* @throws MslMessageException if there is no entity authentication data
* (null), the error data is missing or invalid, the message ID is
* negative, or the internal code is negative.
*/
protected ErrorHeader(final MslContext ctx, final byte[] errordataBytes, final EntityAuthenticationData entityAuthData, final byte[] signature) throws MslEncodingException, MslCryptoException, MslEntityAuthException, MslMessageException {
this.ctx = ctx;
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] plaintext;
try {
// Validate the entity authentication data.
this.entityAuthData = entityAuthData;
if (entityAuthData == null)
throw new MslMessageException(MslError.MESSAGE_ENTITY_NOT_FOUND);
// Grab the entity crypto context.
final EntityAuthenticationScheme scheme = entityAuthData.getScheme();
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(scheme);
if (factory == null)
throw new MslEntityAuthException(MslError.ENTITYAUTH_FACTORY_NOT_FOUND, scheme.name());
final ICryptoContext cryptoContext = factory.getCryptoContext(ctx, entityAuthData);
// Verify and decrypt the error data.
if (!cryptoContext.verify(errordataBytes, signature, encoder))
throw new MslCryptoException(MslError.MESSAGE_VERIFICATION_FAILED).setEntityAuthenticationData(entityAuthData);
plaintext = cryptoContext.decrypt(errordataBytes, encoder);
} catch (final MslCryptoException e) {
e.setEntityAuthenticationData(entityAuthData);
throw e;
} catch (final MslEntityAuthException e) {
e.setEntityAuthenticationData(entityAuthData);
throw e;
}
try {
errordata = encoder.parseObject(plaintext);
messageId = errordata.getLong(KEY_MESSAGE_ID);
if (this.messageId < 0 || this.messageId > MslConstants.MAX_LONG_VALUE)
throw new MslMessageException(MslError.MESSAGE_ID_OUT_OF_RANGE, "errordata " + errordata).setEntityAuthenticationData(entityAuthData);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "errordata " + Base64.encode(plaintext), e).setEntityAuthenticationData(entityAuthData);
}
try {
timestamp = (errordata.has(KEY_TIMESTAMP)) ? errordata.getLong(KEY_TIMESTAMP) : null;
// If we do not recognize the error code then default to fail.
ResponseCode code = ResponseCode.FAIL;
try {
code = ResponseCode.valueOf(errordata.getInt(KEY_ERROR_CODE));
} catch (final IllegalArgumentException e) {
code = ResponseCode.FAIL;
}
errorCode = code;
if (errordata.has(KEY_INTERNAL_CODE)) {
internalCode = errordata.getInt(KEY_INTERNAL_CODE);
if (this.internalCode < 0)
throw new MslMessageException(MslError.INTERNAL_CODE_NEGATIVE, "errordata " + errordata).setEntityAuthenticationData(entityAuthData).setMessageId(messageId);
} else {
internalCode = -1;
}
errorMsg = errordata.optString(KEY_ERROR_MESSAGE, null);
userMsg = errordata.optString(KEY_USER_MESSAGE, null);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "errordata " + errordata, e).setEntityAuthenticationData(entityAuthData).setMessageId(messageId);
}
}
/**
* Returns the entity authentication data.
*
* @return the entity authentication data.
*/
public EntityAuthenticationData getEntityAuthenticationData() {
return entityAuthData;
}
/**
* @return the timestamp. May be null.
*/
public Date getTimestamp() {
return (timestamp != null) ? new Date(timestamp * MILLISECONDS_PER_SECOND) : null;
}
/**
* @return the message ID.
*/
public long getMessageId() {
return messageId;
}
/**
* Returns the error code. If the parsed error code is not recognized then
* this returns {@code ResponseCode#FAIL}.
*
* @return the error code.
*/
public ResponseCode getErrorCode() {
return errorCode;
}
/**
* @return the internal code or -1 if none provided.
*/
public int getInternalCode() {
return internalCode;
}
/**
* @return the error message. May be null.
*/
public String getErrorMessage() {
return errorMsg;
}
/**
* @return the user message. May be null.
*/
public String getUserMessage() {
return userMsg;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
// Return any cached encoding.
if (encodings.containsKey(format))
return encodings.get(format);
// Create the crypto context.
final EntityAuthenticationScheme scheme = entityAuthData.getScheme();
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(scheme);
if (factory == null)
throw new MslEncoderException("No entity authentication factory found for entity.");
final ICryptoContext cryptoContext;
try {
cryptoContext = factory.getCryptoContext(ctx, entityAuthData);
} catch (final MslEntityAuthException e) {
throw new MslEncoderException("Error creating the entity crypto context.", e);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error creating the entity crypto context.", e);
}
// Encrypt and sign the error data.
final byte[] plaintext = encoder.encodeObject(errordata, format);
final byte[] ciphertext;
try {
ciphertext = cryptoContext.encrypt(plaintext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error encrypting the error data.", e);
}
final byte[] signature;
try {
signature = cryptoContext.sign(ciphertext, encoder, format, this);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error signing the error data.", e);
}
// Create the encoding.
final MslObject header = encoder.createObject();
header.put(Header.KEY_ENTITY_AUTHENTICATION_DATA, entityAuthData);
header.put(Header.KEY_ERRORDATA, ciphertext);
header.put(Header.KEY_SIGNATURE, signature);
final byte[] encoding = encoder.encodeObject(header, format);
// Cache and return the encoding.
encodings.put(format, encoding);
return encoding;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (!(obj instanceof ErrorHeader)) return false;
final ErrorHeader that = (ErrorHeader)obj;
return entityAuthData.equals(that.entityAuthData) &&
(timestamp != null && timestamp.equals(that.timestamp) ||
timestamp == null && that.timestamp == null) &&
messageId == that.messageId &&
errorCode == that.errorCode &&
internalCode == that.internalCode &&
(errorMsg == that.errorMsg || (errorMsg != null && errorMsg.equals(that.errorMsg))) &&
(userMsg == that.userMsg || (userMsg != null && userMsg.equals(that.userMsg)));
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return entityAuthData.hashCode() ^
((timestamp != null) ? timestamp.hashCode() : 0) ^
Long.valueOf(messageId).hashCode() ^
errorCode.hashCode() ^
Integer.valueOf(internalCode).hashCode() ^
((errorMsg != null) ? errorMsg.hashCode() : 0) ^
((userMsg != null) ? userMsg.hashCode() : 0);
}
/** MSL context. */
protected final MslContext ctx;
/** Entity authentication data. */
protected final EntityAuthenticationData entityAuthData;
/** Error data. */
protected final MslObject errordata;
/** Timestamp in seconds since the epoch. */
private final Long timestamp;
/** Message ID. */
private final long messageId;
/** Error code. */
private final ResponseCode errorCode;
/** Internal code. */
private final int internalCode;
/** Error message. */
private final String errorMsg;
/** User message. */
private final String userMsg;
/** Cached encodings. */
protected final Map<MslEncoderFormat,byte[]> encodings = new HashMap<MslEncoderFormat,byte[]>();
}
| 1,700 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/ErrorMessageRegistry.java
|
/**
* Copyright (c) 2013-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.msg;
import java.util.List;
import com.netflix.msl.MslError;
/**
* <p>The error message registry is used to provide localized user-consumable
* messages for specific MSL errors.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public interface ErrorMessageRegistry {
/**
* Returns the user-consumable message associated with the given MSL error,
* localized according to the list of preferred languages.
*
* @param err MSL error.
* @param languages preferred languages as BCP-47 codes in descending
* order. May be {@code null}.
* @return the localized user message or {@code null} if there is none.
*/
public String getUserMessage(final MslError err, final List<String> languages);
/**
* Returns the user-consumable message associated with a given non-MSL
* error, localized according to the list of preferred languages.
*
* @param err non-MSL error.
* @param languages preferred languages as BCP-47 codes in descending
* order. May be {@code null}.
* @return the localized user message or {@code null} if there is none.
*/
public String getUserMessage(final Throwable err, final List<String> languages);
}
| 1,701 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/PayloadChunk.java
|
/**
* Copyright (c) 2012-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.msg;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
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.MslMessageException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.io.MslEncodable;
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.util.Base64;
import com.netflix.msl.util.MslCompression;
import com.netflix.msl.util.MslContext;
/**
* <p>A payload chunk is a self-contained block of application data that is
* encrypted, verified, and optionally compressed independent of other chunks.
* A message payload may contain one or more chunks.</p>
*
* <p>Payload chunks are bound to a specific message by the message ID.</p>
*
* <p>Each payload chunk in a message is sequentially ordered by the chunk
* sequence number. The sequence number starts at 1 and is incremented by 1 on
* each sequential chunk.</p>
*
* <p>Payload chunks are represented as
* {@code
* payloadchunk = {
* "#mandatory" : [ "payload", "signature" ],
* "payload" : "binary",
* "signature" : "binary"
* }} where:
* <ul>
* <li>{@code payload} is the Base64-encoded encrypted payload (payload)</li>
* <li>{@code signature} is the Base64-encoded verification data of the payload</li>
* </ul></p>
*
* <p>The payload is represented as
* {@code
* payload = {
* "#mandatory" : [ "sequencenumber", "messageid", "data" ],
* "sequencenumber" : "int64(1,2^53^)",
* "messageid" : "int64(0,2^53^)",
* "endofmsg" : "boolean",
* "compressionalgo" : "enum(GZIP|LZW)",
* "data" : "binary"
* }} where:
* <ul>
* <li>{@code sequencenumber} is the chunk sequence number</li>
* <li>{@code messageid} is the message ID</li>
* <li>{@code endofmsg} indicates this is the last payload of the message</li>
* <li>{@code compressionalgo} indicates the algorithm used to compress the data</li>
* <li>{@code data} is the optionally compressed application data</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class PayloadChunk implements MslEncodable {
/** Key payload. */
private static final String KEY_PAYLOAD = "payload";
/** Key signature. */
private static final String KEY_SIGNATURE = "signature";
// payload
/** Key sequence number. */
private static final String KEY_SEQUENCE_NUMBER = "sequencenumber";
/** Key message ID. */
private static final String KEY_MESSAGE_ID = "messageid";
/** Key end of message. */
private static final String KEY_END_OF_MESSAGE = "endofmsg";
/** Key compression algorithm. */
private static final String KEY_COMPRESSION_ALGORITHM = "compressionalgo";
/** Key encrypted data. */
private static final String KEY_DATA = "data";
/**
* Construct a new payload chunk with the given message ID, data and
* provided crypto context. If requested, the data will be compressed
* before encrypting.
*
* @param ctx the MSL context.
* @param sequenceNumber sequence number.
* @param messageId the message ID.
* @param endofmsg true if this is the last payload chunk of the message.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @param data the payload chunk application data.
* @param cryptoContext the crypto context.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the payload chunk.
* @throws MslException if there is an error compressing the data.
*/
public PayloadChunk(final MslContext ctx, final long sequenceNumber, final long messageId, final boolean endofmsg, final CompressionAlgorithm compressionAlgo, final byte[] data, final ICryptoContext cryptoContext) throws MslEncodingException, MslCryptoException, MslException {
// Verify sequence number and message ID.
if (sequenceNumber < 0 || sequenceNumber > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Sequence number " + sequenceNumber + " is outside the valid range.");
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is outside the valid range.");
// Optionally compress the application data.
final byte[] payloadData;
if (compressionAlgo != null) {
final byte[] compressed = MslCompression.compress(compressionAlgo, data);
// Only use compression if the compressed data is smaller than the
// uncompressed data.
if (compressed != null && compressed.length < data.length) {
this.compressionAlgo = compressionAlgo;
payloadData = compressed;
} else {
this.compressionAlgo = null;
payloadData = data;
}
} else {
this.compressionAlgo = null;
payloadData = data;
}
// Set the payload properties.
this.sequenceNumber = sequenceNumber;
this.messageId = messageId;
this.endofmsg = endofmsg;
this.data = data;
// Construct the payload.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
this.payload = encoder.createObject();
this.payload.put(KEY_SEQUENCE_NUMBER, this.sequenceNumber);
this.payload.put(KEY_MESSAGE_ID, this.messageId);
if (this.endofmsg) this.payload.put(KEY_END_OF_MESSAGE, this.endofmsg);
if (this.compressionAlgo != null) this.payload.put(KEY_COMPRESSION_ALGORITHM, this.compressionAlgo.name());
this.payload.put(KEY_DATA, payloadData);
// Save the crypto context.
this.cryptoContext = cryptoContext;
}
/**
* <p>Construct a new payload chunk from the provided MSL object.</p>
*
* <p>The provided crypto context will be used to decrypt and verify the
* data signature.</p>
*
* @param ctx the MSL context.
* @param payloadChunkMo the MSL object.
* @param cryptoContext the crypto context.
* @throws MslCryptoException if there is a problem decrypting or verifying
* the payload chunk.
* @throws MslEncodingException if there is a problem parsing the data.
* @throws MslMessageException if the compression algorithm is not known,
* or the payload data is corrupt or missing.
* @throws MslException if there is an error uncompressing the data.
*/
public PayloadChunk(final MslContext ctx, final MslObject payloadChunkMo, final ICryptoContext cryptoContext) throws MslEncodingException, MslCryptoException, MslMessageException, MslException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
// Save the crypto context.
this.cryptoContext = cryptoContext;
// Verify the data.
final byte[] ciphertext;
try {
ciphertext = payloadChunkMo.getBytes(KEY_PAYLOAD);
final byte[] signature = payloadChunkMo.getBytes(KEY_SIGNATURE);
if (!cryptoContext.verify(ciphertext, signature, encoder))
throw new MslCryptoException(MslError.PAYLOAD_VERIFICATION_FAILED);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "payload chunk " + payloadChunkMo, e);
}
// Pull the payload data.
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
try {
payload = encoder.parseObject(plaintext);
sequenceNumber = payload.getLong(KEY_SEQUENCE_NUMBER);
if (sequenceNumber < 0 || sequenceNumber > MslConstants.MAX_LONG_VALUE)
throw new MslException(MslError.PAYLOAD_SEQUENCE_NUMBER_OUT_OF_RANGE, "payload chunk payload " + payload);
messageId = payload.getLong(KEY_MESSAGE_ID);
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslException(MslError.PAYLOAD_MESSAGE_ID_OUT_OF_RANGE, "payload chunk payload " + payload);
endofmsg = (payload.has(KEY_END_OF_MESSAGE)) ? payload.getBoolean(KEY_END_OF_MESSAGE) : false;
if (payload.has(KEY_COMPRESSION_ALGORITHM)) {
final String algoName = payload.getString(KEY_COMPRESSION_ALGORITHM);
try {
compressionAlgo = CompressionAlgorithm.valueOf(algoName);
} catch (final IllegalArgumentException e) {
throw new MslMessageException(MslError.UNIDENTIFIED_COMPRESSION, algoName, e);
}
} else {
compressionAlgo = null;
}
final byte[] compressedData = payload.getBytes(KEY_DATA);
if (compressedData.length == 0) {
if (!endofmsg)
throw new MslMessageException(MslError.PAYLOAD_DATA_MISSING);
data = new byte[0];
} else if (compressionAlgo == null) {
data = compressedData;
} else {
data = MslCompression.uncompress(compressionAlgo, compressedData);
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "payload chunk payload " + Base64.encode(plaintext), e);
}
}
/**
* @return the sequence number.
*/
public long getSequenceNumber() {
return sequenceNumber;
}
/**
* @return the message ID.
*/
public long getMessageId() {
return messageId;
}
/**
* @return true if this is the last payload chunk of the message.
*/
public boolean isEndOfMessage() {
return endofmsg;
}
/**
* @return the compression algorithm. May be {@code null} if not
* not compressed.
*/
public CompressionAlgorithm getCompressionAlgo() {
return compressionAlgo;
}
/**
* Returns the application data if we were able to decrypt it.
*
* @return the chunk application data. May be empty (zero-length).
*/
public byte[] getData() {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
// Return any cached encoding.
if (encodings.containsKey(format))
return encodings.get(format);
// Encrypt the payload.
final byte[] plaintext = encoder.encodeObject(payload, format);
final byte[] ciphertext;
try{
ciphertext = cryptoContext.encrypt(plaintext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error encrypting the payload.", e);
}
// Sign the payload.
final byte[] signature;
try {
signature = cryptoContext.sign(ciphertext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error signing the payload.", e);
}
// Encode the payload chunk.
final MslObject mo = encoder.createObject();
mo.put(KEY_PAYLOAD, ciphertext);
mo.put(KEY_SIGNATURE, signature);
final byte[] encoding = encoder.encodeObject(mo, format);
// Cache and return the encoding.
encodings.put(format, encoding);
return encoding;
}
/* (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 PayloadChunk)) return false;
final PayloadChunk that = (PayloadChunk)obj;
return sequenceNumber == that.sequenceNumber &&
messageId == that.messageId &&
endofmsg == that.endofmsg &&
compressionAlgo == that.compressionAlgo &&
Arrays.equals(data, that.data);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Long.valueOf(sequenceNumber).hashCode() ^
Long.valueOf(messageId).hashCode() ^
Boolean.valueOf(endofmsg).hashCode() ^
((compressionAlgo != null) ? compressionAlgo.hashCode() : 0) ^
Arrays.hashCode(data);
}
/** Payload. */
private final MslObject payload;
/** Sequence number. */
private final long sequenceNumber;
/** Message ID. */
private final long messageId;
/** End of message flag. */
private final boolean endofmsg;
/** Compression algorithm. */
private final CompressionAlgorithm compressionAlgo;
/** The application data. */
private final byte[] data;
/** Payload crypto context. */
protected final ICryptoContext cryptoContext;
/** Cached encodings. */
protected final Map<MslEncoderFormat,byte[]> encodings = new HashMap<MslEncoderFormat,byte[]>();
}
| 1,702 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageInputStream.java
|
/**
* Copyright (c) 2012-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.msg;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
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.MslInternalException;
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.crypto.SessionCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.io.MslTokenizer;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.KeyResponseData;
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.userauth.UserAuthenticationData;
import com.netflix.msl.util.MslContext;
/**
* <p>A MSL message consists of a single MSL header followed by one or more
* payload chunks carrying application data. Each payload chunk is individually
* packaged but sequentially ordered. No payload chunks may be included in an
* error message.</p>
*
* <p>Data is read until an end-of-message payload chunk is encountered or an
* error occurs. Closing a {@code MessageInputStream} does not close the source
* input stream in case additional MSL messages will be read.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MessageInputStream extends InputStream {
/**
* <p>Return the crypto context resulting from key response data contained
* in the provided header.</p>
*
* <p>The {@link MslException}s thrown by this method will not have the
* entity or user set.</p>
*
* @param ctx MSL context.
* @param header header.
* @param keyRequestData key request data for key exchange.
* @return the crypto context or null if the header does not contain key
* response data or is for an error message.
* @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 MslCryptoException if the crypto context cannot be created.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be.
* @throws MslEntityAuthException if there is a problem with the master
* token identity.
*/
private static ICryptoContext getKeyxCryptoContext(final MslContext ctx, final MessageHeader header, final Set<KeyRequestData> keyRequestData) throws MslCryptoException, MslKeyExchangeException, MslEncodingException, MslMasterTokenException, MslEntityAuthException {
// Pull the header data.
final MessageHeader messageHeader = header;
final MasterToken masterToken = messageHeader.getMasterToken();
final KeyResponseData keyResponse = messageHeader.getKeyResponseData();
// If there is no key response data then return null.
if (keyResponse == null)
return null;
// If the key response data master token is decrypted then use the
// master token keys to create the crypto context.
final MasterToken keyxMasterToken = keyResponse.getMasterToken();
if (keyxMasterToken.isDecrypted())
return new SessionCryptoContext(ctx, keyxMasterToken);
// Perform the key exchange.
final KeyExchangeScheme responseScheme = keyResponse.getKeyExchangeScheme();
final KeyExchangeFactory factory = ctx.getKeyExchangeFactory(responseScheme);
if (factory == null)
throw new MslKeyExchangeException(MslError.KEYX_FACTORY_NOT_FOUND, responseScheme.name());
// Attempt the key exchange but if it fails then try with the next
// key request data before giving up.
MslException keyxException = null;
final Iterator<KeyRequestData> keyRequests = keyRequestData.iterator();
while (keyRequests.hasNext()) {
final KeyRequestData keyRequest = keyRequests.next();
final KeyExchangeScheme requestScheme = keyRequest.getKeyExchangeScheme();
// Skip incompatible key request data.
if (!responseScheme.equals(requestScheme))
continue;
try {
return factory.getCryptoContext(ctx, keyRequest, keyResponse, masterToken);
} catch (final MslKeyExchangeException e) {
if (!keyRequests.hasNext()) throw e;
keyxException = e;
} catch (final MslEncodingException e) {
if (!keyRequests.hasNext()) throw e;
keyxException = e;
} catch (final MslMasterTokenException e) {
if (!keyRequests.hasNext()) throw e;
keyxException = e;
} catch (final MslEntityAuthException e) {
if (!keyRequests.hasNext()) throw e;
keyxException = e;
}
}
// We did not perform a successful key exchange. If we caught an
// exception then throw that exception now.
if (keyxException != null) {
if (keyxException instanceof MslKeyExchangeException)
throw (MslKeyExchangeException)keyxException;
if (keyxException instanceof MslEncodingException)
throw (MslEncodingException)keyxException;
if (keyxException instanceof MslMasterTokenException)
throw (MslMasterTokenException)keyxException;
if (keyxException instanceof MslEntityAuthException)
throw (MslEntityAuthException)keyxException;
throw new MslInternalException("Unexpected exception caught during key exchange.", keyxException);
}
// If we did not perform a successful key exchange then the
// payloads will not decrypt properly. Throw an exception.
throw new MslKeyExchangeException(MslError.KEYX_RESPONSE_REQUEST_MISMATCH, Arrays.toString(keyRequestData.toArray()));
}
/**
* <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 does not contain an entity
* authentication data or a master token, the header data is
* missing or invalid, or the message ID is negative, or the
* message is not encrypted and contains user authentication data,
* or 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 MessageInputStream(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 {
// Parse the header.
this.ctx = ctx;
this.source = source;
final MslObject mo;
try {
this.tokenizer = this.ctx.getMslEncoderFactory().createTokenizer(source);
if (!this.tokenizer.more(-1))
throw new MslEncodingException(MslError.MESSAGE_DATA_MISSING);
mo = this.tokenizer.nextObject(-1);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "header", e);
}
this.header = Header.parseHeader(ctx, mo, cryptoContexts);
try {
// For error messages there are no key exchange or payload crypto
// contexts.
if (this.header instanceof ErrorHeader) {
this.keyxCryptoContext = null;
this.cryptoContext = null;
return;
}
// Grab the key exchange crypto context, if any.
final MessageHeader messageHeader = (MessageHeader)this.header;
this.keyxCryptoContext = getKeyxCryptoContext(ctx, messageHeader, keyRequestData);
// In peer-to-peer mode or in trusted network mode with no key
// exchange the payload crypto context equals the header crypto
// context.
if (ctx.isPeerToPeer() || this.keyxCryptoContext == null)
this.cryptoContext = messageHeader.getCryptoContext();
// Otherwise the payload crypto context equals the key exchange
// crypto context.
else
this.cryptoContext = this.keyxCryptoContext;
// If this is a handshake message but it is not renewable or does
// not contain key request data then reject the message.
if (messageHeader.isHandshake() &&
(!messageHeader.isRenewable() || messageHeader.getKeyRequestData().isEmpty()))
{
throw new MslMessageException(MslError.HANDSHAKE_DATA_MISSING, messageHeader.toString());
}
// If I am in peer-to-peer mode or the master token is verified
// (i.e. issued by the local entity which is therefore a trusted
// network server) then perform the master token checks.
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null && (ctx.isPeerToPeer() || masterToken.isVerified())) {
// If the master token has been revoked then reject the
// message.
final TokenFactory factory = ctx.getTokenFactory();
final MslError revoked = factory.isMasterTokenRevoked(ctx, masterToken);
if (revoked != null)
throw new MslMasterTokenException(revoked, masterToken);
// If the user ID token has been revoked then reject the
// message. We know the master token is not null and that it is
// verified so we assume the user ID token is as well.
final UserIdToken userIdToken = messageHeader.getUserIdToken();
if (userIdToken != null) {
final MslError uitRevoked = factory.isUserIdTokenRevoked(ctx, masterToken, userIdToken);
if (uitRevoked != null)
throw new MslUserIdTokenException(uitRevoked, userIdToken);
}
// If the master token is expired...
if (masterToken.isExpired(null)) {
// If the message is not renewable or does not contain key
// request data then reject the message.
if (!messageHeader.isRenewable())
throw new MslMessageException(MslError.MESSAGE_EXPIRED_NOT_RENEWABLE, messageHeader.toString());
else if (messageHeader.getKeyRequestData().isEmpty())
throw new MslMessageException(MslError.MESSAGE_EXPIRED_NO_KEYREQUEST_DATA, messageHeader.toString());
// If the master token will not be renewed by the token
// factory then reject the message.
//
// This throws an exception if the master token is not
// renewable.
final MslError notRenewable = factory.isMasterTokenRenewable(ctx, masterToken);
if (notRenewable != null)
throw new MslMessageException(notRenewable, "Master token is expired and not renewable.");
}
}
// If the message is non-replayable (it is not from a trusted
// network server).
final Long nonReplayableId = messageHeader.getNonReplayableId();
if (nonReplayableId != null) {
// ...and does not include a master token then reject the
// message.
if (masterToken == null)
throw new MslMessageException(MslError.INCOMPLETE_NONREPLAYABLE_MESSAGE, messageHeader.toString());
// If the non-replayable ID is not accepted then notify the
// sender.
final TokenFactory factory = ctx.getTokenFactory();
final MslError replayed = factory.acceptNonReplayableId(ctx, masterToken, nonReplayableId);
if (replayed != null)
throw new MslMessageException(replayed, messageHeader.toString());
}
} catch (final MslException e) {
if (this.header instanceof MessageHeader) {
final MessageHeader messageHeader = (MessageHeader)this.header;
e.setMasterToken(messageHeader.getMasterToken());
e.setEntityAuthenticationData(messageHeader.getEntityAuthenticationData());
e.setUserIdToken(messageHeader.getUserIdToken());
e.setUserAuthenticationData(messageHeader.getUserAuthenticationData());
e.setMessageId(messageHeader.getMessageId());
} else {
final ErrorHeader errorHeader = (ErrorHeader)this.header;
e.setEntityAuthenticationData(errorHeader.getEntityAuthenticationData());
e.setMessageId(errorHeader.getMessageId());
}
throw e;
}
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
// Do not close the source because we might want to reuse it.
super.finalize();
}
/**
* Retrieve the next MSL object.
*
* @return the next MSL object or null if none remaining.
* @throws MslEncodingException if there is a problem parsing the data.
*/
protected MslObject nextMslObject() throws MslEncodingException {
// Make sure this message is allowed to have payload chunks.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
throw new MslInternalException("Read attempted with error message.");
// If we previously reached the end of the message, don't try to read
// more.
if (eom)
return null;
// Otherwise read the next MSL object.
try {
if (!tokenizer.more(-1)) {
eom = true;
return null;
}
return tokenizer.nextObject(-1);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "payloadchunk", e);
}
}
/**
* Create a new payload chunk
*
* @param ctx the MSL context.
* @param mo the MSL object.
* @param cryptoContext the crypto context.
* @throws MslCryptoException if there is a problem decrypting or verifying
* the payload chunk.
* @throws MslEncodingException if there is a problem parsing the data.
* @throws MslMessageException if the compression algorithm is not known,
* or the payload data is corrupt or missing.
* @throws MslException if there is an error uncompressing the data.
*/
protected PayloadChunk createPayloadChunk(final MslContext ctx, final MslObject mo, final ICryptoContext cryptoContext) throws MslEncodingException, MslCryptoException, MslMessageException, MslException {
return new PayloadChunk(ctx, mo, cryptoContext);
}
/**
* Retrieve the next payload chunk data.
*
* @return the next payload chunk data or null if none remaining.
* @throws MslCryptoException if there is a problem decrypting or verifying
* the payload chunk.
* @throws MslEncodingException if there is a problem parsing the data.
* @throws MslMessageException if the payload verification failed.
* @throws MslInternalException if attempting to access payloads of an
* error message.
* @throws MslException if there is an error uncompressing the data.
*/
protected ByteArrayInputStream nextData() throws MslCryptoException, MslEncodingException, MslMessageException, MslInternalException, MslException {
// Make sure this message is allowed to have payload chunks.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
throw new MslInternalException("Read attempted with error message.");
// If reading buffered data return the next buffered payload data.
if (payloadIterator != null && payloadIterator.hasNext())
return payloadIterator.next();
// Otherwise read the next payload.
final MslObject mo = nextMslObject();
if (mo == null) return null;
final PayloadChunk payload = createPayloadChunk(ctx, mo, cryptoContext);
// Make sure the payload belongs to this message and is the one we are
// expecting.
final MasterToken masterToken = messageHeader.getMasterToken();
final EntityAuthenticationData entityAuthData = messageHeader.getEntityAuthenticationData();
final UserIdToken userIdToken = messageHeader.getUserIdToken();
final UserAuthenticationData userAuthData = messageHeader.getUserAuthenticationData();
if (payload.getMessageId() != messageHeader.getMessageId()) {
throw new MslMessageException(MslError.PAYLOAD_MESSAGE_ID_MISMATCH, "payload mid " + payload.getMessageId() + " header mid " + messageHeader.getMessageId())
.setMasterToken(masterToken)
.setEntityAuthenticationData(entityAuthData)
.setUserIdToken(userIdToken)
.setUserAuthenticationData(userAuthData);
}
if (payload.getSequenceNumber() != payloadSequenceNumber) {
throw new MslMessageException(MslError.PAYLOAD_SEQUENCE_NUMBER_MISMATCH, "payload seqno " + payload.getSequenceNumber() + " expected seqno " + payloadSequenceNumber)
.setMasterToken(masterToken)
.setEntityAuthenticationData(entityAuthData)
.setUserIdToken(userIdToken)
.setUserAuthenticationData(userAuthData);
}
++payloadSequenceNumber;
// FIXME remove this logic once the old handshake inference logic
// is no longer supported.
// Check for a handshake if this is the first payload chunk.
if (handshake == null) {
handshake = (messageHeader.isRenewable() && !messageHeader.getKeyRequestData().isEmpty() &&
payload.isEndOfMessage() && payload.getData().length == 0);
}
// Check for end of message.
if (payload.isEndOfMessage())
eom = true;
// If mark was called save the payload in the buffer. We have to unset
// the payload iterator since we're adding to the payloads list.
final ByteArrayInputStream data = new ByteArrayInputStream(payload.getData());
if (payloads != null) {
payloads.add(data);
payloadIterator = null;
}
return data;
}
/**
* Returns true if the message is a handshake message.
*
* FIXME
* This method should be removed by a direct query of the message header
* once the old behavior of inferred handshake messages based on a single
* empty payload chunk is no longer supported.
*
* @return true if the message is a handshake message.
* @throws MslCryptoException if there is a problem decrypting or verifying
* the payload chunk.
* @throws MslEncodingException if there is a problem parsing the data.
* @throws MslMessageException if the payload verification failed.
* @throws MslInternalException if attempting to access payloads of an
* error message.
* @throws MslException if there is an error uncompressing the data.
*/
public boolean isHandshake() throws MslCryptoException, MslEncodingException, MslMessageException, MslInternalException, MslException {
final MessageHeader messageHeader = getMessageHeader();
// Error messages are not handshake messages.
if (messageHeader == null) return false;
// If the message header has its handshake flag set return true.
if (messageHeader.isHandshake()) return true;
// If we haven't read a payload we don't know if this is a handshake
// message or not. This also implies the current payload is null.
if (handshake == null) {
try {
// nextData() will set the value of handshake if a payload is
// found.
currentPayload = nextData();
if (currentPayload == null)
handshake = Boolean.FALSE;
} catch (final MslException e) {
// Save the exception to be thrown next time read() is called.
readException = new IOException("Error reading the payload chunk.", e);
throw e;
}
}
// Return the current handshake status.
return handshake.booleanValue();
}
/**
* @return the message header. Will be null for error messages.
*/
public MessageHeader getMessageHeader() {
if (header instanceof MessageHeader)
return (MessageHeader)header;
return null;
}
/**
* @return the error header. Will be null except for error messages.
*/
public ErrorHeader getErrorHeader() {
if (header instanceof ErrorHeader)
return (ErrorHeader)header;
return null;
}
/**
* Returns the sender's entity identity. The identity will be unknown if
* the local entity is a trusted network client and the message was sent by
* a trusted network server using the local entity's master token.
*
* @return the sender's entity identity or null if unknown.
* @throws MslCryptoException if there is a crypto error accessing the
* entity identity;
*/
public String getIdentity() throws MslCryptoException {
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader != null) {
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
return masterToken.getIdentity();
return messageHeader.getEntityAuthenticationData().getIdentity();
}
final ErrorHeader errorHeader = getErrorHeader();
return errorHeader.getEntityAuthenticationData().getIdentity();
}
/**
* Returns the user associated with the message. The user will be unknown
* if the local entity is a trusted network client and the message was sent
* by a trusted network server.
*
* @return the user associated with the message or null if unknown.
*/
public MslUser getUser() {
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
return null;
return messageHeader.getUser();
}
/**
* @return the payload crypto context. Will be null for error messages.
*/
public ICryptoContext getPayloadCryptoContext() {
return cryptoContext;
}
/**
* @return the key exchange crypto context. Will be null if no key response
* data was returned in this message and for error messages.
*/
public ICryptoContext getKeyExchangeCryptoContext() {
return keyxCryptoContext;
}
/**
* Returns true if the payload application data is encrypted. This will be
* true if the entity authentication scheme provides encryption or if
* session keys were used. Returns false for error messages which do not
* have any payload chunks.
*
* @return true if the payload application data is encrypted. Will be false
* for error messages.
*/
public boolean encryptsPayloads() {
// Return false for error messages.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
return false;
// If the message uses entity authentication data for an entity
// authentication scheme that provides encryption, return true.
final EntityAuthenticationData entityAuthData = messageHeader.getEntityAuthenticationData();
if (entityAuthData != null && entityAuthData.getScheme().encrypts())
return true;
// If the message uses a master token, return true.
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
return true;
// If the message includes key response data, return true.
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null)
return true;
// Otherwise return false.
return false;
}
/**
* Returns true if the payload application data is integrity protected.
* This will be true if the entity authentication scheme provides integrity
* protection or if session keys were used. Returns false for error
* messages which do not have any payload chunks.
*
* @return true if the payload application data is integrity protected.
* Will be false for error messages.
*/
public boolean protectsPayloadIntegrity() {
// Return false for error messages.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
return false;
// If the message uses entity authentication data for an entity
// authentication scheme that provides integrity protection, return
// true.
final EntityAuthenticationData entityAuthData = messageHeader.getEntityAuthenticationData();
if (entityAuthData != null && entityAuthData.getScheme().protectsIntegrity())
return true;
// If the message uses a master token, return true.
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
return true;
// If the message includes key response data, return true.
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null)
return true;
// Otherwise return false.
return false;
}
/* (non-Javadoc)
* @see java.io.InputStream#available()
*/
@Override
public int available() throws IOException {
// Start with the amount available in the current payload.
if (currentPayload == null) return 0;
int available = currentPayload.available();
// If there is buffered data, iterate over all subsequent buffered
// payloads.
if (payloads != null) {
final int startIndex = payloads.indexOf(currentPayload);
if (startIndex != -1 && startIndex < payloads.size() - 1) {
final Iterator<ByteArrayInputStream> nextPayloads = payloads.listIterator(startIndex + 1);
while (nextPayloads.hasNext()) {
final ByteArrayInputStream payload = nextPayloads.next();
available += payload.available();
}
}
}
// Return available bytes.
return available;
}
/**
* By default the source input stream is not closed when this message input
* stream is closed. If it should be closed then this method can be used to
* dictate the desired behavior.
*
* @param close true if the source input stream should be closed, false if
* it should not.
*/
public void closeSource(final boolean close) {
this.closeSource = close;
}
/* (non-Javadoc)
* @see java.io.InputStream#close()
*/
@Override
public void close() throws IOException {
// Close the tokenizer.
try {
tokenizer.close();
} catch (final MslEncoderException e) {
// Ignore exceptions.
}
// Only close the source if instructed to do so because we might want
// to reuse the connection.
if (closeSource) {
source.close();
}
// Otherwise if this is not a handshake message or error message then
// consume all payloads that may still be on the source input stream.
else {
try {
if (!isHandshake() && getMessageHeader() != null) {
while (true) {
final ByteArrayInputStream data = nextData();
if (data == null) break;
}
}
} catch (final MslException e) {
// Ignore exceptions.
}
}
}
/* (non-Javadoc)
* @see java.io.InputStream#mark(int)
*/
@Override
public void mark(final int readlimit) {
// Remember the read limit, reset the read count.
this.readlimit = readlimit;
this.readcount = 0;
// Start buffering.
buffering = true;
// If there is a current payload...
if (currentPayload != null) {
// Remove all buffered data earlier than the current payload.
while (payloads.size() > 0 && !payloads.get(0).equals(currentPayload))
payloads.remove(0);
// Add the current payload if it was not already buffered.
if (payloads.size() == 0)
payloads.add(currentPayload);
// Reset the iterator to continue reading buffered data from the
// current payload.
payloadIterator = payloads.listIterator();
currentPayload = payloadIterator.next();
// Set the new mark point on the current payload.
currentPayload.mark(readlimit);
return;
}
// Otherwise we've either read to the end or haven't read anything at
// all yet. Discard all buffered data.
payloadIterator = null;
payloads.clear();
}
/* (non-Javadoc)
* @see java.io.InputStream#markSupported()
*/
@Override
public boolean markSupported() {
return true;
}
/* (non-Javadoc)
* @see java.io.InputStream#read()
*/
@Override
public int read() throws IOException {
final byte[] b = new byte[1];
if (read(b) == -1) return -1;
return b[0];
}
/* (non-Javadoc)
* @see java.io.InputStream#read(byte[], int, int)
*/
@Override
public int read(final byte[] cbuf, final int off, final int len) throws IOException {
// Throw any cached read exception.
if (readException != null) {
final IOException e = readException;
readException = null;
throw e;
}
// Return end of stream immediately for handshake messages.
try {
if (this.isHandshake())
return -1;
} catch (final MslException e) {
// FIXME
// Unset the read exception since we are going to throw it right
// now. This logic can go away once the old handshake logic is
// removed.
readException = null;
throw new IOException("Error reading the payload chunk.", e);
}
// Read from payloads until we are done or cannot read anymore.
int bytesRead = 0;
while (bytesRead < len) {
final int read = (currentPayload != null) ? currentPayload.read(cbuf, off + bytesRead, len - bytesRead) : -1;
// If we read some data continue.
if (read != -1) {
bytesRead += read;
continue;
}
// Otherwise grab the next payload data.
try {
currentPayload = nextData();
if (currentPayload == null)
break;
} catch (final MslException e) {
// If we already read some data return it and save the
// exception to be thrown next time read() is called.
final IOException ioe = new IOException("Error reading the payload chunk.", e);
if (bytesRead > 0) {
readException = ioe;
return bytesRead;
}
// Otherwise throw the exception now.
throw ioe;
}
}
// If nothing was read (but something was requested) return end of
// stream.
if (bytesRead == 0 && len > 0)
return -1;
// If buffering data increment the read count.
if (buffering) {
readcount += bytesRead;
// If the read count exceeds the read limit stop buffering payloads
// and reset the read count and limit, but retain the payload
// iterator as we need to continue reading from any buffered data.
if (readcount > readlimit) {
buffering = false;
readcount = readlimit = 0;
}
}
// Return the number of bytes read.
return bytesRead;
}
/* (non-Javadoc)
* @see java.io.InputStream#read(byte[])
*/
@Override
public int read(final byte[] cbuf) throws IOException {
return read(cbuf, 0, cbuf.length);
}
/* (non-Javadoc)
* @see java.io.InputStream#reset()
*/
@Override
public void reset() throws IOException {
// Do nothing if we are not buffering.
if (!buffering)
return;
// Reset all payloads and initialize the payload iterator.
//
// We need to reset the payloads since we are going to re-read them and
// want the correct value returned when queried for available bytes.
for (final ByteArrayInputStream payload : payloads)
payload.reset();
payloadIterator = payloads.listIterator();
if (payloadIterator.hasNext()) {
currentPayload = payloadIterator.next();
} else {
currentPayload = null;
}
// Reset the read count.
readcount = 0;
}
/* (non-Javadoc)
* @see java.io.InputStream#skip(long)
*/
@Override
public long skip(final long n) throws IOException {
// Skip from payloads until we are done or cannot skip anymore.
int bytesSkipped = 0;
while (bytesSkipped < n) {
final long skipped = (currentPayload != null) ? currentPayload.skip(n - bytesSkipped) : 0;
// If we skipped some data continue.
if (skipped != 0) {
bytesSkipped += skipped;
continue;
}
// Otherwise grab the next payload data.
try {
currentPayload = nextData();
if (currentPayload == null)
break;
} catch (final MslInternalException e) {
throw new IOException("Cannot skip data off an error message.", e);
} catch (final MslException e) {
throw new IOException("Error skipping in the payload chunk.", e);
}
}
return bytesSkipped;
}
/** MSL context. */
private final MslContext ctx;
/** MSL input stream. */
private final InputStream source;
/** MSL tokenizer. */
private final MslTokenizer tokenizer;
/** Header. */
private final Header header;
/** Payload crypto context. */
private final ICryptoContext cryptoContext;
/** Key exchange crypto context. */
private final ICryptoContext keyxCryptoContext;
/** Current payload sequence number. */
private long payloadSequenceNumber = 1;
/** End of message reached. */
private boolean eom = false;
/** Handshake message. */
private Boolean handshake = null;
/** True if the source input stream should be closed. */
private boolean closeSource = false;
/** True if buffering. */
private boolean buffering = false;
/**
* Buffered payload data.
*
* This list contains all payload data that has been referenced since the
* last call to {@link #mark(int)}.
*/
private final List<ByteArrayInputStream> payloads = new LinkedList<ByteArrayInputStream>();;
/** Buffered payload data iterator. Not null if reading buffered data. */
private ListIterator<ByteArrayInputStream> payloadIterator = null;
/** Mark read limit. */
private int readlimit = 0;
/** Mark read count. */
private int readcount = 0;
/** Current payload chunk data. */
private ByteArrayInputStream currentPayload = null;
/** Cached read exception. */
private IOException readException = null;
}
| 1,703 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageContext.java
|
/**
* Copyright (c) 2012-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.msg;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslConstants.ResponseCode;
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.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* <p>The message context provides the information that should be used to
* construct a single message. Each message should have its own context.</p>
*
* <p>All context methods may be called multiple times except for
* {@code #write(OutputStream)} which is guaranteed to be called only once.
* (The written data will be cached in memory in case the message needs to be
* resent.)</p>
*
* @author Wesley Miaw <[email protected]>
*/
public interface MessageContext {
/** Re-authentication reason codes. */
public static enum ReauthCode {
/** The user authentication data did not identify a user. */
USERDATA_REAUTH(ResponseCode.USERDATA_REAUTH),
/** The single-sign-on token was rejected as bad, invalid, or expired. */
SSOTOKEN_REJECTED(ResponseCode.SSOTOKEN_REJECTED),
;
/**
* @return the re-authentication code corresponding to the response
* code.
* @throws IllegalArgumentException if the response code does not map
* onto a re-authentication code.
*/
public static ReauthCode valueOf(final ResponseCode code) {
for (final ReauthCode value : ReauthCode.values()) {
if (value.code == code)
return value;
}
throw new IllegalArgumentException("Unknown reauthentication code value " + code + ".");
}
/**
* Create a new re-authentication code mapped from the specified
* response code.
*
* @param code the response code for the re-authentication code.
*/
private ReauthCode(final ResponseCode code) {
this.code = code;
}
/**
* @return the integer value of the response code.
*/
public int intValue() {
return code.intValue();
}
/** The response code value. */
private final ResponseCode code;
}
/**
* <p>Called when receiving a message to process service tokens.</p>
*
* <p>This method should return a map of crypto contexts by service token
* name for all known service tokens. If the service token name is not
* found then the crypto context mapped onto the empty string will be
* used if found.</p>
*
* @return the service token crypto contexts.
*/
public Map<String,ICryptoContext> getCryptoContexts();
/**
* <p>Called to identify the expected remote entity identity. If the remote
* entity identity is not known this method must return {@code null}.</p>
*
* <p>Trusted network servers may always return {@code null}.</p>
*
* @return the remote entity identity or {@code null} if the identity is
* not known.
*/
public String getRemoteEntityIdentity();
/**
* <p>Called to determine if the message application data must be
* encrypted.</p>
*
* @return true if the application data must be encrypted.
*/
public boolean isEncrypted();
/**
* <p>Called to determine if the message application data must be integrity
* protected.</p>
*
* @return true if the application data must be integrity protected.
*/
public boolean isIntegrityProtected();
/**
* <p>Called to determine if a message should be marked as non-replayable.</p>
*
* <p>Trusted network servers must always return {@code false}.</p>
*
* @return true if the application data should not be carried in a
* replayable message.
*/
public boolean isNonReplayable();
/**
* <p>Called to determine if a message is requesting a master token, user
* ID token, or service tokens.</p>
*
* <p>Trusted network servers must always return {@code false}.</p>
*
* @return true if the message must have a master token and user ID token
* (if associated with a user) or must be carried in a renewable
* message to acquire said tokens.
*/
public boolean isRequestingTokens();
/**
* <p>Called to identify the local user the message should be sent with. If
* a user ID token exists for this user it will be used.</p>
*
* <p>Trusted network servers must always return {@code null}.</p>
*
* <p>Any non-null value returned by this method must match the local user
* associated with the user authentication data returned by
* {@link #getUserAuthData(ReauthCode, boolean, boolean)}.</p>
*
* <p>This method may return a non-null value when
* {@link #getUserAuthData(ReauthCode, boolean, boolean)} will return null
* if the message should be associated with a user but there is no user
* authentication data. For example during new user creation.</p>
*
* <p>This method must return {@code null} if the message should not be
* associated with a user and
* {@link #getUserAuthData(ReauthCode, boolean, boolean)} will also return
* {@code null}.</p>
*
* @return the local user identity or null.
*/
public String getUserId();
/**
* <p>Called if the user ID is not {@code null} to attach user
* authentication data to messages.</p>
*
* <p>Trusted network servers must always return {@code null}.</p>
*
* <p>This method should return user authentication data if the message
* should be associated with a user that has not already received a user ID
* token. This may involve prompting the user for credentials. If the
* message should not be associated with a user, a user ID token already
* exists for the user, or if user credentials are unavailable then this
* method should return {@code null}.</p>
*
* <p>The one exception is if the application wishes to re-authenticate the
* user against the current user ID token in which case this method should
* return user authentication data. The {@code renewable} parameter may be
* used to limit this operation to renewable messages.</p>
*
* <p>This method may be called if user re-authentication is required for
* the transaction to complete. If the application knows that user
* authentication is required for the request being sent and is unable to
* provide user authentication data then it should attempt to cancel the
* request and return {@code null}.</p>
*
* <p>If the {@code reauthCode} parameter is non-{@code null} then new user
* authentication data should be returned for this and all subsequent calls.
* The application may wish to return {@code null} if it knows that the
* request being sent can no longer succeed because the existing user ID
* token or service tokens are no longer valid. This will abort the
* request. Note that a {@code reauthCode} argument may be provided even if
* no user authentication data was included in the message.</p>
*
* <p>If the {@code required} parameter is true then user authentication
* should be returned for this call, even if a user ID token already exists
* for the user. {@code null} should still be returned when {@code required}
* is true if the message should be associated with a user but there is no
* user authentication data. For example during new user creation.</p>
*
* <p>This method will be called multiple times.</p>
*
* @param reauthCode non-{@code null} if new user authentication data is
* required. The reason the old user authentication data was
* rejected is identified by the code.
* @param renewable true if the message being sent is renewable.
* @param required true if user authentication data must be returned.
* @return the user authentication data or null.
*/
public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required);
/**
* <p>Called if a message does not contain a user ID token for the remote
* user.</p>
*
* <p>Trusted network clients must always return {@code null}.</p>
*
* <p>If a non-null value is returned by this method and a master token
* exists for the remote entity then a new user ID token will be created
* for the remote user and sent in the message. This is not the user
* identified by {@link #getUserId()} or authenticated by
* {@link #getUserAuthData(ReauthCode, boolean, boolean)} as those methods
* are used for the local user.</p>
*
* @return the user to attach to the message or null.
*/
public MslUser getUser();
/**
* <p>Called if a request is eligible for key exchange (i.e. the request
* is renewable and contains entity authentication data or a renewable
* master token).</p>
*
* <p>Trusted network servers must always return the empty set.</p>
*
* <p>This method must return key request data for all supported key
* exchange schemes. Failure to provide any key request data may result in
* message delivery failures.</p>
*
* <p>This method may also be called if entity re-authentication is required
* for the transaction to complete.</p>
*
* @return the key request data. May be the empty set.
* @throws MslKeyExchangeException if there is an error generating the key
* request data.
*/
public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException;
/**
* <p>Called prior to message sending to allow the processor to modify the
* message being built.</p>
*
* <p>The boolean {@code handshake} will be true if the function is being
* called for a handshake message that must be sent before the application
* data can be sent. The builder for handshake messages may lack a master
* token, user ID token, and other bound service tokens.</p>
*
* <p>The processor must not attempt to access or retain a reference to the
* builder after this function completes.</p>
*
* <p>This method will be called multiple times. The set of service tokens
* managed by the provided message service token builder may be different
* for each call. The processor should treat each call to this method
* independently from each other.</p>
*
* @param builder message service token builder.
* @param handshake true if the provided builder is for a handshake message.
* @throws MslMessageException if the builder throws an exception or the
* desired service tokens cannot be attached.
* @throws MslCryptoException if there is an error encrypting or signing
* the service token data.
* @throws MslEncodingException if there is an error encoding the service
* token JSON data.
* @throws MslException if there is an error compressing the data.
* @see com.netflix.msl.MslError#RESPONSE_REQUIRES_MASTERTOKEN
* @see com.netflix.msl.MslError#RESPONSE_REQUIRES_USERIDTOKEN
*/
public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) throws MslMessageException, MslCryptoException, MslEncodingException, MslException;
/**
* <p>Called when the message is ready to be sent. The processor should
* use the provided {@code MessageOutputStream} to write its application
* data. This method will only be called once.</p>
*
* <p>The processor must not attempt to access or retain a reference to the
* message output stream after this function completes. It is okay for this
* method to be long-running as the data will be streamed.</p>
*
* <p>If application data must be sent before the remote entity can reply
* then this method must call {@link MessageOutputStream#flush()} before
* returning. If all of the application data must be sent before the remote
* entity can reply then this method must call
* {@link MessageOutputStream#close()} before returning. Closing the
* message output stream will prevent further use of the output stream
* returned by {@link MslControl}.</p>
*
* @param output message output stream.
* @throws IOException if the output stream throws an I/O exception.
*/
public void write(final MessageOutputStream output) throws IOException;
/**
* Returns a message debug context applicable to the message being sent or
* received.
*
* @return the message debug context or {@code null} if there is none.
*/
public MessageDebugContext getDebugContext();
}
| 1,704 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/ResponseMessageBuilder.java
|
/**
* Copyright (c) 2012-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.msg;
import java.util.Arrays;
import java.util.Iterator;
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.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeFactory.KeyExchangeData;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.MslContext;
/**
* <p>Response message builder.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class ResponseMessageBuilder extends MessageBuilder {
/**
* Issue a new master token for the specified identity or renew an existing
* master token.
*
* @param ctx MSL context.
* @param format MSL encoder format.
* @param keyRequestData available key request data.
* @param masterToken master token to renew. Null if the identity is
* provided.
* @param entityAuthData entity authentication data. Null if a master token
* is provided.
* @return the new master token and crypto context or {@code} null if the
* factory chooses not to perform key exchange.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created or none
* of the key exchange schemes are supported.
* @throws MslMasterTokenException if the master token is not trusted.
* @throws MslEntityAuthException if there is a problem with the master
* token identity or entity identity.
* @throws MslException if there is an error creating or renewing the
* master token.
*/
private static KeyExchangeData issueMasterToken(final MslContext ctx, final MslEncoderFormat format, final Set<KeyRequestData> keyRequestData, final MasterToken masterToken, final EntityAuthenticationData entityAuthData) throws MslKeyExchangeException, MslCryptoException, MslMasterTokenException, MslEntityAuthException, MslException {
// Attempt key exchange in the preferred order.
MslException keyxException = null;
final Iterator<KeyExchangeFactory> factories = ctx.getKeyExchangeFactories().iterator();
while (factories.hasNext()) {
final KeyExchangeFactory factory = factories.next();
for (final KeyRequestData request : keyRequestData) {
if (!factory.getScheme().equals(request.getKeyExchangeScheme()))
continue;
// Attempt the key exchange, but if it fails try with the next
// combination before giving up.
try {
if (masterToken != null)
return factory.generateResponse(ctx, format, request, masterToken);
else
return factory.generateResponse(ctx, format, request, entityAuthData);
} catch (final MslCryptoException e) {
if (!factories.hasNext()) throw e;
keyxException = e;
} catch (final MslKeyExchangeException e) {
if (!factories.hasNext()) throw e;
keyxException = e;
} catch (final MslEncodingException e) {
if (!factories.hasNext()) throw e;
keyxException = e;
} catch (final MslMasterTokenException e) {
if (!factories.hasNext()) throw e;
keyxException = e;
} catch (final MslEntityAuthException e) {
if (!factories.hasNext()) throw e;
keyxException = e;
}
}
}
// We did not perform a successful key exchange. If we caught an
// exception then throw that exception now.
if (keyxException != null) {
if (keyxException instanceof MslCryptoException)
throw (MslCryptoException)keyxException;
if (keyxException instanceof MslKeyExchangeException)
throw (MslKeyExchangeException)keyxException;
if (keyxException instanceof MslEncodingException)
throw (MslEncodingException)keyxException;
if (keyxException instanceof MslMasterTokenException)
throw (MslMasterTokenException)keyxException;
if (keyxException instanceof MslEntityAuthException)
throw (MslEntityAuthException)keyxException;
throw new MslInternalException("Unexpected exception caught during key exchange.", keyxException);
}
// If we didn't find any then we're unable to perform key exchange.
throw new MslKeyExchangeException(MslError.KEYX_FACTORY_NOT_FOUND, Arrays.toString(keyRequestData.toArray()));
}
/**
* Create a new message builder that will craft a new message in response
* to another message. The constructed message may be used as a request.
*
* @param ctx MSL context.
* @param requestHeader message header to respond to.
* @throws MslMasterTokenException if the provided message's master token
* is not trusted.
* @throws MslCryptoException if the crypto context from a key exchange
* cannot be created.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created.
* @throws MslUserAuthException if there is an error with the user
* authentication data or the user ID token cannot be created.
* @throws MslException if a user ID token in the message header is not
* bound to its corresponding master token or there is an error
* creating or renewing the master token.
*/
public ResponseMessageBuilder(final MslContext ctx, final MessageHeader requestHeader) throws MslKeyExchangeException, MslCryptoException, MslMasterTokenException, MslUserAuthException, MslException {
super(ctx);
final MasterToken masterToken = requestHeader.getMasterToken();
final EntityAuthenticationData entityAuthData = requestHeader.getEntityAuthenticationData();
UserIdToken userIdToken = requestHeader.getUserIdToken();
final UserAuthenticationData userAuthData = requestHeader.getUserAuthenticationData();
// The response message ID must be equal to the request message ID + 1.
final long requestMessageId = requestHeader.getMessageId();
final long messageId = incrementMessageId(requestMessageId);
// Compute the intersection of the request and response message
// capabilities.
final MessageCapabilities capabilities = MessageCapabilities.intersection(requestHeader.getMessageCapabilities(), ctx.getMessageCapabilities());
// Identify the response format.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final Set<MslEncoderFormat> formats = (capabilities != null) ? capabilities.getEncoderFormats() : null;
final MslEncoderFormat format = encoder.getPreferredFormat(formats);
try {
// If the message contains key request data and is renewable...
final KeyExchangeData keyExchangeData;
final Set<KeyRequestData> keyRequestData = requestHeader.getKeyRequestData();
if (requestHeader.isRenewable() && !keyRequestData.isEmpty()) {
// If the message contains a master token...
if (masterToken != null) {
// If the master token is renewable or expired then renew
// the master token.
if (masterToken.isRenewable(null) || masterToken.isExpired(null))
keyExchangeData = issueMasterToken(ctx, format, keyRequestData, masterToken, null);
// Otherwise we don't need to do anything special.
else
keyExchangeData = null;
}
// Otherwise use the entity authentication data to issue a
// master token.
else {
// The message header is already authenticated via the
// entity authentication data's crypto context so we can
// simply proceed with the master token issuance.
keyExchangeData = issueMasterToken(ctx, format, keyRequestData, null, entityAuthData);
}
}
// If the message does not contain key request data there is no key
// exchange for us to do.
else {
keyExchangeData = null;
}
// If we successfully performed key exchange, use the new master
// token for user authentication.
final MasterToken userAuthMasterToken;
if (keyExchangeData != null) {
userAuthMasterToken = keyExchangeData.keyResponseData.getMasterToken();
} else {
userAuthMasterToken = masterToken;
}
// If the message contains a user ID token issued by the local
// entity...
if (userIdToken != null && userIdToken.isVerified()) {
// If the user ID token is renewable and the message is
// renewable, or it is expired, or it needs to be rebound
// to the new master token then renew the user ID token.
if ((userIdToken.isRenewable(null) && requestHeader.isRenewable()) ||
userIdToken.isExpired(null) ||
!userIdToken.isBoundTo(userAuthMasterToken))
{
final TokenFactory tokenFactory = ctx.getTokenFactory();
userIdToken = tokenFactory.renewUserIdToken(ctx, userIdToken, userAuthMasterToken);
}
}
// If the message is renewable and contains user authentication
// data and a master token then we need to attempt user
// authentication and issue a user ID token.
else if (requestHeader.isRenewable() && userAuthMasterToken != null && userAuthData != null) {
// If this request was parsed then its user authentication data
// should have been authenticated and the user will exist. If
// it was not parsed, then we need to perform user
// authentication now.
MslUser user = requestHeader.getUser();
if (user == null) {
final UserAuthenticationScheme scheme = userAuthData.getScheme();
final UserAuthenticationFactory factory = ctx.getUserAuthenticationFactory(scheme);
if (factory == null) {
throw new MslUserAuthException(MslError.USERAUTH_FACTORY_NOT_FOUND, scheme.name())
.setMasterToken(masterToken)
.setUserAuthenticationData(userAuthData)
.setMessageId(requestMessageId);
}
user = factory.authenticate(ctx, userAuthMasterToken.getIdentity(), userAuthData, null);
}
final TokenFactory tokenFactory = ctx.getTokenFactory();
userIdToken = tokenFactory.createUserIdToken(ctx, user, userAuthMasterToken);
}
// Create the message builder.
//
// Peer-to-peer responses swap the tokens.
final KeyResponseData keyResponseData = requestHeader.getKeyResponseData();
final Set<ServiceToken> serviceTokens = requestHeader.getServiceTokens();
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
final Set<ServiceToken> peerServiceTokens = requestHeader.getPeerServiceTokens();
initializeMessageBuilder(ctx, messageId, capabilities, peerMasterToken, peerUserIdToken, peerServiceTokens, masterToken, userIdToken, serviceTokens, keyExchangeData);
} else {
final MasterToken localMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : masterToken;
initializeMessageBuilder(ctx, messageId, capabilities, localMasterToken, userIdToken, serviceTokens, null, null, null, keyExchangeData);
}
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setUserIdToken(userIdToken);
e.setUserAuthenticationData(userAuthData);
e.setMessageId(requestMessageId);
throw e;
}
}
/**
* Create a new message builder that will craft a new message in response
* to another message without issuing or renewing any master tokens or user
* ID tokens. The constructed message may be used as a request.
*
* @param ctx MSL context.
* @param requestHeader message header to respond to.
* @throws MslCryptoException if there is an error accessing the remote
* entity identity.
* @throws MslException if any of the request's user ID tokens is not bound
* to its master token.
*/
public void createIdempotentResponse(final MslContext ctx, final MessageHeader requestHeader) throws MslCryptoException, MslException {
final MasterToken masterToken = requestHeader.getMasterToken();
final EntityAuthenticationData entityAuthData = requestHeader.getEntityAuthenticationData();
final UserIdToken userIdToken = requestHeader.getUserIdToken();
final UserAuthenticationData userAuthData = requestHeader.getUserAuthenticationData();
// The response message ID must be equal to the request message ID + 1.
final long requestMessageId = requestHeader.getMessageId();
final long messageId = incrementMessageId(requestMessageId);
// Compute the intersection of the request and response message
// capabilities.
final MessageCapabilities capabilities = MessageCapabilities.intersection(requestHeader.getMessageCapabilities(), ctx.getMessageCapabilities());
// Create the message builder.
//
// Peer-to-peer responses swap the tokens.
try {
final KeyResponseData keyResponseData = requestHeader.getKeyResponseData();
final Set<ServiceToken> serviceTokens = requestHeader.getServiceTokens();
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
final Set<ServiceToken> peerServiceTokens = requestHeader.getPeerServiceTokens();
initializeMessageBuilder(ctx, messageId, capabilities, peerMasterToken, peerUserIdToken, peerServiceTokens, masterToken, userIdToken, serviceTokens, null);
} else {
final MasterToken localMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : masterToken;
initializeMessageBuilder(ctx, messageId, capabilities, localMasterToken, userIdToken, serviceTokens, null, null, null, null);
}
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setUserIdToken(userIdToken);
e.setUserAuthenticationData(userAuthData);
e.setMessageId(requestMessageId);
throw e;
}
}
}
| 1,705 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageBuilder.java
|
/**
* Copyright (c) 2012-2020 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.msg;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.crypto.NullCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.keyx.KeyExchangeFactory.KeyExchangeData;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.msg.MessageHeader.HeaderData;
import com.netflix.msl.msg.MessageHeader.HeaderPeerData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslUtils;
/**
* <p>A message builder provides methods for building messages.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MessageBuilder {
/** Empty service token data. */
private static final byte[] EMPTY_DATA = new byte[0];
/**
* Increments the provided message ID by 1, wrapping around to zero if
* the provided value is equal to {@link MslConstants#MAX_LONG_VALUE}.
*
* @param messageId the message ID to increment.
* @return the message ID + 1.
* @throws MslInternalException if the provided message ID is out of range.
*/
public static long incrementMessageId(final long messageId) {
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is outside the valid range.");
return (messageId == MslConstants.MAX_LONG_VALUE) ? 0 : messageId + 1;
}
/**
* Decrements the provided message ID by 1, wrapping around to
* {@link MslConstants#MAX_LONG_VALUE} if the provided value is equal to 0.
*
* @param messageId the message ID to decrement.
* @return the message ID - 1.
* @throws MslInternalException if the provided message ID is out of range.
*/
public static long decrementMessageId(final long messageId) {
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is outside the valid range.");
return (messageId == 0) ? MslConstants.MAX_LONG_VALUE : messageId - 1;
}
/**
* <p>Create a new message builder.</p>
*
* @param ctx MSL context.
*/
protected MessageBuilder(final MslContext ctx) {
this.ctx = ctx;
}
/**
* <p>Create a new message builder that will craft a new message with the
* specified message ID.</p>
*
* @param ctx MSL context.
* @param masterToken master token. May be null unless a user ID token is
* provided.
* @param userIdToken user ID token. May be null.
* @param messageId the message ID to use. Must be within range.
* @throws MslException if a user ID token is not bound to its
* corresponding master token.
*/
public MessageBuilder(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken, final long messageId) throws MslException {
this.ctx = ctx;
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is outside the valid range.");
final MessageCapabilities capabilities = ctx.getMessageCapabilities();
initializeMessageBuilder(ctx, messageId, capabilities, masterToken, userIdToken, null, null, null, null, null);
}
/**
* <p>Create a new message builder that will craft a new message.</p>
*
* @param ctx MSL context.
* @param masterToken master token. May be null unless a user ID token is
* provided.
* @param userIdToken user ID token. May be null.
* @throws MslException if a user ID token is not bound to its
* corresponding master token.
*/
public MessageBuilder(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
this(ctx, masterToken, userIdToken, MslUtils.getRandomLong(ctx));
}
/**
* Initialize a message builder with the provided tokens and key exchange
* data if a master token was issued or renewed.
*
* @param ctx MSL context.
* @param messageId message ID.
* @param capabilities message capabilities.
* @param masterToken master token. May be null unless a user ID token is
* provided.
* @param userIdToken user ID token. May be null.
* @param serviceTokens initial set of service tokens. May be null.
* @param peerMasterToken peer master token. May be null unless a peer user
* ID token is provided.
* @param peerUserIdToken peer user ID token. May be null.
* @param peerServiceTokens initial set of peer service tokens.
* May be null.
* @param keyExchangeData key exchange data. May be null.
* @throws MslException if a user ID token is not bound to its master
* token.
*/
protected void initializeMessageBuilder(final MslContext ctx, final long messageId, final MessageCapabilities capabilities, final MasterToken masterToken, final UserIdToken userIdToken, final Set<ServiceToken> serviceTokens, final MasterToken peerMasterToken, final UserIdToken peerUserIdToken, final Set<ServiceToken> peerServiceTokens, final KeyExchangeData keyExchangeData) throws MslException {
// Primary and peer token combinations will be verified when the
// message header is constructed. So delay those checks in favor of
// avoiding duplicate code.
if (!ctx.isPeerToPeer() && (peerMasterToken != null || peerUserIdToken != null))
throw new MslInternalException("Cannot set peer master token or peer user ID token when not in peer-to-peer mode.");
// Set the primary fields.
this.messageId = messageId;
this.capabilities = capabilities;
this.masterToken = masterToken;
this.userIdToken = userIdToken;
this.keyExchangeData = keyExchangeData;
// If key exchange data is provided and we are not in peer-to-peer mode
// then its master token should be used for querying service tokens.
final MasterToken serviceMasterToken;
if (keyExchangeData != null && !ctx.isPeerToPeer()) {
serviceMasterToken = keyExchangeData.keyResponseData.getMasterToken();
} else {
serviceMasterToken = masterToken;
}
// Set the initial service tokens based on the MSL store and provided
// service tokens.
final Set<ServiceToken> tokens = ctx.getMslStore().getServiceTokens(serviceMasterToken, userIdToken);
this.serviceTokens.addAll(tokens);
if (serviceTokens != null) {
for (final ServiceToken token : serviceTokens) {
// Make sure the service token is properly bound.
if (token.isMasterTokenBound() && !token.isBoundTo(serviceMasterToken))
throw new MslMessageException(MslError.SERVICETOKEN_MASTERTOKEN_MISMATCH, "st " + token + "; mt " + serviceMasterToken).setMasterToken(serviceMasterToken);
if (token.isUserIdTokenBound() && !token.isBoundTo(userIdToken))
throw new MslMessageException(MslError.SERVICETOKEN_USERIDTOKEN_MISMATCH, "st " + token + "; uit " + userIdToken).setMasterToken(serviceMasterToken).setUserIdToken(userIdToken);
// Add the service token.
this.serviceTokens.add(token);
}
}
// Set the peer-to-peer data.
if (ctx.isPeerToPeer()) {
this.peerMasterToken = peerMasterToken;
this.peerUserIdToken = peerUserIdToken;
// If key exchange data is provided then its master token should
// be used to query peer service tokens.
final MasterToken peerServiceMasterToken;
if (keyExchangeData != null)
peerServiceMasterToken = keyExchangeData.keyResponseData.getMasterToken();
else
peerServiceMasterToken = this.peerMasterToken;
// Set the initial peer service tokens based on the MSL store and
// provided peer service tokens.
final Set<ServiceToken> peerTokens = ctx.getMslStore().getServiceTokens(peerServiceMasterToken, peerUserIdToken);
this.peerServiceTokens.addAll(peerTokens);
if (peerServiceTokens != null) {
for (final ServiceToken peerToken : peerServiceTokens) {
// Make sure the service token is properly bound.
if (peerToken.isMasterTokenBound() && !peerToken.isBoundTo(peerMasterToken))
throw new MslMessageException(MslError.SERVICETOKEN_MASTERTOKEN_MISMATCH, "st " + peerToken + "; mt " + peerMasterToken).setMasterToken(peerMasterToken);
if (peerToken.isUserIdTokenBound() && !peerToken.isBoundTo(peerUserIdToken))
throw new MslMessageException(MslError.SERVICETOKEN_USERIDTOKEN_MISMATCH, "st " + peerToken + "; uit " + peerUserIdToken).setMasterToken(peerMasterToken).setUserIdToken(peerUserIdToken);
// Add the peer service token.
this.peerServiceTokens.add(peerToken);
}
}
}
}
/**
* @return the message ID the builder will use.
*/
public long getMessageId() {
return messageId;
}
/**
* @return the primary master token or null if the message will use entity
* authentication data.
*/
public MasterToken getMasterToken() {
return masterToken;
}
/**
* @return the primary user ID token or null if the message will use user
* authentication data.
*/
public UserIdToken getUserIdToken() {
return userIdToken;
}
/**
* @return the key exchange data or null if there is none.
*/
public KeyExchangeData getKeyExchangeData() {
return keyExchangeData;
}
/**
* @return true if the message builder will create a message capable of
* encrypting the header data.
*/
public boolean willEncryptHeader() {
final EntityAuthenticationScheme scheme = ctx.getEntityAuthenticationData(null).getScheme();
return masterToken != null || scheme.encrypts();
}
/**
* @return true if the message builder will create a message capable of
* encrypting the payload data.
*/
public boolean willEncryptPayloads() {
final EntityAuthenticationScheme scheme = ctx.getEntityAuthenticationData(null).getScheme();
return masterToken != null ||
(!ctx.isPeerToPeer() && keyExchangeData != null) ||
scheme.encrypts();
}
/**
* @return true if the message builder will create a message capable of
* integrity protecting the header data.
*/
public boolean willIntegrityProtectHeader() {
final EntityAuthenticationScheme scheme = ctx.getEntityAuthenticationData(null).getScheme();
return masterToken != null || scheme.protectsIntegrity();
}
/**
* @return true if the message builder will create a message capable of
* integrity protecting the payload data.
*/
public boolean willIntegrityProtectPayloads() {
final EntityAuthenticationScheme scheme = ctx.getEntityAuthenticationData(null).getScheme();
return masterToken != null ||
(!ctx.isPeerToPeer() && keyExchangeData != null) ||
scheme.protectsIntegrity();
}
/**
* Construct the message header from the current message builder state.
*
* @return the message header.
* @throws MslCryptoException if there is an error encrypting or signing
* the message.
* @throws MslMasterTokenException if the header master token is not
* trusted and needs to be to accept this message header.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
* @throws MslMessageException if the message is non-replayable but does
* not include a master token.
* @throws MslException should not happen.
*/
public MessageHeader getHeader() throws MslCryptoException, MslMasterTokenException, MslEntityAuthException, MslMessageException, MslException {
final KeyResponseData response = (keyExchangeData != null) ? keyExchangeData.keyResponseData : null;
final Long nonReplayableId;
if (nonReplayable) {
if (masterToken == null)
throw new MslMessageException(MslError.NONREPLAYABLE_MESSAGE_REQUIRES_MASTERTOKEN);
nonReplayableId = ctx.getMslStore().getNonReplayableId(masterToken);
} else {
nonReplayableId = null;
}
final HeaderData headerData = new HeaderData(messageId, nonReplayableId, renewable, handshake, capabilities, keyRequestData, response, userAuthData, userIdToken, serviceTokens);
final HeaderPeerData peerData = new HeaderPeerData(peerMasterToken, peerUserIdToken, peerServiceTokens);
return createMessageHeader(ctx, ctx.getEntityAuthenticationData(null), masterToken, headerData, peerData);
}
/**
* Construct a new message header
*
* @param ctx MSL context.
* @param entityAuthData entity authentication data. Null if a master token is provided.
* @param masterToken master token to renew. Null if the identity is provided.
* @param headerData message header data container.
* @param peerData message header peer data container.
* @return the message header.
*/
protected MessageHeader createMessageHeader(final MslContext ctx, final EntityAuthenticationData entityAuthData, final MasterToken masterToken, final HeaderData headerData, final HeaderPeerData peerData) throws MslException, MslCryptoException {
return new MessageHeader(ctx, entityAuthData, masterToken, headerData, peerData);
}
/**
* <p>Set the message ID.</p>
*
* <p>This method will override the message ID that was computed when the
* message builder was created, and should not need to be called in most
* cases.</p>
*
* @param messageId the message ID.
* @return this.
* @throws MslInternalException if the message ID is out of range.
*/
public MessageBuilder setMessageId(final long messageId) {
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is out of range.");
this.messageId = messageId;
return this;
}
/**
* @return true if the message will be marked non-replayable.
*/
public boolean isNonReplayable() {
return nonReplayable;
}
/**
* Make the message non-replayable. If true this will also set the
* handshake flag to false.
*
* @param nonReplayable true if the message should be non-replayable.
* @return this.
* @see #setHandshake(boolean)
*/
public MessageBuilder setNonReplayable(final boolean nonReplayable) {
this.nonReplayable = nonReplayable;
if (this.nonReplayable)
this.handshake = false;
return this;
}
/**
* @return true if the message will be marked renewable.
*/
public boolean isRenewable() {
return renewable;
}
/**
* Set the message renewable flag. If false this will also set the
* handshake flag to false.
*
* @param renewable true if the message is renewable.
* @return this.
* @see #setHandshake(boolean)
*/
public MessageBuilder setRenewable(final boolean renewable) {
this.renewable = renewable;
if (!this.renewable)
this.handshake = false;
return this;
}
/**
* @return true if the message will be marked as a handshake message.
*/
public boolean isHandshake() {
return handshake;
}
/**
* Set the message handshake flag. If true this will also set the non-
* replayable flag to false and the renewable flag to true.
*
* @param handshake true if the message is a handshake message.
* @return this.
* @see #setNonReplayable(boolean)
* @see #setRenewable(boolean)
*/
public MessageBuilder setHandshake(final boolean handshake) {
this.handshake = handshake;
if (this.handshake) {
this.nonReplayable = false;
this.renewable = true;
}
return this;
}
/**
* <p>Set or change the master token and user ID token. This will overwrite
* any existing tokens. If the user ID token is not null then any existing
* user authentication data will be removed.</p>
*
* <p>Changing these tokens may result in invalidation of existing service
* tokens. Those service tokens will be removed from the message being
* built.</p>
*
* <p>This is a special method for the {@link MslControl} class that assumes
* the builder does not have key response data in trusted network mode.</p>
*
* @param masterToken the master token.
* @param userIdToken the user ID token. May be null.
*/
public void setAuthTokens(final MasterToken masterToken, final UserIdToken userIdToken) {
// Make sure the assumptions hold. Otherwise a bad message could be
// built.
if (userIdToken != null && !userIdToken.isBoundTo(masterToken))
throw new MslInternalException("User ID token must be bound to master token.");
// In trusted network mode key exchange data should only exist if this
// is a server response. In which case this method should not be
// getting called.
if (keyExchangeData != null && !ctx.isPeerToPeer())
throw new MslInternalException("Attempt to set message builder master token when key exchange data exists as a trusted network server.");
// Load the stored service tokens.
final Set<ServiceToken> storedTokens;
try {
storedTokens = ctx.getMslStore().getServiceTokens(masterToken, userIdToken);
} catch (final MslException e) {
// This should never happen because we already checked that the
// user ID token is bound to the master token.
throw new MslInternalException("Invalid master token and user ID token combination despite checking above.", e);
}
// Remove any service tokens that will no longer be bound.
final Iterator<ServiceToken> tokens = serviceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if ((token.isUserIdTokenBound() && !token.isBoundTo(userIdToken)) ||
(token.isMasterTokenBound() && !token.isBoundTo(masterToken)))
{
tokens.remove();
}
}
// Add any service tokens based on the MSL store replacing ones already
// set as they may be newer. The application will have a chance to
// manage the service tokens before the message is constructed and
// sent.
for (final ServiceToken token : storedTokens) {
excludeServiceToken(token.getName(), token.isMasterTokenBound(), token.isUserIdTokenBound());
serviceTokens.add(token);
}
// Set the new authentication tokens.
this.masterToken = masterToken;
this.userIdToken = userIdToken;
if (this.userIdToken != null)
this.userAuthData = null;
}
/**
* <p>Set the user authentication data of the message.</p>
*
* <p>This will overwrite any existing user authentication data.</p>
*
* @param userAuthData user authentication data to set. May be null.
* @return this.
*/
public MessageBuilder setUserAuthenticationData(final UserAuthenticationData userAuthData) {
this.userAuthData = userAuthData;
return this;
}
/**
* <p>Set the remote user of the message. This will create a user ID token
* in trusted network mode or peer user ID token in peer-to-peer mode.</p>
*
* <p>Adding a new user ID token will not impact the service tokens; it is
* assumed that no service tokens exist that are bound to the newly created
* user ID token.</p>
*
* <p>This is a special method for the {@link MslControl} class that assumes
* the builder does not already have a user ID token for the remote user
* and does have a master token that the new user ID token can be bound
* against.</p>
*
* @param user remote user.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslException if there is an error creating the user ID token.
*/
public void setUser(final MslUser user) throws MslCryptoException, MslException {
// Make sure the assumptions hold. Otherwise a bad message could be
// built.
if (!ctx.isPeerToPeer() && userIdToken != null ||
ctx.isPeerToPeer() && peerUserIdToken != null)
{
throw new MslInternalException("User ID token or peer user ID token already exists for the remote user.");
}
// If key exchange data is provided then its master token should be
// used for the new user ID token and for querying service tokens.
final MasterToken uitMasterToken;
if (keyExchangeData != null) {
uitMasterToken = keyExchangeData.keyResponseData.getMasterToken();
} else {
uitMasterToken = (!ctx.isPeerToPeer()) ? masterToken : peerMasterToken;
}
// Make sure we have a master token to create the user for.
if (uitMasterToken == null)
throw new MslInternalException("User ID token or peer user ID token cannot be created because no corresponding master token exists.");
// Create the new user ID token.
final TokenFactory factory = ctx.getTokenFactory();
final UserIdToken userIdToken = factory.createUserIdToken(ctx, user, uitMasterToken);
// Set the new user ID token.
if (!ctx.isPeerToPeer()) {
this.userIdToken = userIdToken;
this.userAuthData = null;
} else {
this.peerUserIdToken = userIdToken;
}
}
/**
* Add key request data to the message.
*
* @param keyRequestData key request data to add.
* @return this.
*/
public MessageBuilder addKeyRequestData(final KeyRequestData keyRequestData) {
this.keyRequestData.add(keyRequestData);
return this;
}
/**
* Remove key request data from the message.
*
* @param keyRequestData key request data to remove.
* @return this.
*/
public MessageBuilder removeKeyRequestData(final KeyRequestData keyRequestData) {
this.keyRequestData.remove(keyRequestData);
return this;
}
/**
* <p>Add a service token to the message. This will overwrite any service
* token with the same name that is also bound to the master token or user
* ID token in the same way as the new service token.</p>
*
* <p>Adding a service token with empty data indicates the recipient should
* delete the service token.</p>
*
* @param serviceToken service token to add.
* @return this.
* @throws MslMessageException if the service token serial numbers do not
* match the primary master token or primary user ID token of the
* message being built.
*/
public MessageBuilder addServiceToken(final ServiceToken serviceToken) throws MslMessageException {
// If key exchange data is provided and we are not in peer-to-peer mode
// then its master token should be used for querying service tokens.
final MasterToken serviceMasterToken;
if (keyExchangeData != null && !ctx.isPeerToPeer()) {
serviceMasterToken = keyExchangeData.keyResponseData.getMasterToken();
} else {
serviceMasterToken = masterToken;
}
// Make sure the service token is properly bound.
if (serviceToken.isMasterTokenBound() && !serviceToken.isBoundTo(serviceMasterToken))
throw new MslMessageException(MslError.SERVICETOKEN_MASTERTOKEN_MISMATCH, "st " + serviceToken + "; mt " + serviceMasterToken).setMasterToken(serviceMasterToken);
if (serviceToken.isUserIdTokenBound() && !serviceToken.isBoundTo(userIdToken))
throw new MslMessageException(MslError.SERVICETOKEN_USERIDTOKEN_MISMATCH, "st " + serviceToken + "; uit " + userIdToken).setMasterToken(serviceMasterToken).setUserIdToken(userIdToken);
// Remove any existing service token with the same name and bound state.
excludeServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
// Add the service token.
serviceTokens.add(serviceToken);
return this;
}
/**
* <p>Add a service token to the message if a service token with the same
* name that is also bound to the master token or user ID token in the same
* way as the new service token does not already exist.</p>
*
* <p>Adding a service token with empty data indicates the recipient should
* delete the service token.</p>
*
* @param serviceToken service token to add.
* @return this.
* @throws MslMessageException if the service token serial numbers do not
* match the master token or user ID token of the message being
* built.
*/
public MessageBuilder addServiceTokenIfAbsent(final ServiceToken serviceToken) throws MslMessageException {
final Iterator<ServiceToken> tokens = serviceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if (token.getName().equals(serviceToken.getName()) &&
token.isMasterTokenBound() == serviceToken.isMasterTokenBound() &&
token.isUserIdTokenBound() == serviceToken.isUserIdTokenBound())
{
return this;
}
}
addServiceToken(serviceToken);
return this;
}
/**
* <p>Exclude a service token from the message. This matches the token name
* and whether or not it is bound to the master token or to a user ID
* token. It does not require the token to be bound to the exact same
* master token or user ID token that will be used in the message.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* <p>This function is equivalent to calling
* {@link #excludeServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return this.
* @see #excludeServiceToken(String, boolean, boolean)
*/
public MessageBuilder excludeServiceToken(final ServiceToken serviceToken) {
return excludeServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Exclude a service token from the message matching all the specified
* parameters. A false value for the master token bound or user ID token
* bound parameters restricts exclusion to tokens that are not bound to a
* master token or not bound to a user ID token respectively.</p>
*
* <p>For example, if a name is provided and the master token bound
* parameter is true while the user ID token bound parameter is false, then
* the master token bound service token with the same name will be excluded
* from the message. If a name is provided but both other parameters are
* false, then only an unbound service token with the same name will be
* excluded.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return this.
*/
public MessageBuilder excludeServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
final Iterator<ServiceToken> tokens = serviceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if (token.getName().equals(name) &&
token.isMasterTokenBound() == masterTokenBound &&
token.isUserIdTokenBound() == userIdTokenBound)
{
tokens.remove();
}
}
return this;
}
/**
* <p>Mark a service token for deletion.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* <p>This function is equivalent to calling
* {@link #deleteServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return this.
*/
public MessageBuilder deleteServiceToken(final ServiceToken serviceToken) {
return deleteServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Mark a service token for deletion. A false value for the master token
* bound or user ID token bound parameters restricts deletion to tokens
* that are not bound to a master token or not bound to a user ID token
* respectively.</p>
*
* <p>For example, if a name is provided and the master token bound
* parameter is true while the user ID token bound parameter is false, then
* the master token bound service token with the same name will be marked
* for deletion. If a name is provided but both other parameters are false,
* then only an unbound service token with the same name will be marked for
* deletion.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* @param name service token name.
* @param masterTokenBound true to delete a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to delete a user ID token bound service
* token.
* @return this.
*/
public MessageBuilder deleteServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Rebuild the original token with empty service data.
final MasterToken masterToken = masterTokenBound ? this.masterToken : null;
final UserIdToken userIdToken = userIdTokenBound ? this.userIdToken : null;
try {
final ServiceToken token = new ServiceToken(ctx, name, EMPTY_DATA, masterToken, userIdToken, false, null, new NullCryptoContext());
return addServiceToken(token);
} catch (final MslException e) {
throw new MslInternalException("Failed to create and add empty service token to message.", e);
}
}
/**
* @return the unmodifiable set of service tokens that will be included in
* the built message.
*/
public Set<ServiceToken> getServiceTokens() {
return Collections.unmodifiableSet(serviceTokens);
}
/**
* @return the peer master token or null if there is none.
*/
public MasterToken getPeerMasterToken() {
return peerMasterToken;
}
/**
* @return the peer user ID token or null if there is none.
*/
public UserIdToken getPeerUserIdToken() {
return peerUserIdToken;
}
/**
* <p>Set the peer master token and peer user ID token of the message. This
* will overwrite any existing peer master token or peer user ID token.</p>
*
* <p>Changing these tokens may result in invalidation of existing peer
* service tokens. Those peer service tokens will be removed from the
* message being built.</p>
*
* @param masterToken peer master token to set. May be null.
* @param userIdToken peer user ID token to set. May be null.
* @throws MslMessageException if the peer user ID token is not bound to
* the peer master token.
*/
public void setPeerAuthTokens(final MasterToken masterToken, final UserIdToken userIdToken) throws MslMessageException {
if (!ctx.isPeerToPeer())
throw new MslInternalException("Cannot set peer master token or peer user ID token when not in peer-to-peer mode.");
if (userIdToken != null && masterToken == null)
throw new MslInternalException("Peer master token cannot be null when setting peer user ID token.");
if (userIdToken != null && !userIdToken.isBoundTo(masterToken))
throw new MslMessageException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit " + userIdToken + "; mt " + masterToken).setMasterToken(masterToken).setUserIdToken(userIdToken);
// Load the stored peer service tokens.
final Set<ServiceToken> storedTokens;
try {
storedTokens = ctx.getMslStore().getServiceTokens(masterToken, userIdToken);
} catch (final MslException e) {
// The checks above should have prevented any invalid master token,
// user ID token combinations.
throw new MslInternalException("Invalid peer master token and user ID token combination despite proper check.", e);
}
// Remove any peer service tokens that will no longer be bound.
final Iterator<ServiceToken> tokens = peerServiceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if ((token.isUserIdTokenBound() && !token.isBoundTo(userIdToken)) ||
(token.isMasterTokenBound() && !token.isBoundTo(masterToken)))
{
tokens.remove();
}
}
// Add any peer service tokens based on the MSL store if they are not
// already set (as a set one may be newer than the stored one).
for (final ServiceToken token : storedTokens) {
excludePeerServiceToken(token.getName(), token.isMasterTokenBound(), token.isUserIdTokenBound());
peerServiceTokens.add(token);
}
// Set the new peer authentication tokens.
peerUserIdToken = userIdToken;
peerMasterToken = masterToken;
}
/**
* <p>Add a peer service token to the message. This will overwrite any peer
* service token with the same name that is also bound to a peer master
* token or peer user ID token in the same way as the new service token.</p>
*
* <p>Adding a service token with empty data indicates the recipient should
* delete the service token.</p>
*
* @param serviceToken service token to add.
* @return this.
* @throws MslMessageException if the service token serial numbers do not
* match the peer master token or peer user ID token of the message
* being built.
*/
public MessageBuilder addPeerServiceToken(final ServiceToken serviceToken) throws MslMessageException {
// If we are not in peer-to-peer mode then peer service tokens cannot
// be set.
if (!ctx.isPeerToPeer())
throw new MslInternalException("Cannot set peer service tokens when not in peer-to-peer mode.");
// Make sure the service token is properly bound.
if (serviceToken.isMasterTokenBound() && !serviceToken.isBoundTo(peerMasterToken))
throw new MslMessageException(MslError.SERVICETOKEN_MASTERTOKEN_MISMATCH, "st " + serviceToken + "; mt " + peerMasterToken).setMasterToken(peerMasterToken);
if (serviceToken.isUserIdTokenBound() && !serviceToken.isBoundTo(peerUserIdToken))
throw new MslMessageException(MslError.SERVICETOKEN_USERIDTOKEN_MISMATCH, "st " + serviceToken + "; uit " + peerUserIdToken).setMasterToken(peerMasterToken).setUserIdToken(peerUserIdToken);
// Remove any existing service token with the same name and bound state.
excludePeerServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
// Add the peer service token.
peerServiceTokens.add(serviceToken);
return this;
}
/**
* <p>Add a peer service token to the message if a peer service token with
* the same name that is also bound to the peer master token or peer user
* ID token in the same way as the new service token does not already
* exist.</p>
*
* <p>Adding a service token with empty data indicates the recipient should
* delete the service token.</p>
*
* @param serviceToken service token to add.
* @return this.
* @throws MslMessageException if the service token serial numbers do not
* match the peer master token or peer user ID token of the message
* being built.
*/
public MessageBuilder addPeerServiceTokenIfAbsent(final ServiceToken serviceToken) throws MslMessageException {
final Iterator<ServiceToken> tokens = peerServiceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if (token.getName().equals(serviceToken.getName()) &&
token.isMasterTokenBound() == serviceToken.isMasterTokenBound() &&
token.isUserIdTokenBound() == serviceToken.isUserIdTokenBound())
{
return this;
}
}
addPeerServiceToken(serviceToken);
return this;
}
/**
* <p>Exclude a peer service token from the message. This matches the token
* name and whether or not it is bound to the master token or to a user ID
* token. It does not require the token to be bound to the exact same
* master token or user ID token that will be used in the message.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* <p>This function is equivalent to calling
* {@link #excludePeerServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return this.
*/
public MessageBuilder excludePeerServiceToken(final ServiceToken serviceToken) {
return excludePeerServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Exclude a peer service token from the message matching all the
* specified parameters. A false value for the master token bound or user
* ID token bound parameters restricts exclusion to tokens that are not
* bound to a master token or not bound to a user ID token
* respectively.</p>
*
* <p>For example, if a name is provided and the master token bound
* parameter is true while the user ID token bound parameter is false, then
* the master token bound service token with the same name will be excluded
* from the message. If a name is provided but both other parameters are
* false, then only an unbound service token with the same name will be
* excluded.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return this.
*/
public MessageBuilder excludePeerServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
final Iterator<ServiceToken> tokens = peerServiceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if (token.getName().equals(name) &&
token.isMasterTokenBound() == masterTokenBound &&
token.isUserIdTokenBound() == userIdTokenBound)
{
tokens.remove();
}
}
return this;
}
/**
* <p>Mark a peer service token for deletion.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* <p>This function is equivalent to calling
* {@link #deletePeerServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return this.
*/
public MessageBuilder deletePeerServiceToken(final ServiceToken serviceToken) {
return deletePeerServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Mark a peer service token for deletion. A false value for the master
* token bound or user ID token bound parameters restricts deletion to
* tokens that are not bound to a master token or not bound to a user ID
* token respectively.</p>
*
* <p>For example, if a name is provided and the master token bound
* parameter is true while the user ID token bound parameter is false, then
* the master token bound service token with the same name will be marked
* for deletion. If a name is provided but both other parameters are false,
* then only an unbound service token with the same name will be marked for
* deletion.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* @param name service token name.
* @param masterTokenBound true to delete a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to delete a user ID token bound service
* token.
* @return this.
*/
public MessageBuilder deletePeerServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Rebuild the original token with empty service data.
final MasterToken peerMasterToken = masterTokenBound ? this.peerMasterToken : null;
final UserIdToken peerUserIdToken = userIdTokenBound ? this.peerUserIdToken : null;
try {
final ServiceToken token = new ServiceToken(ctx, name, EMPTY_DATA, peerMasterToken, peerUserIdToken, false, null, new NullCryptoContext());
return addPeerServiceToken(token);
} catch (final MslException e) {
throw new MslInternalException("Failed to create and add empty peer service token to message.", e);
}
}
/**
* @return the unmodifiable set of peer service tokens that will be
* included in the built message.
*/
public Set<ServiceToken> getPeerServiceTokens() {
return Collections.unmodifiableSet(peerServiceTokens);
}
/** MSL context. */
private final MslContext ctx;
/** Message header master token. */
protected MasterToken masterToken;
/** Header data message ID. */
protected long messageId;
/** Key exchange data. */
protected KeyExchangeData keyExchangeData;
/** Message non-replayable. */
protected boolean nonReplayable = false;
/** Header data renewable. */
protected boolean renewable = false;
/** Handshake message. */
protected boolean handshake = false;
/** Message capabilities. */
protected MessageCapabilities capabilities;
/** Header data key request data. */
protected final Set<KeyRequestData> keyRequestData = new HashSet<KeyRequestData>();
/** Header data user authentication data. */
protected UserAuthenticationData userAuthData = null;
/** Header data user ID token. */
protected UserIdToken userIdToken = null;
/** Header data service tokens. */
protected final Set<ServiceToken> serviceTokens = new HashSet<ServiceToken>();
/** Header peer data master token. */
protected MasterToken peerMasterToken = null;
/** Header peer data user ID token. */
protected UserIdToken peerUserIdToken = null;
/** Header peer data service tokens. */
protected final Set<ServiceToken> peerServiceTokens = new HashSet<ServiceToken>();
}
| 1,706 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageServiceTokenBuilder.java
|
/**
* Copyright (c) 2012-2020 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.msg;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.KeyExchangeFactory.KeyExchangeData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.util.MslContext;
/**
* <p>A message service token builder provides methods for intelligently
* manipulating the primary and peer service tokens that will be included in a
* message.</p>
*
* <p>There are two categories of service tokens: primary and peer.
* <ul>
* <li>Primary service tokens are associated with the primary master token and
* peer user ID token, and are the only category of service token to appear in
* trusted network mode. Primary service tokens are also used in peer-to-peer
* mode.</li>
* <li>Peer service tokens are associated with the peer master token and peer
* user ID token and only used in peer-to-peer mode.</li>
* </ul></p>
*
* <p>There are three levels of service token binding.
* <ul>
* <li>Unbound service tokens may be freely moved between entities and
* users.</li>
* <li>Master token bound service tokens must be accompanied by a master token
* that they are bound to and will be rejected if sent with a different master
* token or without a master token. This binds a service token to a specific
* entity.</li>
* <li>User ID token bound service tokens must be accompanied by a user ID
* token that they are bound to and will be rejected if sent with a different
* user or used without a user ID token. This binds a service token to a
* specific user and by extension a specific entity.</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MessageServiceTokenBuilder {
/**
* <p>Select the appropriate crypto context for the named service token.</p>
*
* <p>If the service token name exists as a key in the map of crypto
* contexts, the mapped crypto context will be returned. Otherwise the
* default crypto context mapped from the empty string key will be returned.
* If no explicit or default crypto context exists null will be
* returned.</p>
*
* @param name service token name.
* @param cryptoContexts the map of service token names onto crypto
* contexts used to decrypt and verify service tokens.
* @return the correct crypto context for the service token or null.
*/
private static ICryptoContext selectCryptoContext(final String name, final Map<String,ICryptoContext> cryptoContexts) {
if (cryptoContexts.containsKey(name))
return cryptoContexts.get(name);
return cryptoContexts.get("");
}
/**
* Create a new message service token builder with the provided MSL and
* message contexts and message builder.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param builder message builder for message being built.
*/
public MessageServiceTokenBuilder(final MslContext ctx, final MessageContext msgCtx, final MessageBuilder builder) {
this.ctx = ctx;
this.cryptoContexts = msgCtx.getCryptoContexts();
this.builder = builder;
}
/**
* Returns the master token that primary service tokens should be bound
* against.
*
* @return the primary service token master token or {@code null} if there
* is none.
*/
private MasterToken getPrimaryMasterToken() {
// If key exchange data is provided and we are not in peer-to-peer mode
// then its master token will be used for creating service tokens.
final KeyExchangeData keyExchangeData = builder.getKeyExchangeData();
if (keyExchangeData != null && !ctx.isPeerToPeer()) {
return keyExchangeData.keyResponseData.getMasterToken();
} else {
return builder.getMasterToken();
}
}
/**
* Returns true if the message has a primary master token available for
* adding master-bound primary service tokens.
*
* @return true if the message has a primary master token.
*/
public boolean isPrimaryMasterTokenAvailable() {
return getPrimaryMasterToken() != null;
}
/**
* @return true if the message has a primary user ID token.
*/
public boolean isPrimaryUserIdTokenAvailable() {
return builder.getUserIdToken() != null;
}
/**
* @return true if the message has a peer master token.
*/
public boolean isPeerMasterTokenAvailable() {
return builder.getPeerMasterToken() != null;
}
/**
* @return true if the message has a peer user ID token.
*/
public boolean isPeerUserIdTokenAvailable() {
return builder.getPeerUserIdToken() != null;
}
/**
* @return the unmodifiable set of primary service tokens that will be
* included in the built message.
*/
public Set<ServiceToken> getPrimaryServiceTokens() {
return builder.getServiceTokens();
}
/**
* @return the unmodifiable set of peer service tokens that will be
* included in the built message.
*/
public Set<ServiceToken> getPeerServiceTokens() {
return builder.getPeerServiceTokens();
}
/**
* Adds a primary service token to the message, replacing any existing
* primary service token with the same name.
*
* @param serviceToken primary service token.
* @return true if the service token was added, false if the service token
* is bound to a master token or user ID token and the message does
* not have the same token.
* @throws MslMessageException if the service token serial numbers do not
* match the primary master token or primary user ID token of the
* message being built.
*/
public boolean addPrimaryServiceToken(final ServiceToken serviceToken) throws MslMessageException {
try {
builder.addServiceToken(serviceToken);
return true;
} catch (final MslMessageException e) {
return false;
}
}
/**
* Adds a peer service token to the message, replacing any existing peer
* service token with the same name.
*
* @param serviceToken peer service token.
* @return true if the service token was added, false if the service token
* is bound to a master token or user ID token and the message does
* not have the same token.
* @throws MslMessageException if the service token serial numbers do not
* match the peer master token or peer user ID token of the message
* being built.
*/
public boolean addPeerServiceToken(final ServiceToken serviceToken) throws MslMessageException {
try {
builder.addPeerServiceToken(serviceToken);
return true;
} catch (final MslMessageException e) {
return false;
}
}
/**
* Adds a new unbound primary service token to the message, replacing any
* existing primary service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addUnboundPrimaryServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, null, null, encrypt, compressionAlgo, cryptoContext);
try {
builder.addServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite being unbound.", e);
}
return true;
}
/**
* Adds a new unbound peer service token to the message, replacing any
* existing peer service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addUnboundPeerServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, null, null, encrypt, compressionAlgo, cryptoContext);
try {
builder.addPeerServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite being unbound.", e);
}
return true;
}
/**
* Adds a new master token bound primary service token to the message,
* replacing any existing primary service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token or the message does not
* have a primary master token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addMasterBoundPrimaryServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no master token.
final MasterToken masterToken = getPrimaryMasterToken();
if (masterToken == null)
return false;
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, masterToken, null, encrypt, compressionAlgo, cryptoContext);
try {
builder.addServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite setting correct master token.", e);
}
return true;
}
/**
* Adds a new master token bound peer service token to the message,
* replacing any existing peer service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token or the message does not
* have a peer master token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addMasterBoundPeerServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no master token.
final MasterToken masterToken = builder.getPeerMasterToken();
if (masterToken == null)
return false;
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, masterToken, null, encrypt, compressionAlgo, cryptoContext);
try {
builder.addPeerServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite setting correct master token.", e);
}
return true;
}
/**
* Adds a new user ID token bound primary service token to the message,
* replacing any existing primary service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token or the message does not
* have a primary user ID token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addUserBoundPrimaryServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no master token.
final MasterToken masterToken = getPrimaryMasterToken();
if (masterToken == null)
return false;
// Fail if there is no user ID token.
final UserIdToken userIdToken = builder.getUserIdToken();
if (userIdToken == null)
return false;
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, masterToken, userIdToken, encrypt, compressionAlgo, cryptoContext);
try {
builder.addServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite setting correct master token and user ID token.", e);
}
return true;
}
/**
* Adds a new user ID token bound peer service token to the message,
* replacing any peer existing service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token or the message does not
* have a peer user ID token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addUserBoundPeerServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no master token.
final MasterToken masterToken = builder.getPeerMasterToken();
if (masterToken == null)
return false;
// Fail if there is no user ID token.
final UserIdToken userIdToken = builder.getPeerUserIdToken();
if (userIdToken == null)
return false;
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, masterToken, userIdToken, encrypt, compressionAlgo, cryptoContext);
try {
builder.addPeerServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite setting correct master token and user ID token.", e);
}
return true;
}
/**
* <p>Exclude a primary service token from the message. This matches the
* token name and whether or not it is bound to a master token or to a user
* ID token. It does not require the token to be bound to the exact same
* master token or user ID token that will be used in the message.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* <p>This function is equivalent to calling
* {@link #excludePrimaryServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return true if the service token was found and therefore removed.
*/
public boolean excludePrimaryServiceToken(final ServiceToken serviceToken) {
return excludePrimaryServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Exclude a primary service token from the message matching all
* specified parameters. A false value for the master token bound or user
* ID token bound parameters restricts exclusion to tokens that are not
* bound to a master token or not bound to a user ID token
* respectively.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return true if the service token was found and therefore removed.
*/
public boolean excludePrimaryServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Exclude the service token if found.
for (final ServiceToken serviceToken : builder.getServiceTokens()) {
if (serviceToken.getName().equals(name) &&
serviceToken.isMasterTokenBound() == masterTokenBound &&
serviceToken.isUserIdTokenBound() == userIdTokenBound)
{
builder.excludeServiceToken(name, masterTokenBound, userIdTokenBound);
return true;
}
}
// Not found.
return false;
}
/**
* <p>Exclude a peer service token from the message. This matches the
* token name and whether or not it is bound to a master token or to a user
* ID token. It does not require the token to be bound to the exact same
* master token or user ID token that will be used in the message.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* <p>This function is equivalent to calling
* {@link #excludePeerServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return true if the service token was found and therefore removed.
*/
public boolean excludePeerServiceToken(final ServiceToken serviceToken) {
return excludePeerServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Exclude a peer service token from the message matching all specified
* parameters. A false value for the master token bound or user ID token
* bound parameters restricts exclusion to tokens that are not bound to a
* master token or not bound to a user ID token respectively.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return true if the peer service token was found and therefore removed.
*/
public boolean excludePeerServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Exclude the service token if found.
for (final ServiceToken serviceToken : builder.getPeerServiceTokens()) {
if (serviceToken.getName().equals(name) &&
serviceToken.isMasterTokenBound() == masterTokenBound &&
serviceToken.isUserIdTokenBound() == userIdTokenBound)
{
builder.excludePeerServiceToken(name, masterTokenBound, userIdTokenBound);
return true;
}
}
// Not found.
return false;
}
/**
* <p>Mark a primary service token for deletion, if it exists. This matches
* the token name and whether or not it is bound to a master token or to a
* user ID token. It does not require the token to be bound to the exact
* same master token or user ID token that will be used in the message.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* <p>This function is equivalent to calling
* {@link #deletePrimaryServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return true if the service token exists and was marked for deletion.
*/
public boolean deletePrimaryServiceToken(final ServiceToken serviceToken) {
return deletePrimaryServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Mark a primary service token for deletion, if it exists, matching all
* specified parameters. A false value for the master token bound or user
* ID token bound parameters restricts deletion to tokens that are not
* bound to a master token or not bound to a user ID token
* respectively.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return true if the service token exists and was marked for deletion.
*/
public boolean deletePrimaryServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Mark the service token for deletion if found.
for (final ServiceToken serviceToken : builder.getServiceTokens()) {
if (serviceToken.getName().equals(name) &&
serviceToken.isMasterTokenBound() == masterTokenBound &&
serviceToken.isUserIdTokenBound() == userIdTokenBound)
{
builder.deleteServiceToken(name, masterTokenBound, userIdTokenBound);
return true;
}
}
// Not found.
return false;
}
/**
* <p>Mark a peer service token for deletion, if it exists. This matches
* the token name and whether or not it is bound to a master token or to a
* user ID token. It does not require the token to be bound to the exact
* same master token or user ID token that will be used in the message.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* <p>This function is equivalent to calling
* {@link #deletePeerServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return true if the service token exists and was marked for deletion.
*/
public boolean deletePeerServiceToken(final ServiceToken serviceToken) {
return deletePeerServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Mark a peer service token for deletion, if it exists, matching all
* specified parameters. A false value for the master token bound or user
* ID token bound parameters restricts deletion to tokens that are not
* bound to a master token or not bound to a user ID token
* respectively.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return true if the peer service token exists and was marked for
* deletion.
*/
public boolean deletePeerServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Mark the service token for deletion if found.
for (final ServiceToken serviceToken : builder.getPeerServiceTokens()) {
if (serviceToken.getName().equals(name) &&
serviceToken.isMasterTokenBound() == masterTokenBound &&
serviceToken.isUserIdTokenBound() == userIdTokenBound)
{
builder.deletePeerServiceToken(name, masterTokenBound, userIdTokenBound);
return true;
}
}
// Not found.
return false;
}
/** MSL context. */
private final MslContext ctx;
/** Service token crypto contexts. */
private final Map<String,ICryptoContext> cryptoContexts;
/** Message builder for message being built. */
private final MessageBuilder builder;
}
| 1,707 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/NonReplayableMessageContext.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.msg;
/**
* <p>A message context implementation that can be extended for use with
* messages that cannot be replayed. This also carries the security properties
* of encryption and integrity protection.</p>
*
* <p>Example uses of the non-replayable message context would be for the
* transmission of financial transactions or to grant access to restricted
* resources where a repeat transmission may result in incorrect data or
* abuse.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class NonReplayableMessageContext implements MessageContext {
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return true;
}
}
| 1,708 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/IdempotentResponseMessageBuilder.java
|
/**
* Copyright (c) 2012-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.msg;
import java.util.Set;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslException;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.util.MslContext;
/**
* <p>Idempotent message builder.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class IdempotentResponseMessageBuilder extends MessageBuilder {
/**
* Create a new message builder that will craft a new message in response
* to another message without issuing or renewing any master tokens or user
* ID tokens. The constructed message may be used as a request.
*
* @param ctx MSL context.
* @param requestHeader message header to respond to.
* @throws MslCryptoException if there is an error accessing the remote
* entity identity.
* @throws MslException if any of the request's user ID tokens is not bound
* to its master token.
*/
public IdempotentResponseMessageBuilder(final MslContext ctx, final MessageHeader requestHeader) throws MslCryptoException, MslException {
super(ctx);
final MasterToken masterToken = requestHeader.getMasterToken();
final EntityAuthenticationData entityAuthData = requestHeader.getEntityAuthenticationData();
final UserIdToken userIdToken = requestHeader.getUserIdToken();
final UserAuthenticationData userAuthData = requestHeader.getUserAuthenticationData();
// The response message ID must be equal to the request message ID + 1.
final long requestMessageId = requestHeader.getMessageId();
final long messageId = incrementMessageId(requestMessageId);
// Compute the intersection of the request and response message
// capabilities.
final MessageCapabilities capabilities = MessageCapabilities.intersection(requestHeader.getMessageCapabilities(), ctx.getMessageCapabilities());
// Create the message builder.
//
// Peer-to-peer responses swap the tokens.
try {
final KeyResponseData keyResponseData = requestHeader.getKeyResponseData();
final Set<ServiceToken> serviceTokens = requestHeader.getServiceTokens();
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
final Set<ServiceToken> peerServiceTokens = requestHeader.getPeerServiceTokens();
initializeMessageBuilder(ctx, messageId, capabilities, peerMasterToken, peerUserIdToken, peerServiceTokens, masterToken, userIdToken, serviceTokens, null);
} else {
final MasterToken localMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : masterToken;
initializeMessageBuilder(ctx, messageId, capabilities, localMasterToken, userIdToken, serviceTokens, null, null, null, null);
}
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setUserIdToken(userIdToken);
e.setUserAuthenticationData(userAuthData);
e.setMessageId(requestMessageId);
throw e;
}
}
}
| 1,709 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/FilterStreamFactory.java
|
/**
* Copyright (c) 2013-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.msg;
import java.io.InputStream;
import java.io.OutputStream;
/**
* A filter stream factory provides filter input stream and filter output
* stream instances.
*
* Implementations must be thread-safe.
*
* @author Wesley Miaw <[email protected]>
*/
public interface FilterStreamFactory {
/**
* Return a new input stream that has the provided input stream as its
* backing source. If no filtering is desired then the original input
* stream must be returned.
*
* @param in the input stream to wrap.
* @return a new filter input stream backed by the provided input stream or
* the original input stream..
*/
public InputStream getInputStream(final InputStream in);
/**
* Return a new output stream that has the provided output stream as its
* backing destination. If no filtering is desired then the original output
* stream must be returned.
*
* @param out the output stream to wrap.
* @return a new filter output stream backed by the provided output stream
* or the original output stream.
*/
public OutputStream getOutputStream(final OutputStream out);
}
| 1,710 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/ServerReceiveMessageContext.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.msg;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
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.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* <p>A trusted services network message context used to receive client
* messages suitable for use with
* {@link MslControl#receive(com.netflix.msl.util.MslContext, MessageContext, java.io.InputStream, java.io.OutputStream, int)}.
* Since this message context is only used for receiving messages, it cannot be
* used to send application data back to the client and does not require
* encryption or integrity protection.</p>
*
* <p>The application may wish to override
* {@link #updateServiceTokens(MessageServiceTokenBuilder, boolean)} to
* modify any service tokens sent in handshake responses.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class ServerReceiveMessageContext extends PublicMessageContext {
/**
* <p>Create a new receive message context.</p>
*
* @param cryptoContexts service token crypto contexts. May be
* {@code null}.
* @param dbgCtx optional message debug context. May be {@code null}.
*/
public ServerReceiveMessageContext(final Map<String,ICryptoContext> cryptoContexts, final MessageDebugContext dbgCtx) {
this.cryptoContexts = (cryptoContexts != null) ? new HashMap<String,ICryptoContext>(cryptoContexts) : new HashMap<String,ICryptoContext>();
this.dbgCtx = dbgCtx;
}
@Override
public Map<String, ICryptoContext> getCryptoContexts() {
return Collections.unmodifiableMap(cryptoContexts);
}
@Override
public String getRemoteEntityIdentity() {
return null;
}
@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 {
}
@Override
public MessageDebugContext getDebugContext() {
return dbgCtx;
}
/** Service token crypto contexts. */
protected final Map<String,ICryptoContext> cryptoContexts;
/** Message debug context. */
protected final MessageDebugContext dbgCtx;
}
| 1,711 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MslControl.java
|
/**
* Copyright (c) 2012-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.msg;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.FileLockInterruptionException;
import java.util.Collections;
import java.util.Date;
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 java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
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.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslErrorResponseException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.NullCryptoContext;
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.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.io.MslTokenizer;
import com.netflix.msl.io.Url;
import com.netflix.msl.io.Url.Connection;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeFactory.KeyExchangeData;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
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.MslUtils;
import com.netflix.msl.util.NullMslStore;
/**
* <p>Message Security Layer control provides the base operational MSL logic of
* sending and receiving messages with an optional thread pool. An application
* should only use one instance of {@code MslControl} for all MSL
* communication. This class is thread-safe.</p>
*
* <p>This class provides methods for sending and receiving messages for all
* types of entities in both trusted network and peer-to-peer network types.
* Refer to the documentation for each method to determine which methods should
* be used based on the entity's role and network type.</p>
*
* <h3>Error Handling</h3>
*
* <dl>
* <dt>{@link ResponseCode#FAIL}</dt>
* <dd>The caller is notified of the failure.</dd>
*
* <dt>{@link ResponseCode#TRANSIENT_FAILURE}</dt>
* <dd>The caller is notified of the failure. MSL will not automatically
* retry.</dd>
*
* <dt>{@link ResponseCode#ENTITY_REAUTH}</dt>
* <dd>MSL will attempt to resend the message using the entity authentication
* data. The previous master token and master token-bound service tokens
* will be discarded if successful.</dd>
*
* <dt>{@link ResponseCode#USER_REAUTH}</dt>
* <dd>MSL will attempt to resend the message using the user authentication
* data if made available by the message context. Otherwise request fails.
* The previous user ID token-bound service tokens will be discarded if
* successful.</dd>
*
* <dt>{@link ResponseCode#KEYX_REQUIRED}</dt>
* <dd>MSL will attempt to perform key exchange to establish session keys and
* then resend the message.</dd>
*
* <dt>{@link ResponseCode#ENTITYDATA_REAUTH}</dt>
* <dd>MSL will attempt to resend the message using new entity authentication
* data. The previous master token and master token-bound service tokens
* will be discarded if successful.</dd>
*
* <dt>{@link ResponseCode#USERDATA_REAUTH}</dt>
* <dd>MSL will attempt to resend the message using new user authentication
* data if made available by the message context. Otherwise request fails.
* The previous user ID token-bound service tokens will be discarded if
* successful.</dd>
*
* <dt>{@link ResponseCode#EXPIRED}</dt>
* <dd>MSL will attempt to resend the message with the renewable flag set or
* after receiving a new master token.</dd>
*
* <dt>{@link ResponseCode#REPLAYED}</dt>
* <dd>MSL will attempt to resend the message after renewing the master token
* or receiving a new master token.</dd>
*
* <dt>{@link ResponseCode#SSOTOKEN_REJECTED}</dt>
* <dd>Identical to {@link ResponseCode#USERDATA_REAUTH}.</dd>
* </dl>
*
* <h3>Anti-Replay</h3>
*
* <p>Requests marked as non-replayable will include a non-replayable ID.</p>
*
* <p>Responses must always reply with the message ID of the request
* incremented by 1. When the request message ID equals 2<sup>63</sup>-1 the
* response message ID must be 0. If the response message ID does not equal the
* expected value it is rejected and the caller is notified.</p>
*
* <h3>Renewal Synchronization</h3>
*
* <p>For a given MSL context there will be at most one renewable request with
* a master token and key request data in process. This prevents excessive
* master token renewal and potential renewal race conditions.</p>
*
* <p>Requests will be marked renewable if any of the following is true:
* <ul>
* <li>The master token renewal window has been entered.</li>
* <li>The user ID token renewal window has been entered.</li>
* <li>The application requests or requires establishment of session keys.</li>
* </ul>
* </p>
*
* <h3>MSL Handshake</h3>
*
* <p>Whenever requested or possible application data is encrypted and
* integrity-protected while in transit. If the MSL context entity
* authentication scheme does not support encryption or integrity protection
* when requested an initial handshake will be performed to establish session
* keys. This handshake occurs silently without the application's
* knowledge.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MslControl {
/**
* Application level errors that may translate into MSL level errors.
*/
public static enum ApplicationError {
/** The entity identity is no longer accepted by the application. */
ENTITY_REJECTED,
/** The user identity is no longer accepted by the application. */
USER_REJECTED,
}
/**
* A {@link MessageInputStream} and {@link MessageOutputStream} pair
* representing a single MSL communication channel established between
* the local and remote entities.
*/
public static class MslChannel {
/**
* Create a new MSL channel with the provided input and output streams.
*
* @param input message input stream to read from the remote entity.
* @param output message output stream to write to the remote entity.
*/
protected MslChannel(final MessageInputStream input, final MessageOutputStream output) {
this.input = input;
this.output = output;
}
/** Message input stream to read from the remote entity. */
public final MessageInputStream input;
/** Message output stream to write to the remote entity. */
public final MessageOutputStream output;
}
/**
* A map key based off a MSL context and master token pair.
*/
private static class MslContextMasterTokenKey {
/**
* Create a new MSL context and master token map key.
*
* @param ctx MSL context.
* @param masterToken master token.
*/
public MslContextMasterTokenKey(final MslContext ctx, final MasterToken masterToken) {
this.ctx = ctx;
this.masterToken = masterToken;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.ctx.hashCode() ^ this.masterToken.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 MslContextMasterTokenKey)) return false;
final MslContextMasterTokenKey that = (MslContextMasterTokenKey)obj;
return this.ctx.equals(that.ctx) && this.masterToken.equals(that.masterToken);
}
/** MSL context. */
private final MslContext ctx;
/** Master token. */
private final MasterToken masterToken;
}
/**
* This class executes all tasks synchronously on the calling thread.
*/
private static class SynchronousExecutor extends AbstractExecutorService {
/* (non-Javadoc)
* @see java.util.concurrent.Executor#execute(java.lang.Runnable)
*/
@Override
public void execute(final Runnable command) {
// All the AbstractExecutorService methods eventually end up here
// so checking for shutdown and executing on the caller should be
// okay for this implementation.
if (shutdown)
throw new RejectedExecutionException("Synchronous executor already shut down.");
command.run();
}
/* (non-Javadoc)
* @see java.util.concurrent.ExecutorService#awaitTermination(long, java.util.concurrent.TimeUnit)
*/
@Override
public boolean awaitTermination(final long timeout, final TimeUnit unit) {
return false;
}
/* (non-Javadoc)
* @see java.util.concurrent.ExecutorService#isShutdown()
*/
@Override
public boolean isShutdown() {
return shutdown;
}
/* (non-Javadoc)
* @see java.util.concurrent.ExecutorService#isTerminated()
*/
@Override
public boolean isTerminated() {
return shutdown;
}
/* (non-Javadoc)
* @see java.util.concurrent.ExecutorService#shutdown()
*/
@Override
public void shutdown() {
shutdown = true;
}
/* (non-Javadoc)
* @see java.util.concurrent.ExecutorService#shutdownNow()
*/
@Override
public List<Runnable> shutdownNow() {
shutdown = true;
return Collections.emptyList();
}
/** Shutdown? */
private boolean shutdown = false;
}
/**
* A dummy MSL context only used for our dummy
* {@link MslControl#NULL_MASTER_TOKEN}.
*/
private static class DummyMslContext extends MslContext {
/** A dummy MSL encoder factory. */
private static class DummyMslEncoderFactory extends MslEncoderFactory {
@Override
public MslEncoderFormat getPreferredFormat(final Set<MslEncoderFormat> formats) {
return MslEncoderFormat.JSON;
}
@Override
protected MslTokenizer generateTokenizer(final InputStream source, final MslEncoderFormat format) {
throw new MslInternalException("DummyMslEncoderFactory.generateTokenizer() not supported.");
}
@Override
public MslObject parseObject(final byte[] encoding) {
throw new MslInternalException("DummyMslEncoderFactory.parseObject() not supported.");
}
@Override
public byte[] encodeObject(final MslObject object, final MslEncoderFormat format) {
throw new MslInternalException("DummyMslEncoderFactory.encodeObject() not supported.");
}
}
/* (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 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 null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getEntityAuthenticationData(com.netflix.msl.util.MslContext.ReauthCode)
*/
@Override
public EntityAuthenticationData getEntityAuthenticationData(final MslContext.ReauthCode reauth) {
return new UnauthenticatedAuthenticationData("dummy");
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslCryptoContext()
*/
@Override
public ICryptoContext getMslCryptoContext() throws MslCryptoException {
return new NullCryptoContext();
}
/* (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 null;
}
/* (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 null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getTokenFactory()
*/
@Override
public TokenFactory getTokenFactory() {
throw new MslInternalException("Dummy token factory should never actually get used.");
}
/* (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) {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getKeyExchangeFactories()
*/
@Override
public SortedSet<KeyExchangeFactory> getKeyExchangeFactories() {
return new TreeSet<KeyExchangeFactory>();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslStore()
*/
@Override
public MslStore getMslStore() {
return new NullMslStore();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslEncoderFactory()
*/
@Override
public MslEncoderFactory getMslEncoderFactory() {
return new DummyMslEncoderFactory();
}
}
/**
* A dummy error message registry that always returns null for the user
* message.
*/
private static class DummyMessageRegistry implements ErrorMessageRegistry {
/* (non-Javadoc)
* @see com.netflix.msl.msg.ErrorMessageRegistry#getUserMessage(com.netflix.msl.MslError, java.util.List)
*/
@Override
public String getUserMessage(final MslError err, final List<String> languages) {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.ErrorMessageRegistry#getUserMessage(java.lang.Throwable, java.util.List)
*/
@Override
public String getUserMessage(final Throwable err, final List<String> languages) {
return null;
}
}
/**
* Base class for custom message contexts. All methods are passed through
* to the backing message context.
*/
private static class FilterMessageContext implements MessageContext {
/**
* Creates a message context that passes through calls to the backing
* message context.
*
* @param appCtx the application's message context.
*/
protected FilterMessageContext(final MessageContext appCtx) {
this.appCtx = appCtx;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getCryptoContexts()
*/
@Override
public Map<String, ICryptoContext> getCryptoContexts() {
return appCtx.getCryptoContexts();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getRemoteEntityIdentity()
*/
@Override
public String getRemoteEntityIdentity() {
return appCtx.getRemoteEntityIdentity();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return appCtx.isEncrypted();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
return appCtx.isIntegrityProtected();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return appCtx.isNonReplayable();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isRequestingTokens()
*/
@Override
public boolean isRequestingTokens() {
return appCtx.isRequestingTokens();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUserId()
*/
@Override
public String getUserId() {
return appCtx.getUserId();
}
/* (non-Javadoc)
* @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) {
return appCtx.getUserAuthData(reauthCode, renewable, required);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUser()
*/
@Override
public MslUser getUser() {
return appCtx.getUser();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getKeyRequestData()
*/
@Override
public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException {
return appCtx.getKeyRequestData();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#updateServiceTokens(com.netflix.msl.msg.MessageServiceTokenBuilder, boolean)
*/
@Override
public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) throws MslMessageException, MslEncodingException, MslCryptoException, MslException {
appCtx.updateServiceTokens(builder, handshake);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#write(com.netflix.msl.msg.MessageOutputStream)
*/
@Override
public void write(final MessageOutputStream output) throws IOException {
appCtx.write(output);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getDebugContext()
*/
@Override
public MessageDebugContext getDebugContext() {
return appCtx.getDebugContext();
}
/** The backing application message context. */
protected final MessageContext appCtx;
}
/**
* This message context is used to re-send a message.
*/
private static class ResendMessageContext extends FilterMessageContext {
/**
* Creates a message context used to re-send a message after an error
* or handshake. If the payloads are null the application's message
* context will be asked to write its data. Otherwise the provided
* payloads will be used for the message's application data.
*
* @param payloads original request payload chunks. May be null.
* @param appCtx the application's message context.
*/
public ResendMessageContext(final List<PayloadChunk> payloads, final MessageContext appCtx) {
super(appCtx);
this.payloads = payloads;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MslControl.FilterMessageContext#write(com.netflix.msl.msg.MessageOutputStream)
*/
@Override
public void write(final MessageOutputStream output) throws IOException {
// If there are no payloads ask the application message context to
// write its data.
if (payloads == null || payloads.isEmpty()) {
appCtx.write(output);
return;
}
// Rewrite the payloads one-by-one.
for (final PayloadChunk chunk : payloads) {
output.setCompressionAlgorithm(chunk.getCompressionAlgo());
output.write(chunk.getData());
if (chunk.isEndOfMessage())
output.close();
else
output.flush();
}
}
/** The application data to resend. */
private final List<PayloadChunk> payloads;
}
/**
* This message context is used to send messages that will not expect a
* response.
*/
private static class SendMessageContext extends FilterMessageContext {
/**
* Creates a message context used to send messages that do not expect a
* response by ensuring that the message context conforms to those
* expectations.
*
* @param appCtx the application's message context.
*/
public SendMessageContext(final MessageContext appCtx) {
super(appCtx);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MslControl.FilterMessageContext#isRequestingTokens()
*/
@Override
public boolean isRequestingTokens() {
return false;
}
}
/**
* This message context is used to send a handshake response.
*/
private static class KeyxResponseMessageContext extends FilterMessageContext {
/**
* Creates a message context used for automatically generated handshake
* responses.
*
* @param appCtx the application's message context.
*/
public KeyxResponseMessageContext(final MessageContext appCtx) {
super(appCtx);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
// Key exchange responses cannot require encryption otherwise key
// exchange could never succeed in some cases.
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MslControl.FilterMessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
// Key exchange responses cannot require integrity protection
// otherwise key exchange could never succeed in some cases.
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MslControl.FilterMessageContext#write(com.netflix.msl.msg.MessageOutputStream)
*/
@Override
public void write(final MessageOutputStream output) throws IOException {
// No application data.
}
}
/**
* <p>Returns true if the current thread has been interrupted as indicated
* by the {@code Thread#isInterrupted()} method or the type of caught
* throwable.</p>
*
* <p>The following {@code Throwable} types are considered interruptions that the application
* initiated or should otherwise be aware of:
* <ul>
* <li>{@link InterruptedException}</li>
* <li>{@link InterruptedIOException} except for {@link SocketTimeoutException}</li>
* <li>{@link FileLockInterruptionException}</li>
* <li>{@link ClosedByInterruptException}</li>
* </ul></p>
*
* @param t caught throwable. May be null.
* @return true if this thread was interrupted or the exception indicates
* an operation was interrupted.
*/
protected static boolean cancelled(Throwable t) {
// Clear the interrupted state so we continue to be cancelled if the
// thread is re-used.
if (Thread.interrupted())
return true;
while (t != null) {
if (t instanceof InterruptedException ||
(t instanceof InterruptedIOException && !(t instanceof SocketTimeoutException)) ||
t instanceof FileLockInterruptionException ||
t instanceof ClosedByInterruptException)
{
return true;
}
t = t.getCause();
}
return false;
}
/**
* Create a new instance of MSL control with the specified number of
* threads. A thread count of zero will cause all operations to execute on
* the calling thread.
*
* @param numThreads number of worker threads to create.
*/
public MslControl(final int numThreads) {
this(numThreads, null, null);
}
/**
* Create a new instance of MSL control with the specified number of
* threads and user error message registry. A thread count of zero will
* cause all operations to execute on the calling thread.
*
* @param numThreads number of worker threads to create.
* @param messageFactory message factory. May be {@code null}.
* @param messageRegistry error message registry. May be {@code null}.
*/
public MslControl(final int numThreads, final MessageFactory messageFactory, final ErrorMessageRegistry messageRegistry) {
if (numThreads < 0)
throw new IllegalArgumentException("Number of threads must be non-negative.");
// Set the stream factory.
this.messageFactory = (messageFactory != null) ? messageFactory : new MessageFactory();
// Set the message registry.
this.messageRegistry = (messageRegistry != null) ? messageRegistry : new DummyMessageRegistry();
// Create the thread pool if requested.
if (numThreads > 0)
executor = Executors.newFixedThreadPool(numThreads);
else
executor = new SynchronousExecutor();
// Create the dummy master token used as a special value when releasing
// the renewal lock without a new master token.
try {
final MslContext ctx = new DummyMslContext();
final MslObject dummy = ctx.getMslEncoderFactory().createObject();
final byte[] keydata = new byte[16];
final SecretKey encryptionKey = new SecretKeySpec(keydata, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(keydata, JcaAlgorithm.HMAC_SHA256);
NULL_MASTER_TOKEN = new MasterToken(ctx, new Date(), new Date(), 1L, 1L, dummy, "dummy", encryptionKey, hmacKey);
} catch (final MslEncodingException e) {
throw new MslInternalException("Unexpected exception when constructing dummy master token.", e);
} catch (final MslCryptoException e) {
throw new MslInternalException("Unexpected exception when constructing dummy master token.", e);
}
}
/**
* Assigns a filter stream factory that will be used to filter any incoming
* or outgoing messages. The filters will be placed between the MSL message
* and MSL control, meaning they will see the actual MSL message data as it
* is being read from or written to the remote entity.
*
* @param factory filter stream factory. May be null.
*/
public void setFilterFactory(final FilterStreamFactory factory) {
filterFactory = factory;
}
/**
* Gracefully shutdown the MSL control instance. No additional messages may
* be processed. Any messages pending or in process will be completed.
*/
public void shutdown() {
executor.shutdown();
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
executor.shutdownNow();
super.finalize();
}
/**
* <p>Returns the newest master token from the MSL store and acquires the
* master token's read lock.</p>
*
* <p>When the caller no longer requires the master token or its crypto
* context to exist (i.e. it does not expect to receive a response that
* uses the same master token) then it must release the lock.</p>
*
* @param ctx MSL context.
* @return the newest master token or null if there is none.
* @throws InterruptedException if the thread is interrupted while trying
* to acquire the master token's read lock.
* @see #releaseMasterToken(MasterToken)
*/
private MasterToken getNewestMasterToken(final MslContext ctx) throws InterruptedException {
do {
// Get the newest master token. If there is none then immediately
// return.
final MslStore store = ctx.getMslStore();
final MasterToken masterToken = store.getMasterToken();
if (masterToken == null) return null;
// Acquire the master token read lock, creating it if necessary.
final MslContextMasterTokenKey key = new MslContextMasterTokenKey(ctx, masterToken);
final ReadWriteLock newLock = new ReentrantReadWriteLock();
final ReadWriteLock oldLock = masterTokenLocks.putIfAbsent(key, newLock);
final ReadWriteLock finalLock = (oldLock != null) ? oldLock : newLock;
finalLock.readLock().lockInterruptibly();
// Now we have to be tricky and make sure the master token we just
// acquired is still the newest master token. This is necessary
// just in case the master token was deleted between grabbing it
// from the MSL store and acquiring the read lock.
final MasterToken newestMasterToken = store.getMasterToken();
if (masterToken.equals(newestMasterToken))
return masterToken;
// If the master tokens are not the same then release the read
// lock, acquire the write lock, and then delete the master token
// lock (it may already be deleted). Then try again.
finalLock.readLock().unlock();
finalLock.writeLock().lockInterruptibly();
masterTokenLocks.remove(key);
finalLock.writeLock().unlock();
} while (true);
}
/**
* Deletes the provided master token from the MSL store. Doing so requires
* acquiring the master token's write lock.
*
* @param ctx MSL context.
* @param masterToken master token to delete. May be null.
* @throws InterruptedException if the thread is interrupted while trying
* to acquire the master token's write lock.
*/
private void deleteMasterToken(final MslContext ctx, final MasterToken masterToken) throws InterruptedException {
// Do nothing if the master token is null.
if (masterToken == null)
return;
// Acquire the write lock and delete the master token from the store.
//
// TODO it would be nice to do this on another thread to avoid delaying
// the application.
final MslContextMasterTokenKey key = new MslContextMasterTokenKey(ctx, masterToken);
final ReadWriteLock newLock = new ReentrantReadWriteLock();
final ReadWriteLock oldLock = masterTokenLocks.putIfAbsent(key, newLock);
// ReentrantReadWriteLock requires us to release the read lock if
// we are holding it before acquiring the write lock. If there is
// an old lock then we are already holding the read lock. Otherwise
// no one is holding any locks.
final Lock writeLock;
if (oldLock != null) {
oldLock.readLock().unlock();
writeLock = oldLock.writeLock();
} else {
writeLock = newLock.writeLock();
}
writeLock.lockInterruptibly();
try {
ctx.getMslStore().removeCryptoContext(masterToken);
} finally {
// It should be okay to delete this read/write lock because no
// one should be using the deleted master token anymore; a new
// master token would have been received before deleting the
// old one.
masterTokenLocks.remove(key);
writeLock.unlock();
}
}
/**
* Release the read lock of the provided master token. If no master token
* is provided then this method is a no-op.
*
* @param ctx MSL context.
* @param masterToken the master token. May be null.
* @see #getNewestMasterToken(MslContext)
*/
private void releaseMasterToken(final MslContext ctx, final MasterToken masterToken) {
if (masterToken != null) {
final MslContextMasterTokenKey key = new MslContextMasterTokenKey(ctx, masterToken);
final ReadWriteLock lock = masterTokenLocks.get(key);
// The lock may be null if the master token was deleted.
if (lock != null)
lock.readLock().unlock();
}
}
/**
* Update the MSL store crypto contexts with the crypto contexts of the
* message being sent. Only crypto contexts for master tokens used by the
* local entity for message authentication are saved.
*
* @param ctx MSL context.
* @param messageHeader outgoing message header.
* @param keyExchangeData outgoing message key exchange data.
* @throws InterruptedException if the thread is interrupted while trying
* to delete an old master token.
*/
private void updateCryptoContexts(final MslContext ctx, final MessageHeader messageHeader, final KeyExchangeData keyExchangeData) throws InterruptedException {
// In trusted network mode save the crypto context of the message's key
// response data as an optimization.
final MslStore store = ctx.getMslStore();
if (!ctx.isPeerToPeer() && keyExchangeData != null) {
final KeyResponseData keyResponseData = keyExchangeData.keyResponseData;
final ICryptoContext keyxCryptoContext = keyExchangeData.cryptoContext;
final MasterToken keyxMasterToken = keyResponseData.getMasterToken();
store.setCryptoContext(keyxMasterToken, keyxCryptoContext);
// Delete the old master token. Even if we receive future messages
// with this master token we can reconstruct the crypto context.
deleteMasterToken(ctx, messageHeader.getMasterToken());
}
}
/**
* Update the MSL store crypto contexts with the crypto contexts provided
* by received message.
*
* @param ctx MSL context.
* @param request previous message the response was received for.
* @param response received message input stream.
* @throws InterruptedException if the thread is interrupted while trying
* to delete an old master token.
*/
private void updateCryptoContexts(final MslContext ctx, final MessageHeader request, final MessageInputStream response) throws InterruptedException {
// Do nothing for error messages.
final MessageHeader messageHeader = response.getMessageHeader();
if (messageHeader == null)
return;
// Save the crypto context of the message's key response data.
final MslStore store = ctx.getMslStore();
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null) {
final MasterToken keyxMasterToken = keyResponseData.getMasterToken();
store.setCryptoContext(keyxMasterToken, response.getKeyExchangeCryptoContext());
// Delete the old master token. We won't use it anymore to build
// messages.
deleteMasterToken(ctx, request.getMasterToken());
}
}
/**
* Update the MSL store by removing any service tokens marked for deletion
* and adding/replacing any other service tokens contained in the message
* header.
*
* @param ctx MSL context.
* @param masterToken master for the service tokens.
* @param userIdToken user ID token for the service tokens.
* @param serviceTokens the service tokens to update.
* @throws MslException if a token cannot be removed or added/replaced
* because of a master token or user ID token mismatch.
*/
private static void storeServiceTokens(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken, final Set<ServiceToken> serviceTokens) throws MslException {
// Remove deleted service tokens from the store. Update stored
// service tokens.
final MslStore store = ctx.getMslStore();
final Set<ServiceToken> storeTokens = new HashSet<ServiceToken>();
for (final ServiceToken token : serviceTokens) {
// Skip service tokens that are bound to a master token if the
// local entity issued the master token.
if (token.isBoundTo(masterToken) && masterToken.isVerified())
continue;
final byte[] data = token.getData();
if (data != null && data.length == 0)
store.removeServiceTokens(token.getName(), token.isMasterTokenBound() ? masterToken : null, token.isUserIdTokenBound() ? userIdToken : null);
else
storeTokens.add(token);
}
store.addServiceTokens(storeTokens);
}
/**
* <p>Create a new message builder that will craft a new message.</p>
*
* <p>If a master token is available it will be used to build the new
* message and its read lock will be acquired. The caller must release the
* read lock after it has either received a response to the built request
* or after sending the message if no response is expected.</p>
*
* <p>If a master token is available and a user ID is provided by the
* message context the user ID token for that user ID will be used to build
* the message if the user ID token is bound to the master token.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @return the message builder.
* @throws InterruptedException if the thread is interrupted while trying
* to acquire the master token's read lock.
*/
private MessageBuilder buildRequest(final MslContext ctx, final MessageContext msgCtx) throws InterruptedException {
final MslStore store = ctx.getMslStore();
// Grab the newest master token.
final MasterToken masterToken = getNewestMasterToken(ctx);
try {
final UserIdToken userIdToken;
if (masterToken != null) {
// Grab the user ID token for the message's user. It may not be bound
// to the newest master token if the newest master token invalidated
// it.
final String userId = msgCtx.getUserId();
final UserIdToken storedUserIdToken = (userId != null) ? store.getUserIdToken(userId) : null;
userIdToken = (storedUserIdToken != null && storedUserIdToken.isBoundTo(masterToken)) ? storedUserIdToken : null;
} else {
userIdToken = null;
}
final MessageBuilder builder = messageFactory.createRequest(ctx, masterToken, userIdToken);
builder.setNonReplayable(msgCtx.isNonReplayable());
return builder;
} catch (final MslException e) {
// Release the master token lock.
releaseMasterToken(ctx, masterToken);
throw new MslInternalException("User ID token not bound to master token despite internal check.", e);
} catch (final RuntimeException re) {
// Release the master token lock.
releaseMasterToken(ctx, masterToken);
throw re;
}
}
/**
* <p>Create a new message builder that will craft a new message in
* response to another message. The constructed message may be used as a
* request.</p>
*
* <p>In peer-to-peer mode if the response does not have a primary master
* token and a master token is available then it will be used to build the
* new message and its read lock will be acquired. The caller must release
* the read lock after it has either received a response to the built
* request or after sending the message if no response is expected.</p>
*
* <p>In peer-to-peer mode if a master token is being used to build the new
* message and a user ID is provided by the message context, the user ID
* token for that user ID will be used to build the message if the user ID
* token is bound to the master token.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param request message header to respond to.
* @return the message builder.
* @throws MslMasterTokenException if the provided message's master token
* is not trusted.
* @throws MslCryptoException if the crypto context from a key exchange
* cannot be created.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created.
* @throws MslUserAuthException if there is an error with the user
* authentication data or the user ID token cannot be created.
* @throws MslException if a user ID token in the message header is not
* bound to its corresponding master token.
* @throws InterruptedException if the thread is interrupted while trying
* to acquire the master token's read lock. (Only applicable in
* peer-to-peer mode.)
*/
private MessageBuilder buildResponse(final MslContext ctx, final MessageContext msgCtx, final MessageHeader request) throws MslKeyExchangeException, MslCryptoException, MslMasterTokenException, MslUserAuthException, MslException, InterruptedException {
// Create the response.
final MessageBuilder builder = messageFactory.createResponse(ctx, request);
builder.setNonReplayable(msgCtx.isNonReplayable());
// Trusted network clients should use the newest master token. Trusted
// network servers must not use a newer master token. This method is
// only called by trusted network clients after a handshake response is
// received so if the request does not contain key response data then
// we know the local entity is a trusted network server and should
// return immediately.
if (!ctx.isPeerToPeer() && request.getKeyResponseData() == null)
return builder;
// In peer-to-peer mode the primary master token may no longer be known
// if it was renewed between calls to receive() and respond()
// (otherwise we would have held a lock). In this case, we need to
// use the newest primary authentication tokens.
//
// Likewise, if the primary authentication tokens are not already set
// then use what we have received.
//
// Either way we should be able to use the newest master token,
// acquiring the read lock at the same time which we definitely want.
final MasterToken masterToken = getNewestMasterToken(ctx);
try {
final UserIdToken userIdToken;
if (masterToken != null) {
// Grab the user ID token for the message's user. It may not be
// bound to the newest master token if the newest master token
// invalidated it.
final String userId = msgCtx.getUserId();
final MslStore store = ctx.getMslStore();
final UserIdToken storedUserIdToken = (userId != null) ? store.getUserIdToken(userId) : null;
userIdToken = (storedUserIdToken != null && storedUserIdToken.isBoundTo(masterToken)) ? storedUserIdToken : null;
} else {
userIdToken = null;
}
// Set the authentication tokens.
builder.setAuthTokens(masterToken, userIdToken);
return builder;
} catch (final RuntimeException e) {
// Release the master token lock.
releaseMasterToken(ctx, masterToken);
throw e;
}
}
/**
* <p>Create a new message builder that will craft a new message based on
* another message. The constructed message will have a randomly assigned
* message ID, thus detaching it from the message being responded to, and
* may be used as a request.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param request message header to respond to.
* @return the message builder.
* @throws MslCryptoException if there is an error accessing the remote
* entity identity.
* @throws MslException if any of the request's user ID tokens is not bound
* to its master token.
*/
private MessageBuilder buildDetachedResponse(final MslContext ctx, final MessageContext msgCtx, final MessageHeader request) throws MslCryptoException, MslException {
// Create an idempotent response. Assign a random message ID.
final MessageBuilder builder = messageFactory.createIdempotentResponse(ctx, request);
builder.setNonReplayable(msgCtx.isNonReplayable());
builder.setMessageId(MslUtils.getRandomLong(ctx));
return builder;
}
/**
* The result of building an error response.
*/
private static class ErrorResult {
/**
* Create a new result with the provided request builder and message
* context.
*
* @param builder
* @param msgCtx
*/
public ErrorResult(final MessageBuilder builder, final MessageContext msgCtx) {
this.builder = builder;
this.msgCtx = msgCtx;
}
/** The new request to send. */
public final MessageBuilder builder;
/** The new message context to use. */
public final MessageContext msgCtx;
}
/**
* Creates a message builder and message context appropriate for re-sending
* the original message in response to the received error.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param sent result of original sent message.
* @param errorHeader received error header.
* @return the message builder and message context that should be used to
* re-send the original request in response to the received error
* or null if the error cannot be handled (i.e. should be returned
* to the application).
* @throws MslException if there is an error creating the message.
* @throws InterruptedException if the thread is interrupted while trying
* to acquire the master token lock (user re-authentication only).
*/
private ErrorResult buildErrorResponse(final MslContext ctx, final MessageContext msgCtx, final SendResult sent, final ErrorHeader errorHeader) throws MslException, InterruptedException {
// Handle the error.
final MessageHeader requestHeader = sent.request.getMessageHeader();
final List<PayloadChunk> payloads = sent.request.getPayloads();
final MslConstants.ResponseCode errorCode = errorHeader.getErrorCode();
switch (errorCode) {
case ENTITYDATA_REAUTH:
case ENTITY_REAUTH:
{
// If the MSL context cannot provide new entity authentication
// data then return null. This function should never return
// null.
try {
final MslContext.ReauthCode reauthCode = MslContext.ReauthCode.valueOf(errorCode);
if (ctx.getEntityAuthenticationData(reauthCode) == null)
return null;
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Unsupported response code mapping onto entity re-authentication codes.", e);
}
// Resend the request without a master token or user ID token.
// Make sure the use the error header message ID + 1.
final long messageId = MessageBuilder.incrementMessageId(errorHeader.getMessageId());
final MessageContext resendMsgCtx = new ResendMessageContext(payloads, msgCtx);
final MessageBuilder requestBuilder = messageFactory.createRequest(ctx, null, null, messageId);
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
requestBuilder.setPeerAuthTokens(peerMasterToken, peerUserIdToken);
}
requestBuilder.setNonReplayable(resendMsgCtx.isNonReplayable());
return new ErrorResult(requestBuilder, resendMsgCtx);
}
case USERDATA_REAUTH:
case SSOTOKEN_REJECTED:
{
// If the message context cannot provide user authentication
// data then return null.
try {
final MessageContext.ReauthCode reauthCode = MessageContext.ReauthCode.valueOf(errorCode);
if (msgCtx.getUserAuthData(reauthCode, false, true) == null)
return null;
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Unsupported response code mapping onto user re-authentication codes.", e);
}
// Otherwise we have now triggered the need for new user
// authentication data. Fall through.
}
case USER_REAUTH:
{
// Grab the newest master token and its read lock.
final MasterToken masterToken = getNewestMasterToken(ctx);
// Resend the request without a user ID token.
// Make sure the use the error header message ID + 1.
final long messageId = MessageBuilder.incrementMessageId(errorHeader.getMessageId());
final MessageContext resendMsgCtx = new ResendMessageContext(payloads, msgCtx);
final MessageBuilder requestBuilder = messageFactory.createRequest(ctx, masterToken, null, messageId);
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
requestBuilder.setPeerAuthTokens(peerMasterToken, peerUserIdToken);
}
requestBuilder.setNonReplayable(resendMsgCtx.isNonReplayable());
return new ErrorResult(requestBuilder, resendMsgCtx);
}
case KEYX_REQUIRED:
{
// This error will only be received by trusted network clients
// and peer-to-peer entities that do not have a master token.
// Make sure the use the error header message ID + 1.
final long messageId = MessageBuilder.incrementMessageId(errorHeader.getMessageId());
final MessageContext resendMsgCtx = new ResendMessageContext(payloads, msgCtx);
final MessageBuilder requestBuilder = messageFactory.createRequest(ctx, null, null, messageId);
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
requestBuilder.setPeerAuthTokens(peerMasterToken, peerUserIdToken);
}
// Mark the message as renewable to make sure the response can
// be encrypted. During renewal lock acquisition we will either
// block until we acquire the renewal lock or receive a master
// token.
requestBuilder.setRenewable(true);
requestBuilder.setNonReplayable(resendMsgCtx.isNonReplayable());
return new ErrorResult(requestBuilder, resendMsgCtx);
}
case EXPIRED:
{
// Grab the newest master token and its read lock.
final MasterToken masterToken = getNewestMasterToken(ctx);
final UserIdToken userIdToken;
if (masterToken != null) {
// Grab the user ID token for the message's user. It may not be bound
// to the newest master token if the newest master token invalidated
// it.
final String userId = msgCtx.getUserId();
final MslStore store = ctx.getMslStore();
final UserIdToken storedUserIdToken = (userId != null) ? store.getUserIdToken(userId) : null;
userIdToken = (storedUserIdToken != null && storedUserIdToken.isBoundTo(masterToken)) ? storedUserIdToken : null;
} else {
userIdToken = null;
}
// Resend the request.
final long messageId = MessageBuilder.incrementMessageId(errorHeader.getMessageId());
final MessageContext resendMsgCtx = new ResendMessageContext(payloads, msgCtx);
final MessageBuilder requestBuilder = messageFactory.createRequest(ctx, masterToken, userIdToken, messageId);
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
requestBuilder.setPeerAuthTokens(peerMasterToken, peerUserIdToken);
}
// If the newest master token is equal to the previous
// request's master token then mark this message as renewable.
// During renewal lock acquisition we will either block until
// we acquire the renewal lock or receive a master token.
//
// Check for a missing master token in case the remote entity
// returned an incorrect error code.
final MasterToken requestMasterToken = requestHeader.getMasterToken();
if (requestMasterToken == null || requestMasterToken.equals(masterToken))
requestBuilder.setRenewable(true);
requestBuilder.setNonReplayable(resendMsgCtx.isNonReplayable());
return new ErrorResult(requestBuilder, resendMsgCtx);
}
case REPLAYED:
{
// This error will be received if the previous request's non-
// replayable ID is not accepted by the remote entity. In this
// situation simply try again.
//
// Grab the newest master token and its read lock.
final MasterToken masterToken = getNewestMasterToken(ctx);
final UserIdToken userIdToken;
if (masterToken != null) {
// Grab the user ID token for the message's user. It may not be bound
// to the newest master token if the newest master token invalidated
// it.
final String userId = msgCtx.getUserId();
final MslStore store = ctx.getMslStore();
final UserIdToken storedUserIdToken = (userId != null) ? store.getUserIdToken(userId) : null;
userIdToken = (storedUserIdToken != null && storedUserIdToken.isBoundTo(masterToken)) ? storedUserIdToken : null;
} else {
userIdToken = null;
}
// Resend the request.
final long messageId = MessageBuilder.incrementMessageId(errorHeader.getMessageId());
final MessageContext resendMsgCtx = new ResendMessageContext(payloads, msgCtx);
final MessageBuilder requestBuilder = messageFactory.createRequest(ctx, masterToken, userIdToken, messageId);
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
requestBuilder.setPeerAuthTokens(peerMasterToken, peerUserIdToken);
}
// Mark the message as replayable or not as dictated by the
// message context.
requestBuilder.setNonReplayable(resendMsgCtx.isNonReplayable());
return new ErrorResult(requestBuilder, resendMsgCtx);
}
default:
// Nothing to do. Return null.
return null;
}
}
/**
* Called after successfully handling an error message to delete the old
* invalid crypto contexts and bound service tokens associated with the
* invalid master token or user ID token.
*
* @param ctx MSL context.
* @param requestHeader initial request that generated the error.
* @param errorHeader error response received and successfully handled.
* @throws MslException if the user ID token is not bound to the master
* token. (This should not happen.)
* @throws InterruptedException if the thread is interrupted while trying
* to delete the old master token.
*/
private void cleanupContext(final MslContext ctx, final MessageHeader requestHeader, final ErrorHeader errorHeader) throws MslException, InterruptedException {
// The data-reauth error codes also delete tokens in case those errors
// are returned when a token does exist.
switch (errorHeader.getErrorCode()) {
case ENTITY_REAUTH:
case ENTITYDATA_REAUTH:
{
// The old master token is invalid. Delete the old
// crypto context and any bound service tokens.
deleteMasterToken(ctx, requestHeader.getMasterToken());
break;
}
case USER_REAUTH:
case USERDATA_REAUTH:
{
// The old user ID token is invalid. Delete the old user ID
// token and any bound service tokens. It is okay to stomp on
// other requests when doing this because automatically
// generated messages and replies to outstanding requests that
// use the user ID token and service tokens will work fine.
//
// This will be a no-op if we received a new user ID token that
// overwrote the old one.
final MasterToken masterToken = requestHeader.getMasterToken();
final UserIdToken userIdToken = requestHeader.getUserIdToken();
if (masterToken != null && userIdToken != null) {
final MslStore store = ctx.getMslStore();
store.removeUserIdToken(userIdToken);
}
break;
}
default:
// No cleanup required.
break;
}
}
/**
* The result of sending a message.
*/
private static class SendResult {
/**
* Create a new result with the provided message output stream
* containing the cached application data (which was not sent if the
* message was a handshake).
*
* @param request request message output stream.
* @param handshake true if a handshake message was sent and the
* application data was not sent.
*/
private SendResult(final MessageOutputStream request, final boolean handshake) {
this.request = request;
this.handshake = handshake;
}
/** The request message output stream. */
public final MessageOutputStream request;
/** True if the message was a handshake (application data was not sent). */
public final boolean handshake;
}
/**
* <p>Send a message. The message context will be used to build the message.
* If the message will be sent then the stored master token crypto contexts
* and service tokens will be updated just prior to sending.</p>
*
* <p>If the application data must be encrypted but the message does not
* support payload encryption then a handshake message will be sent. This
* will be indicated by the returned result.</p>
*
* <p>N.B. The message builder must be set renewable and non-replayable
* before calling this method. If the application data must be delayed then
* this specific message will be sent replayable regardless of the builder
* non-replayable value.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param out remote entity output stream.
* @param builder message builder.
* @param closeDestination true if the remote entity output stream must
* be closed when the constructed message output stream is closed.
* @return a result containing the sent message header and a copy of the
* application data.
* @throws IOException if there is an error writing the message.
* @throws MslMessageException if there is an error building the request.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslCryptoException if there is an error encrypting or signing
* the message.
* @throws MslMasterTokenException if the header master token is not
* trusted and needs to be to accept this message header.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
* @throws MslKeyExchangeException if there is an error generating the key
* request data.
* @throws MslException if there was an error updating the service tokens
* or building the message header.
* @throws InterruptedException if the thread is interrupted while trying
* to delete an old master token the sent message is replacing.
*/
private SendResult send(final MslContext ctx, final MessageContext msgCtx, final OutputStream out, final MessageBuilder builder, final boolean closeDestination) throws IOException, MslMessageException, MslEncodingException, MslCryptoException, MslMasterTokenException, MslEntityAuthException, MslKeyExchangeException, MslException, InterruptedException {
final MasterToken masterToken = builder.getMasterToken();
UserIdToken userIdToken = builder.getUserIdToken();
final UserIdToken peerUserIdToken = builder.getPeerUserIdToken();
// Ask the message context for user authentication data.
boolean userAuthDataDelayed = false;
final String userId = msgCtx.getUserId();
if (userId != null) {
// If we are not including a user ID token, the user authentication
// data is required.
final boolean required = (userIdToken == null);
final UserAuthenticationData userAuthData = msgCtx.getUserAuthData(null, builder.isRenewable(), required);
if (userAuthData != null) {
// We can only include user authentication data if the message
// header will be encrypted and integrity protected.
if (builder.willEncryptHeader() && builder.willIntegrityProtectHeader())
builder.setUserAuthenticationData(userAuthData);
// If the message should include user authentication data but
// cannot at this time then we also cannot send the application
// data as it may be user-specific. There is also no user ID token
// otherwise the header will be encrypted.
else
userAuthDataDelayed = true;
}
// If user authentication data is required but was not provided
// then this message may be associated with a user but not have any
// user authentication data. For example upon user creation.
}
// If there is no user ID token for the remote user then check if a
// user ID token should be created and attached.
if (!ctx.isPeerToPeer() && userIdToken == null ||
ctx.isPeerToPeer() && peerUserIdToken == null)
{
final MslUser user = msgCtx.getUser();
if (user != null) {
builder.setUser(user);
// The user ID token may have changed and we need the latest one to
// store the service tokens below.
userIdToken = builder.getUserIdToken();
}
}
// If we have not delayed the user authentication data, and the message
// payloads either do not need to be encrypted or can be encrypted with
// this message, and the message payloads either do not need to be
// integrity protected or can be integrity protected with this message,
// and the message is either replayable or the message will be sent non-
// replayable and has a master token, then we can write the application
// data now.
final boolean writeData = !userAuthDataDelayed &&
(!msgCtx.isEncrypted() || builder.willEncryptPayloads()) &&
(!msgCtx.isIntegrityProtected() || builder.willIntegrityProtectPayloads()) &&
(!msgCtx.isNonReplayable() || (builder.isNonReplayable() && masterToken != null));
final boolean handshake = !writeData;
// Set the message handshake flag.
builder.setHandshake(handshake);
// If this message is renewable...
final Set<KeyRequestData> keyRequests = new HashSet<KeyRequestData>();
if (builder.isRenewable()) {
// Ask for key request data if we are using entity authentication
// data or if the master token needs renewing or if the message is
// non-replayable.
final Date now = ctx.getRemoteTime();
if (masterToken == null || masterToken.isRenewable(now) || msgCtx.isNonReplayable()) {
keyRequests.addAll(msgCtx.getKeyRequestData());
for (final KeyRequestData keyRequest : keyRequests)
builder.addKeyRequestData(keyRequest);
}
}
// Ask the caller to perform any final modifications to the
// message and then build the message.
final MessageServiceTokenBuilder serviceTokenBuilder = new MessageServiceTokenBuilder(ctx, msgCtx, builder);
msgCtx.updateServiceTokens(serviceTokenBuilder, handshake);
final MessageHeader requestHeader = builder.getHeader();
// Deliver the header that will be sent to the debug context.
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
if (debugCtx != null) debugCtx.sentHeader(requestHeader);
// Update the stored crypto contexts just before sending the
// message so we can receive new messages immediately after it is
// sent.
final KeyExchangeData keyExchangeData = builder.getKeyExchangeData();
updateCryptoContexts(ctx, requestHeader, keyExchangeData);
// Update the stored service tokens.
final MasterToken tokenVerificationMasterToken = (keyExchangeData != null) ? keyExchangeData.keyResponseData.getMasterToken() : masterToken;
final Set<ServiceToken> serviceTokens = requestHeader.getServiceTokens();
storeServiceTokens(ctx, tokenVerificationMasterToken, userIdToken, serviceTokens);
// We will either use the header crypto context or the key exchange
// data crypto context in trusted network mode to process the message
// payloads.
final ICryptoContext payloadCryptoContext;
if (!ctx.isPeerToPeer() && keyExchangeData != null)
payloadCryptoContext = keyExchangeData.cryptoContext;
else
payloadCryptoContext = requestHeader.getCryptoContext();
// Send the request.
final OutputStream os = (filterFactory != null) ? filterFactory.getOutputStream(out) : out;
final MessageOutputStream request = messageFactory.createOutputStream(ctx, os, requestHeader, payloadCryptoContext);
request.closeDestination(closeDestination);
// If it is okay to write the data then ask the application to write it
// and return the real output stream. Otherwise it will be asked to do
// so after the handshake is completed.
if (!handshake)
msgCtx.write(request);
// Return the result.
return new SendResult(request, handshake);
}
/**
* <p>Receive a message.</p>
*
* <p>If a message is received the stored master tokens, crypto contexts,
* user ID tokens, and service tokens will be updated.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param request message header of the previously sent message, if any,
* the received message is responding to. May be null.
* @return the received message.
* @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 MslMasterTokenException if the master token is not trusted and
* needs to be.
* @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 MslException if the message does not contain an entity
* authentication data or a master token, or a token is improperly
* bound to another token, or there is an error updating the
* service tokens.
* @throws MslMessageException if the message does not contain an entity
* authentication data or a master token, or a token is improperly
* bound to another token, or there is an error updating the
* service tokens, or the header data is missing or invalid, or the
* message ID is negative, or the message is not encrypted and
* contains user authentication data, or if the message master
* token is expired and the message is not renewable.
* @throws InterruptedException if the thread is interrupted while trying
* to delete an old master token the received message is replacing.
*/
private MessageInputStream receive(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final MessageHeader request) throws IOException, MslEncodingException, MslEntityAuthException, MslCryptoException, MslUserAuthException, MslMessageException, MslKeyExchangeException, MslMasterTokenException, MslException, InterruptedException {
// Grab the response.
final Set<KeyRequestData> keyRequestData = new HashSet<KeyRequestData>();
if (request != null)
keyRequestData.addAll(request.getKeyRequestData());
final Map<String,ICryptoContext> cryptoContexts = msgCtx.getCryptoContexts();
final InputStream is = (filterFactory != null) ? filterFactory.getInputStream(in) : in;
final MessageInputStream response = messageFactory.createInputStream(ctx, is, keyRequestData, cryptoContexts);
// Deliver the received header to the debug context.
final MessageHeader responseHeader = response.getMessageHeader();
final ErrorHeader errorHeader = response.getErrorHeader();
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
if (debugCtx != null) debugCtx.receivedHeader((responseHeader != null) ? responseHeader : errorHeader);
// Pull the response master token or entity authentication data and
// user ID token or user authentication data to attach them to any
// thrown exceptions.
final MasterToken masterToken;
final EntityAuthenticationData entityAuthData;
final UserIdToken userIdToken;
final UserAuthenticationData userAuthData;
if (responseHeader != null) {
masterToken = responseHeader.getMasterToken();
entityAuthData = responseHeader.getEntityAuthenticationData();
userIdToken = responseHeader.getUserIdToken();
userAuthData = responseHeader.getUserAuthenticationData();
} else {
masterToken = null;
entityAuthData = errorHeader.getEntityAuthenticationData();
userIdToken = null;
userAuthData = null;
}
try {
// If there is a request make sure the response message ID equals
// the request message ID + 1.
if (request != null) {
// Only enforce this for message headers and error headers that are
// not entity re-authenticate or entity data re-authenticate (as in
// those cases the remote entity is not always able to extract the
// request message ID).
final ResponseCode errorCode = (errorHeader != null) ? errorHeader.getErrorCode() : null;
if (responseHeader != null ||
(errorCode != ResponseCode.FAIL && errorCode != ResponseCode.TRANSIENT_FAILURE && errorCode != ResponseCode.ENTITY_REAUTH && errorCode != ResponseCode.ENTITYDATA_REAUTH))
{
final long responseMessageId = (responseHeader != null) ? responseHeader.getMessageId() : errorHeader.getMessageId();
final long expectedMessageId = MessageBuilder.incrementMessageId(request.getMessageId());
if (responseMessageId != expectedMessageId)
throw new MslMessageException(MslError.UNEXPECTED_RESPONSE_MESSAGE_ID, "expected " + expectedMessageId + "; received " + responseMessageId);
}
}
// Verify expected identity if specified.
final String expectedIdentity = msgCtx.getRemoteEntityIdentity();
if (expectedIdentity != null) {
// Reject if the remote entity identity is not equal to the
// message entity authentication data identity.
if (entityAuthData != null) {
final String entityAuthIdentity = entityAuthData.getIdentity();
if (entityAuthIdentity != null && !expectedIdentity.equals(entityAuthIdentity))
throw new MslMessageException(MslError.MESSAGE_SENDER_MISMATCH, "expected " + expectedIdentity + "; received " + entityAuthIdentity);
}
// Reject if in peer-to-peer mode and the message sender does
// not match.
if (ctx.isPeerToPeer()) {
final String sender = response.getIdentity();
if (sender != null && !expectedIdentity.equals(sender))
throw new MslMessageException(MslError.MESSAGE_SENDER_MISMATCH, "expected " + expectedIdentity + "; received " + sender);
}
}
// Process the response.
if (responseHeader != null) {
// If there is a request update the stored crypto contexts.
if (request != null)
updateCryptoContexts(ctx, request, response);
// In trusted network mode the local tokens are the primary tokens.
// In peer-to-peer mode they are the peer tokens. The master token
// might be in the key response data.
final KeyResponseData keyResponseData = responseHeader.getKeyResponseData();
final MasterToken tokenVerificationMasterToken;
final UserIdToken localUserIdToken;
final Set<ServiceToken> serviceTokens;
if (!ctx.isPeerToPeer()) {
tokenVerificationMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : responseHeader.getMasterToken();
localUserIdToken = responseHeader.getUserIdToken();
serviceTokens = responseHeader.getServiceTokens();
} else {
tokenVerificationMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : responseHeader.getPeerMasterToken();
localUserIdToken = responseHeader.getPeerUserIdToken();
serviceTokens = responseHeader.getPeerServiceTokens();
}
// Save any returned user ID token if the local entity is not the
// issuer of the user ID token.
final String userId = msgCtx.getUserId();
if (userId != null && localUserIdToken != null && !localUserIdToken.isVerified())
ctx.getMslStore().addUserIdToken(userId, localUserIdToken);
// Update the stored service tokens.
storeServiceTokens(ctx, tokenVerificationMasterToken, localUserIdToken, serviceTokens);
}
// Update the synchronized clock if we are a trusted network client
// (there is a request) or peer-to-peer entity.
final Date timestamp = (responseHeader != null) ? responseHeader.getTimestamp() : errorHeader.getTimestamp();
if (timestamp != null && (request != null || ctx.isPeerToPeer()))
ctx.updateRemoteTime(timestamp);
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setUserIdToken(userIdToken);
e.setUserAuthenticationData(userAuthData);
throw e;
}
// Return the result.
return response;
}
/**
* Indicates response expectations for a specific request.
*/
private static enum Receive {
/** A response is always expected. */
ALWAYS,
/** A response is only expected if tokens are being renewed. */
RENEWING,
/** A response is never expected. */
NEVER
}
/**
* The result of sending and receiving messages.
*/
private static class SendReceiveResult extends SendResult {
/**
* Create a new result with the provided response and send result.
*
* @param response response message input stream. May be {@code null}.
* @param sent sent message result.
*/
public SendReceiveResult(final MessageInputStream response, final SendResult sent) {
super(sent.request, sent.handshake);
this.response = response;
}
/** The response message input stream. */
public final MessageInputStream response;
}
/**
* <p>Send the provided request and optionally receive a response from the
* remote entity. The method will attempt to receive a response if one of
* the following is met:
* <ul>
* <li>the caller indicates a response is expected</li>
* <li>a handshake message was sent</li>
* <li>key request data appears in the request</li>
* <li>a renewable message with user authentication data was sent</li>
* </ul></p>
*
* <p>This method is only used from trusted network clients and peer-to-
* peer entities.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param builder request message builder.
* @param receive indicates if a response should always be expected, should
* only be expected if the master token or user ID token will be
* renewed, or should never be expected.
* @param closeStreams true if the remote entity input and output streams
* must be closed when the constructed message input and output
* streams are closed.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @return the received message or {@code null} if cancelled or interrupted.
* @throws IOException if there was an error reading or writing a
* message.
* @throws MslEncodingException if there is an error parsing or encoding a
* message.
* @throws MslCryptoException if there is an error encrypting/decrypting or
* signing/verifying a message header or creating the message
* payload crypto context.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
* @throws MslUserAuthException if unable to create the user authentication
* data.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be.
* @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, if there is an error building the
* request, or if the response message ID does not equal the
* expected value, or the header data is missing or invalid, or the
* message ID is negative, or the message is not encrypted and
* contains user authentication data.
* @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, or there is an error updating the
* service tokens, or there was an error building the message
* header.
* @throws InterruptedException if the thread is interrupted while trying
* to delete an old master token the received message is replacing.
* @throws TimeoutException if the thread timed out while trying to acquire
* a master token from a renewing thread.
*/
private SendReceiveResult sendReceive(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageBuilder builder, final Receive receive, final boolean closeStreams, final int timeout) throws IOException, MslEncodingException, MslCryptoException, MslEntityAuthException, MslUserAuthException, MslMessageException, MslMasterTokenException, MslKeyExchangeException, MslException, InterruptedException, TimeoutException {
// Attempt to acquire the renewal lock.
final BlockingQueue<MasterToken> renewalQueue = new ArrayBlockingQueue<MasterToken>(1, true);
final boolean renewing;
try {
renewing = acquireRenewalLock(ctx, msgCtx, renewalQueue, builder, timeout);
} catch (final InterruptedException e) {
// Release the master token lock.
releaseMasterToken(ctx, builder.getMasterToken());
// This should only be if we were cancelled so return null.
return null;
} catch (final TimeoutException | RuntimeException e) {
// Release the master token lock.
releaseMasterToken(ctx, builder.getMasterToken());
throw e;
}
// Send the request and receive the response.
final SendResult sent;
MessageInputStream response = null;
try {
// Send the request.
builder.setRenewable(renewing);
sent = send(ctx, msgCtx, out, builder, closeStreams);
// Receive the response if expected, if we sent a handshake request,
// or if we expect a response when renewing tokens and either key
// request data was included or a master token and user
// authentication data was included in a renewable message.
final MessageHeader requestHeader = sent.request.getMessageHeader();
final Set<KeyRequestData> keyRequestData = requestHeader.getKeyRequestData();
if (receive == Receive.ALWAYS || sent.handshake ||
(receive == Receive.RENEWING &&
(!keyRequestData.isEmpty() ||
(requestHeader.isRenewable() && requestHeader.getMasterToken() != null && requestHeader.getUserAuthenticationData() != null))))
{
response = receive(ctx, msgCtx, in, requestHeader);
response.closeSource(closeStreams);
// If we received an error response then cleanup.
final ErrorHeader errorHeader = response.getErrorHeader();
if (errorHeader != null)
cleanupContext(ctx, requestHeader, errorHeader);
}
} finally {
// Release the renewal lock.
if (renewing)
releaseRenewalLock(ctx, renewalQueue, response);
// Release the master token lock.
releaseMasterToken(ctx, builder.getMasterToken());
}
// Return the response.
return new SendReceiveResult(response, sent);
}
/**
* <p>Attempt to acquire the renewal lock if the message will need it using
* the given blocking queue.</p>
*
* <p>If anti-replay is required then this method will block until the
* renewal lock is acquired.</p>
*
* <p>If the message has already been marked renewable then this method
* will block until the renewal lock is acquired or a renewing thread
* delivers a new master token to this builder.</p>
*
* <p>If encryption is required but the builder will not be able to encrypt
* the message payloads, or if integrity protection is required but the
* builder will not be able to integrity protect the message payloads, or
* if the builder's master token is expired, or if there is no user ID
* token but the message is associated with a user and the builder will not
* be able to encrypt and integrity protect the message header, then this
* method will block until the renewal lock is acquired or a renewing
* thread delivers a master token to this builder.</p>
*
* <p>If the message is requesting tokens in response but there is no
* master token, or there is no user ID token but the message is associated
* with a user, then this method will block until the renewal lock is
* acquired or a renewing thread delivers a master token to this builder
* and a user ID token is also available if the message is associated with
* a user.</p>
*
* <p>If there is no master token, or either the master token or the user
* ID token is renewable, or there is no user ID token but the message is
* associated with a user and the builder will be able to encrypt the
* message header then this method will attempt to acquire the renewal
* lock. If unable to do so, it returns null.</p>
*
* <p>If this method returns true, then the renewal lock must be released by
* calling {@code releaseRenewalLock()}.</p>
*
* <p>This method is only used from trusted network clients and peer-to-
* peer entities.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param queue caller's blocking queue.
* @param builder message builder for the message to be sent.
* @param timeout timeout in milliseconds for acquiring the renewal lock
* or receiving a master token.
* @return true if the renewal lock was acquired, false if the builder's
* message is now capable of encryption or the renewal lock is not
* needed.
* @throws InterruptedException if interrupted while waiting to acquire
* a master token from a renewing thread.
* @throws TimeoutException if timed out while waiting to acquire a master
* token from a renewing thread.
* @see #releaseRenewalLock(MslContext, BlockingQueue, MessageInputStream)
*/
private boolean acquireRenewalLock(final MslContext ctx, final MessageContext msgCtx, final BlockingQueue<MasterToken> queue, final MessageBuilder builder, final long timeout) throws InterruptedException, TimeoutException {
MasterToken masterToken = builder.getMasterToken();
UserIdToken userIdToken = builder.getUserIdToken();
final String userId = msgCtx.getUserId();
// If the application data needs to be encrypted and the builder will
// not encrypt payloads, or the application data needs to be integrity
// protected and the builder will not integrity protect payloads, or if
// the master token is expired, or if the message is to be sent with
// user authentication data and the builder will not encrypt and
// integrity protect the header, then we must either mark this message
// as renewable to perform a handshake or get a master token from a
// renewing thread.
//
// If the message has been marked renewable then we must either mark
// this message as renewable or receive a new master token.
//
// If the message must be marked non-replayable and we do not have a
// master token then we must mark this message as renewable to perform
// a handshake or receive a new master token.
final Date startTime = ctx.getRemoteTime();
if ((msgCtx.isEncrypted() && !builder.willEncryptPayloads()) ||
(msgCtx.isIntegrityProtected() && !builder.willIntegrityProtectPayloads()) ||
builder.isRenewable() ||
(masterToken == null && msgCtx.isNonReplayable()) ||
(masterToken != null && masterToken.isExpired(startTime)) ||
(userIdToken == null && userId != null && (!builder.willEncryptHeader() || !builder.willIntegrityProtectHeader())) ||
(msgCtx.isRequestingTokens() && (masterToken == null || (userId != null && userIdToken == null))))
{
do {
// We do not have a master token or this message is non-
// replayable. Try to acquire the renewal lock on this MSL
// context so we can send a handshake message.
final BlockingQueue<MasterToken> ctxRenewingQueue = renewingContexts.putIfAbsent(ctx, queue);
// If there is no one else already renewing then our queue has
// acquired the renewal lock.
if (ctxRenewingQueue == null)
return true;
// Otherwise we need to wait for a master token from the
// renewing request.
final MasterToken newMasterToken = ctxRenewingQueue.poll(timeout, TimeUnit.MILLISECONDS);
// If timed out throw an exception.
if (newMasterToken == null)
throw new TimeoutException("acquireRenewalLock timed out.");
// Put the same master token back on the renewing queue so
// anyone else waiting can also proceed.
ctxRenewingQueue.add(newMasterToken);
// If the renewing request did not acquire a master token then
// try again to acquire renewal ownership.
if (newMasterToken == NULL_MASTER_TOKEN)
continue;
// If the new master token is not equal to the previous master
// token then release the previous master token and get the
// newest master token.
//
// We cannot simply use the new master token directly since we
// have not acquired its master token lock.
final MasterToken previousMasterToken = masterToken;
if (masterToken == null || !masterToken.equals(newMasterToken)) {
releaseMasterToken(ctx, masterToken);
masterToken = getNewestMasterToken(ctx);
// If there is no newest master token (it could have been
// deleted despite just being delivered to us) then try
// again to acquire renewal ownership.
if (masterToken == null)
continue;
}
// The renewing request may have acquired a new user ID token.
// Attach it to this message if the message is associated with
// a user and we do not already have a user ID token.
//
// Unless the previous master token was thrown out, any user ID
// token should still be bound to this new master token. If the
// master token serial number has changed then our user ID
// token is no longer valid and the new one should be attached.
if ((userId != null && userIdToken == null) ||
(userIdToken != null && !userIdToken.isBoundTo(masterToken)))
{
final UserIdToken storedUserIdToken = ctx.getMslStore().getUserIdToken(userId);
userIdToken = (storedUserIdToken != null && storedUserIdToken.isBoundTo(masterToken)) ? storedUserIdToken : null;
}
// Update the message's master token and user ID token.
builder.setAuthTokens(masterToken, userIdToken);
// If the new master token is still expired then try again to
// acquire renewal ownership.
final Date updateTime = ctx.getRemoteTime();
if (masterToken.isExpired(updateTime))
continue;
// If this message is already marked renewable and the received
// master token is the same as the previous master token then
// we must still attempt to acquire the renewal lock.
if (builder.isRenewable() && masterToken.equals(previousMasterToken))
continue;
// If this message is requesting tokens and is associated with
// a user but there is no user ID token then we must still
// attempt to acquire the renewal lock.
if (msgCtx.isRequestingTokens() && userIdToken == null)
continue;
// We may still want to renew, but it is not required. Fall
// through.
break;
} while (true);
}
// If we do not have a master token or the master token should be
// renewed, or we do not have a user ID token but the message is
// associated with a user, or if the user ID token should be renewed,
// then try to mark this message as renewable.
final Date finalTime = ctx.getRemoteTime();
if ((masterToken == null || masterToken.isRenewable(finalTime)) ||
(userIdToken == null && msgCtx.getUserId() != null) ||
(userIdToken != null && userIdToken.isRenewable(finalTime)))
{
// Try to acquire the renewal lock on this MSL context.
final BlockingQueue<MasterToken> ctxRenewingQueue = renewingContexts.putIfAbsent(ctx, queue);
// If there is no one else already renewing then our queue has
// acquired the renewal lock.
if (ctxRenewingQueue == null)
return true;
// Otherwise proceed without acquiring the lock.
return false;
}
// Otherwise we do not need to acquire the renewal lock.
return false;
}
/**
* <p>Release the renewal lock.</p>
*
* <p>Delivers any received master token to the blocking queue. This may be
* a null value if an error message was received or if the received message
* does not contain a master token for the local entity.</p>
*
* <p>If no message was received a null master token will be delivered.</p>
*
* <p>This method is only used from trusted network clients and peer-to-
* peer entities.</p>
*
* @param ctx MSL context.
* @param queue caller's blocking queue.
* @param message received message. May be null if no message was received.
*/
private void releaseRenewalLock(final MslContext ctx, final BlockingQueue<MasterToken> queue, final MessageInputStream message) {
// Sanity check.
if (renewingContexts.get(ctx) != queue)
throw new IllegalStateException("Attempt to release renewal lock that is not owned by this queue.");
// If no message was received then deliver a null master token, release
// the lock, and return immediately.
if (message == null) {
queue.add(NULL_MASTER_TOKEN);
renewingContexts.remove(ctx);
return;
}
// If we received an error message then deliver a null master token,
// release the lock, and return immediately.
final MessageHeader messageHeader = message.getMessageHeader();
if (messageHeader == null) {
queue.add(NULL_MASTER_TOKEN);
renewingContexts.remove(ctx);
return;
}
// If we performed key exchange then the renewed master token should be
// delivered.
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null) {
queue.add(keyResponseData.getMasterToken());
}
// In trusted network mode deliver the header master token. This may be
// null.
else if (!ctx.isPeerToPeer()) {
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
queue.add(masterToken);
else
queue.add(NULL_MASTER_TOKEN);
}
// In peer-to-peer mode deliver the peer master token. This may be
// null.
else {
final MasterToken masterToken = messageHeader.getPeerMasterToken();
if (masterToken != null)
queue.add(masterToken);
else
queue.add(NULL_MASTER_TOKEN);
}
// Release the lock.
renewingContexts.remove(ctx);
}
/**
* Send an error response over the provided output stream.
*
* @param ctx MSL context.
* @param debugCtx message debug context.
* @param requestHeader message the error is being sent in response to. May
* be {@code null}.
* @param messageId request message ID. May be {@code null}.
* @param error the MSL error.
* @param userMessage localized user-consumable error message. May be
* {@code null}.
* @param out message output stream.
* @throws MslEncodingException if there is an error encoding the message.
* @throws MslCryptoException if there is an error encrypting or signing
* the message.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
* @throws MslMessageException if no entity authentication data was
* returned by the MSL context.
* @throws IOException if there is an error sending the error response.
*/
private void sendError(final MslContext ctx, final MessageDebugContext debugCtx, final MessageHeader requestHeader, final Long messageId, final MslError error, final String userMessage, final OutputStream out) throws MslEncodingException, MslCryptoException, MslEntityAuthException, MslMessageException, IOException {
// Create error header.
final ErrorHeader errorHeader = messageFactory.createErrorResponse(ctx, messageId, error, userMessage);
if (debugCtx != null) debugCtx.sentHeader(errorHeader);
// Determine encoder format.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MessageCapabilities capabilities = (requestHeader != null)
? MessageCapabilities.intersection(ctx.getMessageCapabilities(), requestHeader.getMessageCapabilities())
: ctx.getMessageCapabilities();
final Set<MslEncoderFormat> formats = (capabilities != null) ? capabilities.getEncoderFormats() : null;
final MslEncoderFormat format = encoder.getPreferredFormat(formats);
// Send error response.
final MessageOutputStream response = messageFactory.createOutputStream(ctx, out, errorHeader, format);
response.close();
}
/**
* <p>This service receives a request from a remote entity, and either
* returns the received message or automatically generates a reply (and
* returns null).</p>
*
* <p>This class will only be used by trusted-network servers and peer-to-
* peer servers.</p>
*/
private class ReceiveService implements Callable<MessageInputStream> {
/** MSL context. */
private final MslContext ctx;
/** Message context. */
private final MessageContext msgCtx;
/** Remote entity input stream. */
private final InputStream in;
/** Remote entity output stream. */
private final OutputStream out;
/** Read timeout in milliseconds. */
private final int timeout;
/**
* Create a new message receive service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param timeout renewal lock aquisition timeout in milliseconds.
*/
public ReceiveService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final int timeout) {
this.ctx = ctx;
this.msgCtx = msgCtx;
this.in = in;
this.out = out;
this.timeout = timeout;
}
/**
* @return the received message or {@code null} if cancelled.
* @throws MslException if there was an error with the received message
* or an error creating an automatically generated response.
* @throws MslErrorResponseException if there was an error sending an
* automatically generated error response.
* @throws IOException if there was an error reading or writing a
* message.
* @throws TimeoutException if the thread timed out while trying to
* acquire the renewal lock.
* @see java.util.concurrent.Callable#call()
*/
@Override
public MessageInputStream call() throws MslException, MslErrorResponseException, IOException, TimeoutException {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
// Read the incoming message.
final MessageInputStream request;
try {
request = receive(ctx, msgCtx, in, null);
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Try to send an error response.
try {
final MslError error = e.getError();
final String userMessage = messageRegistry.getUserMessage(error, null);
sendError(ctx, debugCtx, null, e.getMessageId(), error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error receiving the message header.", rt, e);
}
throw e;
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
sendError(ctx, debugCtx, null, null, MslError.MSL_COMMS_FAILURE, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error receiving the message header.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Try to send an error response.
try {
sendError(ctx, debugCtx, null, null, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error receiving the message header.", rt, t);
}
throw new MslInternalException("Error receiving the message header.", t);
}
// Return error headers to the caller.
final MessageHeader requestHeader = request.getMessageHeader();
if (requestHeader == null)
return request;
// If the message is not a handshake message deliver it to the
// caller.
try {
if (!request.isHandshake())
return request;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Try to send an error response.
try {
final MslError error = e.getError();
final String userMessage = messageRegistry.getUserMessage(error, null);
sendError(ctx, debugCtx, requestHeader, e.getMessageId(), error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error peeking into the message payloads.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Try to send an error response.
try {
final Long requestMessageId = requestHeader.getMessageId();
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error peeking into the message payloads.", rt, t);
}
throw new MslInternalException("Error peeking into the message payloads.", t);
}
// This is a handshake request so automatically return a response.
final MessageBuilder responseBuilder;
try {
// In peer-to-peer mode this will acquire the local entity's
// master token read lock.
responseBuilder = buildResponse(ctx, msgCtx, request.getMessageHeader());
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Try to send an error response.
try {
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, e.getMessageId(), error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error creating an automatic handshake response.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Try to send an error response.
try {
final Long requestMessageId = requestHeader.getMessageId();
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error creating an automatic handshake response.", rt, t);
}
throw new MslInternalException("Error creating an automatic handshake response.", t);
} finally {
try { request.close(); } catch (final IOException e) {}
}
// If we are in trusted services mode then no additional data is
// expected. Send the handshake response and return null. The next
// message from the remote entity can be retrieved by another call
// to receive.
final MessageContext keyxMsgCtx = new KeyxResponseMessageContext(msgCtx);
if (!ctx.isPeerToPeer()) {
try {
responseBuilder.setRenewable(false);
send(ctx, keyxMsgCtx, out, responseBuilder, false);
return null;
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Try to send an error response.
try {
final Long requestMessageId = requestHeader.getMessageId();
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, requestMessageId, error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending an automatic handshake response.", rt, e);
}
throw e;
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
final Long requestMessageId = requestHeader.getMessageId();
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.MSL_COMMS_FAILURE, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending an automatic handshake response.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Try to send an error response.
try {
final Long requestMessageId = requestHeader.getMessageId();
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending an automatic handshake response.", rt, t);
}
throw new MslInternalException("Error sending an automatic handshake response.", t);
}
}
// Since we are in peer-to-peer mode our response may contain key
// request data. Therefore we may receive another request after the
// remote entity's key exchange completes containing peer
// authentication tokens for the local entity.
//
// The master token lock acquired from buildResponse() will be
// released when the service executes.
//
// We have received one message.
final RequestService service = new RequestService(ctx, keyxMsgCtx, in, out, responseBuilder, timeout, 1);
final MslChannel channel = service.call();
// The MSL channel message output stream can be discarded since it
// only contained a handshake response.
if (channel != null)
return channel.input;
return null;
}
}
/**
* <p>This service sends a response to the remote entity.</p>
*
* <p>This class will only be used trusted network servers and peer-to-peer
* servers.</p>
*/
private class RespondService implements Callable<MslChannel> {
/** MSL context. */
protected final MslContext ctx;
/** Message context. */
protected final MessageContext msgCtx;
/** Request message input stream. */
protected final MessageInputStream request;
/** Remote entity input stream. */
protected final InputStream in;
/** Remote entity output stream. */
protected final OutputStream out;
/** Read timeout in milliseconds. */
protected final int timeout;
/**
* Create a new message respond service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param request request message input stream.
* @param timeout renewal lock acquisition timeout in milliseconds.
*/
public RespondService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageInputStream request, final int timeout) {
if (request.getErrorHeader() != null)
throw new MslInternalException("Respond service created for an error message.");
this.ctx = ctx;
this.msgCtx = msgCtx;
this.in = in;
this.out = out;
this.request = request;
this.timeout = timeout;
}
/**
* Send the response as a trusted network server.
*
* @param builder response message builder.
* @param msgCount number of messages that have already been sent or
* received.
* @return the MSL channel if the response was sent or null if
* cancelled, interrupted, if the response could not be sent
* encrypted or integrity protected when required, a user could
* not be attached due to lack of a master token, or if the
* maximum message count is hit.
* @throws MslException if there was an error creating the response.
* @throws MslErrorResponseException if there was an error sending an
* automatically generated error response.
* @throws IOException if there was an error writing the message.
* @throws InterruptedException if the thread is interrupted while
* trying to delete an old master token the sent message is
* replacing.
*/
protected MslChannel trustedNetworkExecute(final MessageBuilder builder, final int msgCount) throws MslException, MslErrorResponseException, IOException, InterruptedException {
try {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
final MessageHeader requestHeader = request.getMessageHeader();
// Do nothing if we cannot send one more message.
if (msgCount + 1 > MslConstants.MAX_MESSAGES)
return null;
// If the response must be encrypted or integrity protected but
// cannot then send an error requesting it. The client must re-
// initiate the transaction.
final MslError securityRequired;
if (msgCtx.isIntegrityProtected() && !builder.willIntegrityProtectPayloads())
securityRequired = MslError.RESPONSE_REQUIRES_INTEGRITY_PROTECTION;
else if (msgCtx.isEncrypted() && !builder.willEncryptPayloads())
securityRequired = MslError.RESPONSE_REQUIRES_ENCRYPTION;
else
securityRequired = null;
if (securityRequired != null) {
// Try to send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, securityRequired, null, out);
return null;
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Response requires encryption or integrity protection but cannot be protected: " + securityRequired, rt, null);
}
}
// If the response wishes to attach a user ID token but there is no
// master token then send an error requesting the master token. The
// client must re-initiate the transaction.
if (msgCtx.getUser() != null && builder.getMasterToken() == null && builder.getKeyExchangeData() == null) {
// Try to send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.RESPONSE_REQUIRES_MASTERTOKEN, null, out);
return null;
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Response wishes to attach a user ID token but there is no master token.", rt, null);
}
}
// Otherwise simply send the response.
builder.setRenewable(false);
final SendResult result = send(ctx, msgCtx, out, builder, false);
return new MslChannel(request, result.request);
} finally {
// Release the master token lock.
releaseMasterToken(ctx, builder.getMasterToken());
}
}
/**
* Send the response as a peer-to-peer entity.
*
* @param msgCtx message context.
* @param builder response message builder.
* @param msgCount number of messages sent or received so far.
* @return a MSL channel if the response was sent or null if cancelled,
* interrupted, or if the response could not be sent encrypted
* or integrity protected when required, a user could not be
* attached due to lack of a master token, or if the maximum
* message count is hit.
* @throws MslException if there was an error creating or processing a
* message.
* @throws MslErrorResponseException if there was an error sending an
* automatically generated error response.
* @throws IOException if there was an error writing the message.
* @throws InterruptedException if the thread is interrupted while
* trying to acquire the master token lock.
* @throws TimeoutException if the thread timed out while trying to
* acquire the renewal lock.
*/
protected MslChannel peerToPeerExecute(final MessageContext msgCtx, final MessageBuilder builder, int msgCount) throws MslException, IOException, InterruptedException, MslErrorResponseException, TimeoutException {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
final MessageHeader requestHeader = request.getMessageHeader();
// Do nothing if we cannot send and receive two more messages.
//
// Make sure to release the master token lock.
if (msgCount + 2 > MslConstants.MAX_MESSAGES) {
releaseMasterToken(ctx, builder.getMasterToken());
return null;
}
// If the response wishes to attach a user ID token but there is no
// master token then send an error requesting the master token. The
// client must re-initiate the transaction.
if (msgCtx.getUser() != null && builder.getPeerMasterToken() == null && builder.getKeyExchangeData() == null) {
// Release the master token lock and try to send an error
// response.
releaseMasterToken(ctx, builder.getMasterToken());
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.RESPONSE_REQUIRES_MASTERTOKEN, null, out);
return null;
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Response wishes to attach a user ID token but there is no master token.", rt, null);
}
}
// Send the response. A reply is not expected, but may be received.
// This adds two to our message count.
//
// This will release the master token lock.
final SendReceiveResult result = sendReceive(ctx, msgCtx, in, out, builder, Receive.RENEWING, false, timeout);
final MessageInputStream response = result.response;
msgCount += 2;
// If we did not receive a response then we're done. Return the
// original message input stream and the new message output stream.
if (response == null)
return new MslChannel(request, result.request);
// If the response is an error see if we can handle the error and
// retry.
final MessageHeader responseHeader = response.getMessageHeader();
if (responseHeader == null) {
// Close the response. We have everything we need.
try {
response.close();
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Otherwise we don't care about an exception on close.
}
// Build the error response. This will acquire the master token
// lock.
final ErrorHeader errorHeader = response.getErrorHeader();
final ErrorResult errMsg = buildErrorResponse(ctx, msgCtx, result, errorHeader);
// If there is no error response then return the error.
if (errMsg == null)
return null;
// Send the error response. Recursively execute this because it
// may take multiple messages to succeed with sending the
// response.
//
// The master token lock will be released by the recursive call
// to peerToPeerExecute().
final MessageBuilder requestBuilder = errMsg.builder;
final MessageContext resendMsgCtx = errMsg.msgCtx;
return peerToPeerExecute(resendMsgCtx, requestBuilder, msgCount);
}
// If we performed a handshake then re-send the message over the
// same connection so this time the application can send its data.
if (result.handshake) {
// Close the response as we are discarding it.
try {
response.close();
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Otherwise we don't care about an exception on close.
}
// This will acquire the local entity's master token read lock.
// The master token lock will be released by the recursive call
// to peerToPeerExecute().
final MessageContext resendMsgCtx = new ResendMessageContext(null, msgCtx);
final MessageBuilder requestBuilder = buildResponse(ctx, resendMsgCtx, responseHeader);
return peerToPeerExecute(resendMsgCtx, requestBuilder, msgCount);
}
// Otherwise we did send our application data (which may have been
// zero-length) so we do not need to re-send our message. Return
// the new message input stream and the new message output stream.
return new MslChannel(result.response, result.request);
}
/**
* @return a {@link MslChannel} on success or {@code null} if cancelled,
* interrupted, if an error response was received (peer-to-peer
* mode only), if the response could not be sent encrypted or
* integrity protected when required (trusted network-mode
* only), or if the maximum number of messages is hit.
* @throws MslException if there was an error creating the response.
* @throws MslErrorResponseException if there was an error sending an
* automatically generated error response.
* @throws IOException if there was an error writing the message.
* @see java.util.concurrent.Callable#call()
*/
@Override
public MslChannel call() throws MslException, MslErrorResponseException, IOException {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
final MessageHeader requestHeader = request.getMessageHeader();
final MessageBuilder builder;
try {
// In peer-to-peer mode this will acquire the local entity's
// master token read lock.
builder = buildResponse(ctx, msgCtx, requestHeader);
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
try {
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, e.getMessageId(), error, userMessage, out);
} catch (final Throwable rt) {
throw new MslErrorResponseException("Error building the response.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
try {
sendError(ctx, debugCtx, requestHeader, null, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
throw new MslErrorResponseException("Error building the response.", rt, t);
}
throw new MslInternalException("Error building the response.", t);
}
// At most three messages would have been involved in the original
// receive.
try {
// Send the response. This will release the master token lock.
final MslChannel channel;
if (!ctx.isPeerToPeer())
channel = trustedNetworkExecute(builder, 3);
else
channel = peerToPeerExecute(msgCtx, builder, 3);
// Clear any cached payloads.
if (channel != null)
channel.output.stopCaching();
// Return the established channel.
return channel;
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.MSL_COMMS_FAILURE, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending the response.", rt, e);
}
throw e;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, requestMessageId, error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending the response.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending the response.", rt, t);
}
throw new MslInternalException("Error sending the response.", t);
}
}
}
/**
* <p>This service sends an error response to the remote entity.</p>
*
* <p>This class will only be used trusted network servers and peer-to-peer
* entities.</p>
*/
private class ErrorService implements Callable<Boolean> {
/** MSL context. */
private final MslContext ctx;
/** Message context. */
private final MessageContext msgCtx;
/** Application error. */
private final ApplicationError appError;
/** Request message input stream. */
private final MessageInputStream request;
/** Remote entity output stream. */
private final OutputStream out;
/**
* Create a new error service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param err the application error.
* @param out remote entity output stream.
* @param request request message input stream.
*/
public ErrorService(final MslContext ctx, final MessageContext msgCtx, final ApplicationError err, final OutputStream out, final MessageInputStream request) {
if (request.getErrorHeader() != null)
throw new MslInternalException("Error service created for an error message.");
this.ctx = ctx;
this.msgCtx = msgCtx;
this.appError = err;
this.out = out;
this.request = request;
}
/**
* @return true on success or false if cancelled or interrupted.
* @throws MslException if there was an error creating the response.
* @throws IOException if there was an error writing the message.
* @see java.util.concurrent.Callable#call()
*/
@Override
public Boolean call() throws MslException {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
final MessageHeader header = request.getMessageHeader();
try {
// Identify the correct MSL error.
final MslError error;
switch (appError) {
case ENTITY_REJECTED:
error = (header.getMasterToken() != null)
? MslError.MASTERTOKEN_REJECTED_BY_APP
: MslError.ENTITY_REJECTED_BY_APP;
break;
case USER_REJECTED:
error = (header.getUserIdToken() != null)
? MslError.USERIDTOKEN_REJECTED_BY_APP
: MslError.USER_REJECTED_BY_APP;
break;
default:
throw new MslInternalException("Unhandled application error " + appError + ".");
}
// Build and send the error response.
final MessageCapabilities caps = header.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, header, header.getMessageId(), error, userMessage, out);
// Success.
return Boolean.TRUE;
} catch (final MslException e) {
// If we were cancelled then return false.
if (cancelled(e)) return false;
// We failed to return an error response. Deliver the exception
// to the application.
throw e;
} catch (final Throwable t) {
// If we were cancelled then return false.
if (cancelled(t)) return false;
// An unexpected exception occurred.
throw new MslInternalException("Error building the error response.", t);
}
}
}
/**
* <p>This service sends a request to the remote entity and returns the
* response.</p>
*
* <p>This class will only be used by trusted network clients, peer-to-peer
* clients, and peer-to-peer servers.</p>
*/
private class RequestService implements Callable<MslChannel> {
/** MSL context. */
private final MslContext ctx;
/** Message context. */
private final MessageContext msgCtx;
/** Remote entity URL. */
private final Url remoteEntity;
/** Remote entity input stream. */
private InputStream in;
/** Remote entity output stream. */
private OutputStream out;
/** True if we opened the streams. */
private boolean openedStreams;
/** Request message builder. */
private MessageBuilder builder;
/** Response expectation. */
private final Receive expectResponse;
/** Connect and read timeout in milliseconds. */
private final int timeout;
/** Number of messages sent or received so far. */
private final int msgCount;
/** True if the maximum message count is hit. */
private boolean maxMessagesHit = false;
/**
* Create a new message request service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param remoteEntity remote entity URL.
* @param expectResponse response expectation.
* @param timeout connect, read, and renewal lock acquisition timeout
* in milliseconds.
*/
public RequestService(final MslContext ctx, final MessageContext msgCtx, final Url remoteEntity, final Receive expectResponse, final int timeout) {
this.ctx = ctx;
this.msgCtx = msgCtx;
this.remoteEntity = remoteEntity;
this.in = null;
this.out = null;
this.openedStreams = false;
this.builder = null;
this.expectResponse = expectResponse;
this.timeout = timeout;
this.msgCount = 0;
}
/**
* Create a new message request service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param expectResponse response expectation.
* @param timeout read and renewal lock acquisition timeout in
* milliseconds.
*/
public RequestService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final Receive expectResponse, final int timeout) {
this.ctx = ctx;
this.msgCtx = msgCtx;
this.remoteEntity = null;
this.in = in;
this.out = out;
this.openedStreams = false;
this.builder = null;
this.expectResponse = expectResponse;
this.timeout = timeout;
this.msgCount = 0;
}
/**
* Create a new message request service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param remoteEntity remote entity URL.
* @param builder request message builder.
* @param expectResponse response expectation.
* @param timeout connect, read, and renewal lock acquisition timeout
* in milliseconds.
* @param msgCount number of messages that have already been sent or
* received.
*/
private RequestService(final MslContext ctx, final MessageContext msgCtx, final Url remoteEntity, final MessageBuilder builder, final Receive expectResponse, final int timeout, final int msgCount) {
this.ctx = ctx;
this.msgCtx = msgCtx;
this.remoteEntity = remoteEntity;
this.in = null;
this.out = null;
this.openedStreams = false;
this.builder = builder;
this.expectResponse = expectResponse;
this.timeout = timeout;
this.msgCount = msgCount;
}
/**
* Create a new message request service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param builder request message builder.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @param msgCount number of messages that have already been sent or
* received.
*/
public RequestService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageBuilder builder, final int timeout, final int msgCount) {
this.ctx = ctx;
this.msgCtx = msgCtx;
this.remoteEntity = null;
this.in = in;
this.out = out;
this.openedStreams = false;
this.builder = builder;
this.expectResponse = Receive.ALWAYS;
this.timeout = timeout;
this.msgCount = msgCount;
}
/**
* <p>Send the provided request and receive a response from the remote
* entity. Any necessary handshake messages will be sent.</p>
*
* <p>If an error was received and cannot be handled the returned MSL
* channel will have {@code null} for its message output stream.</p>
*
* @param msgCtx message context.
* @param builder request message builder.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @param msgCount number of messages sent or received so far.
* @return the established MSL channel or {@code null} if cancelled or
* if the maximum message count is hit.
* @throws MslException if there was an error creating or processing
* a message.
* @throws IOException if there was an error reading or writing a
* message.
* @throws InterruptedException if the thread is interrupted while
* trying to acquire a master token's read lock.
* @throws TimeoutException if the thread timed out while trying to
* acquire the renewal lock.
*/
private MslChannel execute(final MessageContext msgCtx, final MessageBuilder builder, final int timeout, int msgCount) throws MslException, IOException, InterruptedException, TimeoutException {
// Do not do anything if cannot send and receive two more messages.
//
// Make sure to release the master token lock.
if (msgCount + 2 > MslConstants.MAX_MESSAGES) {
releaseMasterToken(ctx, builder.getMasterToken());
maxMessagesHit = true;
return null;
}
// Send the request and receive the response. This adds two to our
// message count.
//
// This will release the master token lock.
final SendReceiveResult result = sendReceive(ctx, msgCtx, in, out, builder, expectResponse, openedStreams, timeout);
final MessageOutputStream request = result.request;
final MessageInputStream response = result.response;
msgCount += 2;
// If we did not receive a response then we're done. Return the
// new message output stream.
if (response == null)
return new MslChannel(response, request);
// If the response is an error see if we can handle the error and
// retry.
final MessageHeader responseHeader = response.getMessageHeader();
if (responseHeader == null) {
// Close the request and response. The response is an error and
// the request is not usable.
try {
request.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
try {
response.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
// Build the error response. This will acquire the master token
// lock.
final ErrorHeader errorHeader = response.getErrorHeader();
final ErrorResult errMsg = buildErrorResponse(ctx, msgCtx, result, errorHeader);
// If there is no error response then return the error.
if (errMsg == null)
return new MslChannel(response, null);
// In trusted network mode send the response in a new request.
// In peer-to-peer mode reuse the connection.
final MslChannel newChannel;
final MessageBuilder requestBuilder = errMsg.builder;
final MessageContext resendMsgCtx = errMsg.msgCtx;
if (!ctx.isPeerToPeer()) {
// The master token lock acquired from buildErrorResponse()
// will be released when the service executes.
final RequestService service = new RequestService(ctx, resendMsgCtx, remoteEntity, requestBuilder, expectResponse, timeout, msgCount);
newChannel = service.call();
maxMessagesHit = service.maxMessagesHit;
} else {
// Send the error response. Recursively execute this
// because it may take multiple messages to succeed with
// sending the request.
//
// The master token lock will be released by the recursive
// call to execute().
newChannel = execute(resendMsgCtx, requestBuilder, timeout, msgCount);
}
// If the maximum message count was hit or if there is no new
// response then return the original error response.
if (maxMessagesHit || (newChannel != null && newChannel.input == null))
return new MslChannel(response, null);
// Return the new channel, which may contain an error or be
// null if cancelled or interrupted.
return newChannel;
}
// If we are in trusted network mode...
if (!ctx.isPeerToPeer()) {
// If we did not perform a handshake then we're done. Deliver
// the response.
if (!result.handshake)
return new MslChannel(response, request);
// We did perform a handshake. Re-send the message over a new
// connection to allow the application to send its data.
//
// Close the request and response. The response will be
// discarded and we will be issuing a new request.
try {
request.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
try {
response.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
// The master token lock acquired from buildResponse() will be
// released when the service executes.
final MessageContext resendMsgCtx = new ResendMessageContext(null, msgCtx);
final MessageBuilder requestBuilder = buildResponse(ctx, msgCtx, responseHeader);
final RequestService service = new RequestService(ctx, resendMsgCtx, remoteEntity, requestBuilder, expectResponse, timeout, msgCount);
return service.call();
}
// We are in peer-to-peer mode...
//
// If we did perform a handshake. Re-send the message over the same
// connection to allow the application to send its data. This may
// also return key response data.
if (result.handshake) {
// Close the request and response. The response will be
// discarded and we will be issuing a new request.
try {
request.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
try {
response.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
// Now resend.
//
// The master token lock acquired from buildResponse() will be
// released by the recursive call to execute().
final MessageContext resendMsgCtx = new ResendMessageContext(null, msgCtx);
final MessageBuilder requestBuilder = buildResponse(ctx, msgCtx, responseHeader);
return execute(resendMsgCtx, requestBuilder, timeout, msgCount);
}
// Otherwise we did send our application data (which may have been
// zero-length) so we do not need to re-send our message.
//
// If the response contains key request data, or is renewable and
// contains a master token and user authentication data, then we
// need to return a response to perform key exchange and/or provide
// a user ID token.
final Set<KeyRequestData> responseKeyxData = responseHeader.getKeyRequestData();
if (!responseKeyxData.isEmpty() ||
(responseHeader.isRenewable() && responseHeader.getMasterToken() != null && responseHeader.getUserAuthenticationData() != null))
{
// Build the response. This will acquire the master token lock.
final MessageContext keyxMsgCtx = new KeyxResponseMessageContext(msgCtx);
final MessageBuilder keyxBuilder = buildResponse(ctx, keyxMsgCtx, responseHeader);
// We should release the master token lock when finished, but
// there is one case where we should not.
boolean releaseLock = true;
try {
// If the response is not a handshake message then we do not
// expect a reply.
if (!response.isHandshake()) {
// Close the request as we are issuing a new request.
try {
request.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
// The remote entity is expecting a response. We need
// to send it even if this exceeds the maximum number of
// messages. We're guaranteed to stop sending more
// messages after this response.
//
// Return the original message input stream and the new
// message output stream to the caller.
keyxBuilder.setRenewable(false);
final SendResult newResult = send(ctx, keyxMsgCtx, out, keyxBuilder, openedStreams);
return new MslChannel(response, newResult.request);
}
// Otherwise the remote entity may still have to send us the
// application data in a reply.
else {
// Close the request and response. The response will be
// discarded and we will be issuing a new request.
try {
request.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
try {
response.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
// The master token lock acquired from buildResponse() will be
// released by the recursive call to execute().
releaseLock = false;
return execute(keyxMsgCtx, keyxBuilder, timeout, msgCount);
}
} finally {
// Release the master token read lock if necessary.
if (releaseLock)
releaseMasterToken(ctx, keyxBuilder.getMasterToken());
}
}
// Return the established MSL channel to the caller.
return new MslChannel(response, request);
}
/**
* @return the established MSL channel or {@code null} if cancelled or
* interrupted.
* @throws MslException if there was an error creating or processing
* a message.
* @throws IOException if there was an error reading or writing a
* message.
* @throws TimeoutException if the thread timed out while trying to
* acquire the renewal lock.
* @see java.util.concurrent.Callable#call()
*/
@Override
public MslChannel call() throws MslException, IOException, TimeoutException {
// If we do not already have a connection then establish one.
final int lockTimeout;
if (in == null || out == null) {
try {
// Set up the connection.
remoteEntity.setTimeout(timeout);
// Connect. Keep track of how much time this takes to subtract
// that from the lock timeout timeout.
final long start = System.currentTimeMillis();
final Connection conn = remoteEntity.openConnection();
out = conn.getOutputStream();
in = conn.getInputStream();
lockTimeout = timeout - (int)(System.currentTimeMillis() - start);
openedStreams = true;
} catch (final IOException e) {
// If a message builder was provided then release the
// master token read lock.
if (builder != null)
releaseMasterToken(ctx, builder.getMasterToken());
// Close any open streams.
// We don't care about an I/O exception on close.
if (out != null) try { out.close(); } catch (final IOException ioe) { }
if (in != null) try { in.close(); } catch (final IOException ioe) { }
// If we were cancelled then return null.
if (cancelled(e)) return null;
throw e;
} catch (final RuntimeException e) {
// If a message builder was provided then release the
// master token read lock.
if (builder != null)
releaseMasterToken(ctx, builder.getMasterToken());
// Close any open streams.
// We don't care about an I/O exception on close.
if (out != null) try { out.close(); } catch (final IOException ioe) { }
if (in != null) try { in.close(); } catch (final IOException ioe) { }
throw e;
}
} else {
lockTimeout = timeout;
}
// If no builder was provided then build a new request. This will
// acquire the master token lock.
if (builder == null) {
try {
builder = buildRequest(ctx, msgCtx);
} catch (final InterruptedException e) {
// Close the streams if we opened them.
// We don't care about an I/O exception on close.
if (openedStreams) {
try { out.close(); } catch (final IOException ioe) { }
try { in.close(); } catch (final IOException ioe) { }
}
// We were cancelled so return null.
return null;
}
}
try {
// Execute. This will release the master token lock.
final MslChannel channel = execute(msgCtx, builder, lockTimeout, msgCount);
// If the channel was established clear the cached payloads.
if (channel != null && channel.output != null)
channel.output.stopCaching();
// Close the input stream if we opened it and there is no
// response. This may be necessary to transmit data
// buffered in the output stream, and the caller will not
// be given a message input stream by which to close it.
//
// We don't care about an I/O exception on close.
if (openedStreams && (channel == null || channel.input == null))
try { in.close(); } catch (final IOException ioe) { }
// Return the established channel.
return channel;
} catch (final InterruptedException e) {
// Close the streams if we opened them.
// We don't care about an I/O exception on close.
if (openedStreams) {
try { out.close(); } catch (final IOException ioe) { }
try { in.close(); } catch (final IOException ioe) { }
}
// We were cancelled so return null.
return null;
} catch (final MslException | IOException | RuntimeException | TimeoutException e) {
// Close the streams if we opened them.
// We don't care about an I/O exception on close.
if (openedStreams) {
try { out.close(); } catch (final IOException ioe) { }
try { in.close(); } catch (final IOException ioe) { }
}
// If we were cancelled then return null.
if (cancelled(e)) return null;
throw e;
}
}
}
/**
* <p>This service sends a message to a remote entity.</p>
*
* <p>This class is only used from trusted network clients and peer-to-peer
* entities.</p>
*/
private class SendService implements Callable<MessageOutputStream> {
/** The request service. */
private final RequestService requestService;
/**
* Create a new message send service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param remoteEntity remote entity URL.
* @param timeout connect, read, and renewal lock acquisition timeout
* in milliseconds.
*/
public SendService(final MslContext ctx, final MessageContext msgCtx, final Url remoteEntity, final int timeout) {
this.requestService = new RequestService(ctx, msgCtx, remoteEntity, Receive.NEVER, timeout);
}
/**
* Create a new message send service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param timeout read and renewal lock acquisition timeout in
* milliseconds.
*/
public SendService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final int timeout) {
this.requestService = new RequestService(ctx, msgCtx, in, out, Receive.NEVER, timeout);
}
/**
* @return the established MSL channel or {@code null} if cancelled or
* interrupted.
* @throws MslException if there was an error creating or processing
* a message.
* @throws IOException if there was an error reading or writing a
* message.
* @throws TimeoutException if the thread timed out while trying to
* acquire the renewal lock.
* @see java.util.concurrent.Callable#call()
*/
@Override
public MessageOutputStream call() throws MslException, IOException, TimeoutException {
final MslChannel channel = this.requestService.call();
return (channel != null) ? channel.output : null;
}
}
/**
* <p>This service sends a message to the remote entity using a request as
* the basis for the response.</p>
*
* <p>This class will only be used trusted network servers.</p>
*/
public class PushService extends RespondService {
/**
* Create a new message push service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param request request message input stream.
* @param timeout renewal lock acquisition timeout in milliseconds.
*/
public PushService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageInputStream request, final int timeout) {
super(ctx, msgCtx, in, out, request, timeout);
}
/**
* @return a {@link MslChannel} on success or {@code null} if cancelled,
* interrupted, if the response could not be sent encrypted or
* integrity protected when required, or if the maximum number
* of messages is hit.
* @throws MslException if there was an error creating the response.
* @throws MslErrorResponseException if there was an error sending an
* automatically generated error response.
* @throws IOException if there was an error writing the message.
* @see java.util.concurrent.Callable#call()
*/
@Override
public MslChannel call() throws MslException, MslErrorResponseException, IOException {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
final MessageHeader requestHeader = request.getMessageHeader();
final MessageBuilder builder;
try {
builder = buildDetachedResponse(ctx, msgCtx, requestHeader);
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
try {
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, e.getMessageId(), error, userMessage, out);
} catch (final Throwable rt) {
throw new MslErrorResponseException("Error building the message.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
try {
sendError(ctx, debugCtx, requestHeader, null, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
throw new MslErrorResponseException("Error building the message.", rt, t);
}
throw new MslInternalException("Error building the message.", t);
}
try {
// Send the message. This will release the master token lock.
final MslChannel channel = trustedNetworkExecute(builder, 0);
// Clear any cached payloads.
if (channel != null)
channel.output.stopCaching();
// Return the established channel.
return channel;
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.MSL_COMMS_FAILURE, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error pushing the message.", rt, e);
}
throw e;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, requestMessageId, error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error pushing the message.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error pushing the message.", rt, t);
}
throw new MslInternalException("Error pushing the message.", t);
}
}
}
/**
* <p>Send a message to the entity at the provided URL.</p>
*
* <p>Use of this method is not recommended as it does not confirm delivery
* or acceptance of the message. Establishing a MSL channel to send
* application data without requiring the remote entity to acknowledge
* receipt in the response application data is the recommended approach.
* Only use this method if guaranteed receipt is not required.</p>
*
* <p>This method should only be used by trusted network clients and per-
* to-peer entities when no response is expected from the remote entity.
* The remote entity should be using
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}
* and should not attempt to send a response.</p>
*
* <p>The returned {@code Future} will return a {@code MessageOutputStream}
* containing the final {@code MessageOutputStream} that should be used to
* send any additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)}.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) cancelled or interrupted}, if an error
* response was received resulting in a failure to send the message, or if
* the maximum number of messages is hit without sending the message.</p>
*
* <p>The {@code Future} may throw an {@code ExecutionException} whose
* cause is a {@code MslException}, {@code IOException}, or
* {@code TimeoutException}.</p>
*
* <p>The caller must close the returned message output stream.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param remoteEntity remote entity URL.
* @param timeout connect, read, and renewal lock acquisition timeout in
* milliseconds.
* @return a future for the message output stream.
*/
public Future<MessageOutputStream> send(final MslContext ctx, final MessageContext msgCtx, final Url remoteEntity, final int timeout) {
final MessageContext sendMsgCtx = new SendMessageContext(msgCtx);
final SendService service = new SendService(ctx, sendMsgCtx, remoteEntity, timeout);
return executor.submit(service);
}
/**
* <p>Send a message over the provided output stream.</p>
*
* <p>Use of this method is not recommended as it does not confirm delivery
* or acceptance of the message. Establishing a MSL channel to send
* application data without requiring the remote entity to acknowledge
* receipt in the response application data is the recommended approach.
* Only use this method if guaranteed receipt is not required.</p>
*
* <p>This method should only be used by trusted network clients and peer-
* to-peer entities when no response is expected from the remote entity.
* The remote entity should be using
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}
* and should not attempt to send a response.</p>
*
* <p>The returned {@code Future} will return a {@code MessageOutputStream}
* containing the final {@code MessageOutputStream} that should be used to
* send any additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)}.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) cancelled or interrupted}, if an error
* response was received resulting in a failure to send the message, or if
* the maximum number of messages is hit without sending the message.</p>
*
* <p>The {@code Future} may throw an {@code ExecutionException} whose
* cause is a {@code MslException}, {@code IOException}, or
* {@code TimeoutException}.</p>
*
* <p>The caller must close the returned message output stream. The remote
* entity output stream will not be closed when the message output stream
* is closed, in case the caller wishes to reuse them.</p>
*
* TODO once Java supports the WebSocket protocol we can remove this method
* in favor of the one accepting a URL parameter. (Or is it the other way
* around?)
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param timeout connect, read, and renewal lock acquisition timeout in
* milliseconds.
* @return a future for the message output stream.
*/
public Future<MessageOutputStream> send(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final int timeout) {
final MessageContext sendMsgCtx = new SendMessageContext(msgCtx);
final SendService service = new SendService(ctx, sendMsgCtx, in, out, timeout);
return executor.submit(service);
}
/**
* <p>Push a message over the provided output stream based on a message
* received from the remote entity.</p>
*
* <p>Use of this method is not recommended as it does not perform master
* token or user ID token issuance or renewal which the remote entity may
* be attempting to perform. Only use this method if there is some other
* means by which the client will be able to acquire and renew its master
* token or user ID token on a regular basis.</p>
*
* <p>This method should only be used by trusted network servers that wish
* to send multiple responses to a trusted network client. The remote
* entity should be using
* {@link #send(MslContext, MessageContext, Url, int)} or
* {@link #send(MslContext, MessageContext, InputStream, OutputStream, int)}
* and
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}.</p>
*
* <p>This method must not be used if
* {@link MslControl#respond(MslContext, MessageContext, InputStream, OutputStream, MessageInputStream, int)}
* has already been used with the same {@code MessageInputStream}.</p>
*
* <p>The returned {@code Future} will return a {@code MslChannel}
* containing the same {@code MessageInputStream} that was provided and the
* final {@code MessageOutputStream} that should be used to send any
* additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)} to the remote
* entity.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) canncelled or interrupted}, if the message
* could not be sent with encryption or integrity protection when required,
* if a user cannot be attached to the respond to the response due to lack
* of a master token, or if the maximum number of messages is hit without
* sending the message. In these cases the local entity should wait for a
* new message from the remote entity to be received by a call to
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}
* before attempting to push another message.</p>
*
* <p>The {@code Future} may throw an {@code ExecutionException} whose
* cause is a {@code MslException}, {@code MslErrorResponseException},
* {@code IOException}, or {@code TimeoutException}.</p>
*
* <p>The remote entity input and output streams will not be closed in case
* the caller wishes to reuse them.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param request message input stream used to create the message.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @return a future for the communication channel.
* @throws IllegalStateException if used in peer-to-peer mode.
* @throws IllegalArgumentException if the request message input stream is
* an error message.
*/
public Future<MslChannel> push(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageInputStream request, final int timeout) {
if (ctx.isPeerToPeer())
throw new IllegalStateException("This method cannot be used in peer-to-peer mode.");
if (request.getErrorHeader() != null)
throw new IllegalArgumentException("Request message input stream cannot be for an error message.");
final PushService service = new PushService(ctx, msgCtx, in, out, request, timeout);
return executor.submit(service);
}
/**
* <p>Receive a request over the provided input stream.</p>
*
* <p>If there is an error with the message an error response will be sent
* over the provided output stream.</p>
*
* <p>This method should only be used to receive a request initiated by the
* remote entity. The remote entity should have used one of the request
* methods
* {@link #request(MslContext, MessageContext, Url, int)} or
* {@link #request(MslContext, MessageContext, InputStream, OutputStream, int)}
* or one of the send methods
* {@link #send(MslContext, MessageContext, Url, int)} or
* {@link #send(MslContext, MessageContext, InputStream, OutputStream, int)}.<p>
*
* <p>The returned {@code Future} will return the received
* {@code MessageInputStream} on completion or {@code null} if a reply was
* automatically sent (for example in response to a handshake request) or
* if the operation was
* {@link #cancelled(Throwable) cancelled or interrupted}. The returned
* message may be an error message if the maximum number of messages is hit
* without successfully receiving the final message. The {@code Future} may
* throw an {@code ExecutionException} whose cause is a
* {@code MslException}, {@code MslErrorResponseException},
* {@code IOException}, or {@code TimeoutException}.</p>
*
* <p>The remote entity input and output streams will not be closed in case
* the caller wishes to reuse them.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param timeout renewal acquisition lock timeout in milliseconds.
* @return a future for the message.
*/
public Future<MessageInputStream> receive(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final int timeout) {
final ReceiveService service = new ReceiveService(ctx, msgCtx, in, out, timeout);
return executor.submit(service);
}
/**
* <p>Send a response over the provided output stream.</p>
*
* <p>This method should only be used by trusted network servers and peer-
* to-peer entities after receiving a request via
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}.
* The remote entity should have used one of the request methods
* {@link #request(MslContext, MessageContext, Url, int)} or
* {@link #request(MslContext, MessageContext, InputStream, OutputStream, int)}.</p>
*
* <p>The returned {@code Future} will return a {@code MslChannel}
* containing the final {@code MessageOutputStream} that should be used to
* send any additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)} to the remote entity,
* and in peer-to-peer mode may also contain a {@code MessageInputStream}
* as described below.</p>
*
* <p>In peer-to-peer mode a new {@code MessageInputStream} may be returned
* which should be used in place of the previous {@code MessageInputStream}
* being responded to. This will only occur if the initial response sent
* could not include application data and was instead a handshake message.
* The new {@code MessageInputStream} will not include any application data
* already read off of the previous {@code MessageInputStream}; it will
* only contain new application data that is a continuation of the previous
* message's application data.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) cancelled or interrupted}, if an error
* response was received (peer-to-peer only) resulting in a failure to
* establish the communication channel, if the response could not be sent
* with encryption or integrity protection when required (trusted network-
* mode only), if a user cannot be attached to the response due to lack of
* a master token, or if the maximum number of messages is hit without
* sending the message. In these cases the remote entity's next message can
* be received by another call to
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}.</p>
*
* <p>The {@code Future} may throw an {@code ExecutionException} whose
* cause is a {@code MslException}, {@code MslErrorResponseException},
* {@code IOException}, or {@code TimeoutException}.</p>
*
* <p>The remote entity input and output streams will not be closed in case
* the caller wishes to reuse them.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param request message input stream to create the response for.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @return a future for the communication channel.
* @throws IllegalArgumentException if the request message input stream is
* an error message.
*/
public Future<MslChannel> respond(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageInputStream request, final int timeout) {
if (request.getErrorHeader() != null)
throw new IllegalArgumentException("Request message input stream cannot be for an error message.");
final RespondService service = new RespondService(ctx, msgCtx, in, out, request, timeout);
return executor.submit(service);
}
/**
* <p>Send an error response over the provided output stream. Any replies
* to the error response may be received by a subsequent call to
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}.</p>
*
* <p>This method should only be used by trusted network servers and peer-
* to-peer entities after receiving a request via
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}.
* The remote entity should have used
* {@link #request(MslContext, MessageContext, Url, int)}.</p>
*
* <p>The returned {@code Future} will return true on success or false if
* {@link #cancelled(Throwable) cancelled or interrupted}. The
* {@code Future} may throw an {@code ExecutionException} whose cause is a
* {@code MslException} or {@code IOException}.</p>
*
* <p>The remote entity input and output streams will not be closed in case
* the caller wishes to reuse them.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param err error type.
* @param out remote entity output stream.
* @param request request input srtream to create the response for.
* @return a future for the operation.
* @throws IllegalArgumentException if the request message input stream is
* an error message.
*/
public Future<Boolean> error(final MslContext ctx, final MessageContext msgCtx, final ApplicationError err, final OutputStream out, final MessageInputStream request) {
if (request.getErrorHeader() != null)
throw new IllegalArgumentException("Request message input stream cannot be for an error message.");
final ErrorService service = new ErrorService(ctx, msgCtx, err, out, request);
return executor.submit(service);
}
/**
* <p>Send a request to the entity at the provided URL.</p>
*
* <p>This method should only be used by trusted network clients when
* initiating a new request. The remote entity should be using
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}
* and
* {@link #respond(MslContext, MessageContext, InputStream, OutputStream, MessageInputStream, int)}.</p>
*
* <p>The returned {@code Future} will return a {@code MslChannel}
* containing the final {@code MessageOutputStream} that should be used to
* send any additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)} and the
* {@code MessageInputStream} of the established MSL communication
* channel. If an error message was received then the MSL channel's message
* output stream will be {@code null}.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) cancelled or interrupted}. The returned
* message may be an error message if the maximum number of messages is hit
* without successfully sending the request and receiving the response. The
* {@code Future} may throw an {@code ExecutionException} whose cause is a
* {@code MslException}, {@code IOException}, or
* {@code TimeoutException}.</p>
*
* <p>The caller must close the returned message input stream and message
* outut stream.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param remoteEntity remote entity URL.
* @param timeout connect, read, and renewal lock acquisition timeout in
* milliseconds.
* @return a future for the communication channel.
* @throws IllegalStateException if used in peer-to-peer mode.
*/
public Future<MslChannel> request(final MslContext ctx, final MessageContext msgCtx, final Url remoteEntity, final int timeout) {
if (ctx.isPeerToPeer())
throw new IllegalStateException("This method cannot be used in peer-to-peer mode.");
final RequestService service = new RequestService(ctx, msgCtx, remoteEntity, Receive.ALWAYS, timeout);
return executor.submit(service);
}
/**
* <p>Send a request to the remote entity over the provided output stream
* and receive a resposne over the provided input stream.</p>
*
* <p>This method should only be used by peer-to-peer entities when
* initiating a new request. The remote entity should be using
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}
* and
* {@link #respond(MslContext, MessageContext, InputStream, OutputStream, MessageInputStream, int)}.</p>
*
* <p>The returned {@code Future} will return a {@code MslChannel}
* containing the final {@code MessageOutputStream} that should be used to
* send any additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)} and the
* {@code MessageInputStream} of the established MSL communication
* channel. If an error message was received then the MSL channel's message
* output stream will be {@code null}.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) cancelled or interrupted}. The returned
* message may be an error message if the maximum number of messages is hit
* without successfully sending the request and receiving the response. The
* {@code Future} may throw an {@code ExecutionException} whose cause is a
* {@code MslException}, {@code IOException}, or
* {@code TimeoutException}.</p>
*
* <p>The caller must close the returned message input stream and message
* outut stream. The remote entity input and output streams will not be
* closed when the message input and output streams are closed, in case the
* caller wishes to reuse them.</p>
*
* TODO once Java supports the WebSocket protocol we can remove this method
* in favor of the one accepting a URL parameter. (Or is it the other way
* around?)
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @return a future for the communication channel.
* @throws IllegalStateException if used in trusted network mode.
*/
public Future<MslChannel> request(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final int timeout) {
if (!ctx.isPeerToPeer())
throw new IllegalStateException("This method cannot be used in trusted network mode.");
final RequestService service = new RequestService(ctx, msgCtx, in, out, Receive.ALWAYS, timeout);
return executor.submit(service);
}
/** MSL executor. */
private final ExecutorService executor;
/** Message factory. */
private final MessageFactory messageFactory;
/** Error message registry. */
private final ErrorMessageRegistry messageRegistry;
/** Filter stream factory. May be null. */
private FilterStreamFactory filterFactory = null;
/**
* Map tracking outstanding renewable messages by MSL context. The blocking
* queue is used to wait for a master token from a different thread if the
* message requires one.
*/
private final ConcurrentHashMap<MslContext,BlockingQueue<MasterToken>> renewingContexts = new ConcurrentHashMap<MslContext,BlockingQueue<MasterToken>>();
/** Dummy master token used to release the renewal lock. */
private final MasterToken NULL_MASTER_TOKEN;
/**
* Map of in-flight master token read-write locks by MSL context and master
* token.
*/
private final ConcurrentHashMap<MslContextMasterTokenKey,ReadWriteLock> masterTokenLocks = new ConcurrentHashMap<MslContextMasterTokenKey,ReadWriteLock>();
}
| 1,712 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageCapabilities.java
|
/**
* Copyright (c) 2013-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.msg;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.io.MslArray;
import com.netflix.msl.io.MslEncodable;
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>The message capabilities identify the features supported by the message
* sender.</p>
*
* <p>The message capabilities are represented as
* {@code
* capabilities = {
* "compressionalgos" : [ enum(GZIP|LZW) ],
* "languages" : [ "string" ],
* "encoderformats" : [ "string" ],
* }} where:
* <ul>
* <li>{@code compressionalgos} is the set of supported compression algorithms</li>
* <li>{@code languages} is the preferred list of BCP-47 languages in descending order</li>
* <li>{@code encoderformats} is the preferred list of MSL encoder formats in descending order</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MessageCapabilities implements MslEncodable {
/** Key compression algorithms. */
private static final String KEY_COMPRESSION_ALGOS = "compressionalgos";
/** Key languages. */
private static final String KEY_LANGUAGES = "languages";
/** Key encoder formats. */
private static final String KEY_ENCODER_FORMATS = "encoderformats";
/**
* Computes and returns the intersection of two message capabilities.
*
* @param mc1 first message capabilities. May be {@code null}.
* @param mc2 second message capabilities. May be {@code null}.
* @return the intersection of message capabilities or {@code null} if one
* of the message capabilities is {@code null}.
*/
public static MessageCapabilities intersection(final MessageCapabilities mc1, final MessageCapabilities mc2) {
if (mc1 == null || mc2 == null)
return null;
// Compute the intersection of compression algorithms.
final Set<CompressionAlgorithm> compressionAlgos = EnumSet.noneOf(CompressionAlgorithm.class);
compressionAlgos.addAll(mc1.compressionAlgos);
compressionAlgos.retainAll(mc2.compressionAlgos);
// Compute the intersection of languages. This may not respect order.
final List<String> languages = new ArrayList<String>(mc1.languages);
languages.retainAll(mc2.languages);
// Compute the intersection of encoder formats. This may not respect
// order.
final Set<MslEncoderFormat> encoderFormats = new HashSet<MslEncoderFormat>();
encoderFormats.addAll(mc1.encoderFormats);
encoderFormats.retainAll(mc2.encoderFormats);
return new MessageCapabilities(compressionAlgos, languages, encoderFormats);
}
/**
* Create a new message capabilities object with the specified supported
* features.
*
* @param compressionAlgos supported payload compression algorithms. May be
* {@code null}.
* @param languages preferred languages as BCP-47 codes in descending
* order. May be {@code null}.
* @param encoderFormats supported encoder formats. May be {@code null}.
*/
public MessageCapabilities(final Set<CompressionAlgorithm> compressionAlgos, final List<String> languages, final Set<MslEncoderFormat> encoderFormats) {
this.compressionAlgos = Collections.unmodifiableSet(compressionAlgos != null ? compressionAlgos : EnumSet.noneOf(CompressionAlgorithm.class));
this.languages = Collections.unmodifiableList(languages != null ? languages : new ArrayList<String>());
this.encoderFormats = Collections.unmodifiableSet(encoderFormats != null ? encoderFormats : new HashSet<MslEncoderFormat>());
}
/**
* Construct a new message capabilities object from the provided MSL
* object.
*
* @param capabilitiesMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
*/
public MessageCapabilities(final MslObject capabilitiesMo) throws MslEncodingException {
try {
// Extract compression algorithms.
final Set<CompressionAlgorithm> compressionAlgos = EnumSet.noneOf(CompressionAlgorithm.class);
final MslArray algos = capabilitiesMo.optMslArray(KEY_COMPRESSION_ALGOS);
for (int i = 0; algos != null && i < algos.size(); ++i) {
final String algo = algos.getString(i);
// Ignore unsupported algorithms.
try {
compressionAlgos.add(CompressionAlgorithm.valueOf(algo));
} catch (final IllegalArgumentException e) {}
}
this.compressionAlgos = Collections.unmodifiableSet(compressionAlgos);
// Extract languages.
final List<String> languages = new ArrayList<String>();
final MslArray langs = capabilitiesMo.optMslArray(KEY_LANGUAGES);
for (int i = 0; langs != null && i < langs.size(); ++i)
languages.add(langs.getString(i));
this.languages = Collections.unmodifiableList(languages);
// Extract encoder formats.
final Set<MslEncoderFormat> encoderFormats = new HashSet<MslEncoderFormat>();
final MslArray formats = capabilitiesMo.optMslArray(KEY_ENCODER_FORMATS);
for (int i = 0; formats != null && i < formats.size(); ++i) {
final String format = formats.getString(i);
final MslEncoderFormat encoderFormat = MslEncoderFormat.getFormat(format);
// Ignore unsupported formats.
if (encoderFormat != null)
encoderFormats.add(encoderFormat);
}
this.encoderFormats = Collections.unmodifiableSet(encoderFormats);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "capabilities " + capabilitiesMo, e);
}
}
/**
* @return the supported compression algorithms.
*/
public Set<CompressionAlgorithm> getCompressionAlgorithms() {
return this.compressionAlgos;
}
/**
* @return the preferred languages as BCP-47 codes in descending order.
*/
public List<String> getLanguages() {
return this.languages;
}
/**
* @return the supported encoder formats.
*/
public Set<MslEncoderFormat> getEncoderFormats() {
return this.encoderFormats;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_COMPRESSION_ALGOS, encoder.createArray(compressionAlgos));
mo.put(KEY_LANGUAGES, languages);
final MslArray formats = encoder.createArray();
for (final MslEncoderFormat encoderFormat : encoderFormats)
formats.put(-1, encoderFormat.name());
mo.put(KEY_ENCODER_FORMATS, formats);
return encoder.encodeObject(mo, format);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (!(obj instanceof MessageCapabilities)) return false;
final MessageCapabilities that = (MessageCapabilities)obj;
return this.compressionAlgos.equals(that.compressionAlgos) &&
this.languages.equals(that.languages) &&
this.encoderFormats.equals(that.encoderFormats);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.compressionAlgos.hashCode() ^ this.languages.hashCode() ^ this.encoderFormats.hashCode();
}
/** Supported payload compression algorithms. */
private final Set<CompressionAlgorithm> compressionAlgos;
/** Preferred languages as BCP-47 codes in descending order. */
private final List<String> languages;
/** Supported encoder formats. */
private final Set<MslEncoderFormat> encoderFormats;
}
| 1,713 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/SecretMessageContext.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.msg;
/**
* <p>A message context implementation that can be extended for use with
* messages that have secret contents which must be protected from the view of
* unauthorized parties. The contents will be encrypted and integrity protected
* but still replayable.</p>
*
* <p>Most messages should be considered secret messages. Examples would
* private conversations between individuals or the transmission of personal
* information.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class SecretMessageContext implements MessageContext {
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return false;
}
}
| 1,714 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageHeader.java
|
/**
* Copyright (c) 2012-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.msg;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslConstants;
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.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.SessionCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.io.MslArray;
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.keyx.KeyRequestData;
import com.netflix.msl.keyx.KeyResponseData;
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.UserAuthenticationData;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>If a master token exists, the header data chunks will be encrypted and
* verified using the master token. If no master token exists, the header data
* will be verified and encrypted based on the entity authentication
* scheme.</p>
*
* <p>If peer tokens exist, the message recipient is expected to use the peer
* master token to secure its response and send the peer user ID token and peer
* service tokens back in the header data. The request's tokens should be
* included as the response's peer tokens.</p>
*
* <p>If key response data exists, it applies to the token set the receiving
* entity uses to identify itself. In a trusted services network the key
* response data applies to the primary tokens. In a peer-to-peer network the
* key response data applies to the peer tokens.</p>
*
* <p>The header data is represented as
* {@code
* headerdata = {
* "#mandatory" : [ "messageid", "renewable", "handshake" ],
* "timestamp" : "int64(0,2^53^)",
* "messageid" : "int64(0,2^53^)",
* "nonreplayableid" : "int64(0,2^53^)",
* "renewable" : "boolean",
* "handshake" : "boolean",
* "capabilities" : capabilities,
* "keyrequestdata" : [ keyrequestdata ],
* "keyresponsedata" : keyresponsedata,
* "userauthdata" : userauthdata,
* "useridtoken" : useridtoken,
* "servicetokens" : [ servicetoken ],
* "peermastertoken" : mastertoken,
* "peeruseridtoken" : useridtoken,
* "peerservicetokens" : [ servicetoken ]
* }} where:
* <ul>
* <li>{@code timestamp} is the sender time when the header is created in seconds since the UNIX epoch</li>
* <li>{@code messageid} is the message ID</li>
* <li>{@code nonreplayableid} is the non-replayable ID</li>
* <li>{@code renewable} indicates if the master token and user ID are renewable</li>
* <li>{@code handshake} indicates a handshake message</li>
* <li>{@code capabilities} lists the sender's message capabilities</li>
* <li>{@code keyrequestdata} is session key request data</li>
* <li>{@code keyresponsedata} is the session key response data</li>
* <li>{@code userauthdata} is the user authentication data</li>
* <li>{@code useridtoken} is the user ID token</li>
* <li>{@code servicetokens} are the service tokens</li>
* <li>{@code peermastertoken} is the peer master token</li>
* <li>{@code peeruseridtoken} is the peer user ID token</li>
* <li>{@code peerservicetokens} are the peer service tokens</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MessageHeader extends Header {
/** Milliseconds per second. */
private static final long MILLISECONDS_PER_SECOND = 1000;
// Message header data.
/** Key sender. */
private static final String KEY_SENDER = "sender";
/** Key timestamp. */
private static final String KEY_TIMESTAMP = "timestamp";
/** Key message ID. */
private static final String KEY_MESSAGE_ID = "messageid";
/** Key non-replayable ID. */
private static final String KEY_NON_REPLAYABLE_ID = "nonreplayableid";
/** Key non-replayable flag. */
private static final String KEY_NON_REPLAYABLE = "nonreplayable";
/** Key renewable flag. */
private static final String KEY_RENEWABLE = "renewable";
/** Key handshake flag */
private static final String KEY_HANDSHAKE = "handshake";
/** Key capabilities. */
private static final String KEY_CAPABILITIES = "capabilities";
/** Key key exchange request. */
private static final String KEY_KEY_REQUEST_DATA = "keyrequestdata";
/** Key key exchange response. */
private static final String KEY_KEY_RESPONSE_DATA = "keyresponsedata";
/** Key user authentication data. */
private static final String KEY_USER_AUTHENTICATION_DATA = "userauthdata";
/** Key user ID token. */
private static final String KEY_USER_ID_TOKEN = "useridtoken";
/** Key service tokens. */
private static final String KEY_SERVICE_TOKENS = "servicetokens";
// Message header peer data.
/** Key peer master token. */
private static final String KEY_PEER_MASTER_TOKEN = "peermastertoken";
/** Key peer user ID token. */
private static final String KEY_PEER_USER_ID_TOKEN = "peeruseridtoken";
/** Key peer service tokens. */
private static final String KEY_PEER_SERVICE_TOKENS = "peerservicetokens";
/**
* Container struct for message header data.
*/
public static class HeaderData {
/**
* @param messageId the message ID.
* @param nonReplayableId the message's non-replayable ID. May be null.
* @param renewable the message's renewable flag.
* @param handshake the message's handshake flag.
* @param capabilities the sender's message capabilities.
* @param keyRequestData session key request data. May be null or
* empty.
* @param keyResponseData session key response data. May be null.
* @param userAuthData the user authentication data. May be null if a
* user ID token is provided or there is no user authentication
* for this message.
* @param userIdToken the user ID token. May be null if user
* authentication data is provided or there is no user
* authentication for this message.
* @param serviceTokens the service tokens. May be null or empty.
*/
public HeaderData(final long messageId, final Long nonReplayableId,
final boolean renewable, final boolean handshake,
final MessageCapabilities capabilities,
final Set<KeyRequestData> keyRequestData, final KeyResponseData keyResponseData,
final UserAuthenticationData userAuthData, final UserIdToken userIdToken,
final Set<ServiceToken> serviceTokens)
{
this.messageId = messageId;
this.nonReplayableId = nonReplayableId;
this.renewable = renewable;
this.handshake = handshake;
this.capabilities = capabilities;
this.keyRequestData = keyRequestData;
this.keyResponseData = keyResponseData;
this.userAuthData = userAuthData;
this.userIdToken = userIdToken;
this.serviceTokens = serviceTokens;
}
public final long messageId;
public final Long nonReplayableId;
public final boolean renewable;
public final boolean handshake;
public final MessageCapabilities capabilities;
public final Set<KeyRequestData> keyRequestData;
public final KeyResponseData keyResponseData;
public final UserAuthenticationData userAuthData;
public final UserIdToken userIdToken;
public final Set<ServiceToken> serviceTokens;
}
/**
* Container struct for header peer data.
*/
public static class HeaderPeerData {
/**
* @param peerMasterToken peer master token. May be null.
* @param peerUserIdToken peer user ID token. May be null if there is
* no user authentication for the peer.
* @param peerServiceTokens peer service tokens. May be empty.
*/
public HeaderPeerData(final MasterToken peerMasterToken, final UserIdToken peerUserIdToken,
final Set<ServiceToken> peerServiceTokens)
{
this.peerMasterToken = peerMasterToken;
this.peerUserIdToken = peerUserIdToken;
this.peerServiceTokens = peerServiceTokens;
}
public final MasterToken peerMasterToken;
public final UserIdToken peerUserIdToken;
public final Set<ServiceToken> peerServiceTokens;
}
/**
* <p>Construct a new message header with the provided message data.</p>
*
* <p>Headers are encrypted and signed. If a master token is provided, it
* will be used for this purpose. Otherwise the crypto context appropriate
* for the entity authentication scheme will be used. N.B. Either the
* entity authentication data or the master token must be provided.</p>
*
* <p>Peer tokens are only processed if operating in peer-to-peer mode.</p>
*
* @param ctx MSL context.
* @param entityAuthData the entity authentication data. May be null if a
* master token is provided.
* @param masterToken the master token. May be null if entity
* authentication data is provided.
* @param headerData message header data container.
* @param peerData message header peer data container.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the message.
* @throws MslMasterTokenException if the header master token is not
* trusted and needs to be to accept this message header.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
*/
public MessageHeader(final MslContext ctx, final EntityAuthenticationData entityAuthData, final MasterToken masterToken, final HeaderData headerData, final HeaderPeerData peerData) throws MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException {
// Message ID must be within range.
if (headerData.messageId < 0 || headerData.messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + headerData.messageId + " is out of range.");
// Message entity must be provided.
if (entityAuthData == null && masterToken == null)
throw new MslInternalException("Message entity authentication data or master token must be provided.");
// Do not allow user authentication data to be included if the message
// will not be encrypted.
final boolean encrypted;
if (masterToken != null) {
encrypted = true;
} else {
final EntityAuthenticationScheme scheme = entityAuthData.getScheme();
encrypted = scheme.encrypts();
}
if (!encrypted && headerData.userAuthData != null)
throw new MslInternalException("User authentication data cannot be included if the message is not encrypted.");
// Older MSL stacks expect the sender if a master token is being used.
//
// If the local entity does not know its entity identity, then use the
// empty string. This will work except for the case where the old MSL
// stack is receiving a message for which it is also the issuer of the
// master token. That scenario will continue to fail.
final String sender;
if (masterToken != null) {
final String localIdentity = ctx.getEntityAuthenticationData(null).getIdentity();
sender = (localIdentity != null) ? localIdentity : "";
} else {
sender = null;
}
this.entityAuthData = (masterToken == null) ? entityAuthData : null;
this.masterToken = masterToken;
this.nonReplayableId = headerData.nonReplayableId;
this.renewable = headerData.renewable;
this.handshake = headerData.handshake;
this.capabilities = headerData.capabilities;
this.timestamp = ctx.getTime() / MILLISECONDS_PER_SECOND;
this.messageId = headerData.messageId;
this.keyRequestData = Collections.unmodifiableSet((headerData.keyRequestData != null) ? headerData.keyRequestData : new HashSet<KeyRequestData>());
this.keyResponseData = headerData.keyResponseData;
this.userAuthData = headerData.userAuthData;
this.userIdToken = headerData.userIdToken;
this.serviceTokens = Collections.unmodifiableSet((headerData.serviceTokens != null) ? headerData.serviceTokens : new HashSet<ServiceToken>());
if (ctx.isPeerToPeer()) {
this.peerMasterToken = peerData.peerMasterToken;
this.peerUserIdToken = peerData.peerUserIdToken;
this.peerServiceTokens = Collections.unmodifiableSet((peerData.peerServiceTokens != null) ? peerData.peerServiceTokens : new HashSet<ServiceToken>());
} else {
this.peerMasterToken = null;
this.peerUserIdToken = null;
this.peerServiceTokens = Collections.emptySet();
}
// Grab token verification master tokens.
final MasterToken tokenVerificationMasterToken, peerTokenVerificationMasterToken;
if (this.keyResponseData != null) {
// The key response data is used for token verification in a
// trusted services network and peer token verification in a peer-
// to-peer network.
if (!ctx.isPeerToPeer()) {
tokenVerificationMasterToken = this.keyResponseData.getMasterToken();
peerTokenVerificationMasterToken = this.peerMasterToken;
} else {
tokenVerificationMasterToken = this.masterToken;
peerTokenVerificationMasterToken = this.keyResponseData.getMasterToken();
}
} else {
tokenVerificationMasterToken = this.masterToken;
peerTokenVerificationMasterToken = this.peerMasterToken;
}
// Check token combinations.
if (this.userIdToken != null && (tokenVerificationMasterToken == null || !this.userIdToken.isBoundTo(tokenVerificationMasterToken)))
throw new MslInternalException("User ID token must be bound to a master token.");
if (this.peerUserIdToken != null && (peerTokenVerificationMasterToken == null || !this.peerUserIdToken.isBoundTo(peerTokenVerificationMasterToken)))
throw new MslInternalException("Peer user ID token must be bound to a peer master token.");
// Grab the user.
if (this.userIdToken != null)
this.user = this.userIdToken.getUser();
else
this.user = null;
// All service tokens must be unbound or if bound, bound to the
// provided tokens.
for (final ServiceToken serviceToken : this.serviceTokens) {
if (serviceToken.isMasterTokenBound() && (tokenVerificationMasterToken == null || !serviceToken.isBoundTo(tokenVerificationMasterToken)))
throw new MslInternalException("Master token bound service tokens must be bound to the provided master token.");
if (serviceToken.isUserIdTokenBound() && (this.userIdToken == null || !serviceToken.isBoundTo(this.userIdToken)))
throw new MslInternalException("User ID token bound service tokens must be bound to the provided user ID token.");
}
for (final ServiceToken peerServiceToken : this.peerServiceTokens) {
if (peerServiceToken.isMasterTokenBound() && (peerTokenVerificationMasterToken == null || !peerServiceToken.isBoundTo(peerTokenVerificationMasterToken)))
throw new MslInternalException("Master token bound peer service tokens must be bound to the provided peer master token.");
if (peerServiceToken.isUserIdTokenBound() && (this.peerUserIdToken == null || !peerServiceToken.isBoundTo(this.peerUserIdToken)))
throw new MslInternalException("User ID token bound peer service tokens must be bound to the provided peer user ID token.");
}
// Construct the header data.
try {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final Set<MslEncoderFormat> formats = (capabilities != null) ? capabilities.getEncoderFormats() : null;
final MslEncoderFormat format = encoder.getPreferredFormat(formats);
headerdata = encoder.createObject();
if (sender != null) headerdata.put(KEY_SENDER, sender);
headerdata.put(KEY_TIMESTAMP, this.timestamp);
headerdata.put(KEY_MESSAGE_ID, this.messageId);
headerdata.put(KEY_NON_REPLAYABLE, this.nonReplayableId != null);
if (this.nonReplayableId != null) headerdata.put(KEY_NON_REPLAYABLE_ID, this.nonReplayableId);
headerdata.put(KEY_RENEWABLE, this.renewable);
headerdata.put(KEY_HANDSHAKE, this.handshake);
if (this.capabilities != null) headerdata.put(KEY_CAPABILITIES, this.capabilities);
if (this.keyRequestData.size() > 0) headerdata.put(KEY_KEY_REQUEST_DATA, MslEncoderUtils.createArray(ctx, format, this.keyRequestData));
if (this.keyResponseData != null) headerdata.put(KEY_KEY_RESPONSE_DATA, this.keyResponseData);
if (this.userAuthData != null) headerdata.put(KEY_USER_AUTHENTICATION_DATA, this.userAuthData);
if (this.userIdToken != null) headerdata.put(KEY_USER_ID_TOKEN, this.userIdToken);
if (this.serviceTokens.size() > 0) headerdata.put(KEY_SERVICE_TOKENS, MslEncoderUtils.createArray(ctx, format, this.serviceTokens));
if (this.peerMasterToken != null) headerdata.put(KEY_PEER_MASTER_TOKEN, this.peerMasterToken);
if (this.peerUserIdToken != null) headerdata.put(KEY_PEER_USER_ID_TOKEN, this.peerUserIdToken);
if (this.peerServiceTokens.size() > 0) headerdata.put(KEY_PEER_SERVICE_TOKENS, MslEncoderUtils.createArray(ctx, format, this.peerServiceTokens));
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_ENCODE_ERROR, "headerdata", e)
.setMasterToken(this.masterToken)
.setEntityAuthenticationData(this.entityAuthData)
.setUserIdToken(this.userIdToken)
.setUserAuthenticationData(this.userAuthData)
.setMessageId(this.messageId);
}
// Create the correct crypto context.
if (this.masterToken != null) {
// Use a stored master token crypto context if we have one.
final ICryptoContext cachedCryptoContext = ctx.getMslStore().getCryptoContext(this.masterToken);
// If there was no stored crypto context try making one from
// the master token. We can only do this if we can open up the
// master token.
if (cachedCryptoContext == null) {
if (!this.masterToken.isVerified() || !this.masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, this.masterToken).setUserIdToken(this.userIdToken).setUserAuthenticationData(this.userAuthData).setMessageId(this.messageId);
this.messageCryptoContext = new SessionCryptoContext(ctx, this.masterToken);
} else {
this.messageCryptoContext = cachedCryptoContext;
}
} else {
try {
final EntityAuthenticationScheme scheme = this.entityAuthData.getScheme();
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(scheme);
if (factory == null)
throw new MslEntityAuthException(MslError.ENTITYAUTH_FACTORY_NOT_FOUND, scheme.name());
this.messageCryptoContext = factory.getCryptoContext(ctx, this.entityAuthData);
} catch (final MslCryptoException e) {
e.setEntityAuthenticationData(this.entityAuthData);
e.setUserIdToken(this.userIdToken);
e.setUserAuthenticationData(this.userAuthData);
e.setMessageId(this.messageId);
throw e;
} catch (final MslEntityAuthException e) {
e.setEntityAuthenticationData(this.entityAuthData);
e.setUserIdToken(this.userIdToken);
e.setUserAuthenticationData(this.userAuthData);
e.setMessageId(this.messageId);
throw e;
}
}
}
/**
* <p>Construct a new message from the provided JSON object.</p>
*
* <p>Headers are encrypted and signed. If a master token is found, it will
* be used for this purpose. Otherwise the crypto context appropriate for
* the entity authentication scheme will be used. Either the master token
* or entity authentication data must be found.</p>
*
* <p>If user authentication data is included user authentication will be
* performed. If a user ID token is included then its user information is
* considered to be trusted.</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 explicitly mapped onto a crypto context, the default crypto context
* will be used.</p>
*
* @param ctx MSL context.
* @param headerdataBytes encoded header data.
* @param entityAuthData the entity authentication data. May be null if a
* master token is provided.
* @param masterToken the master token. May be null if entity
* authentication data is provided.
* @param signature the header signature.
* @param cryptoContexts the map of service token names onto crypto
* contexts used to decrypt and verify service tokens.
* @throws MslEncodingException if there is an error parsing the JSON.
* @throws MslCryptoException if there is an error decrypting or verifying
* the header or creating the key exchange crypto context.
* @throws MslEntityAuthException if unable to create the entity
* authentication data or there is an error with the entity
* authentication data.
* @throws MslKeyExchangeException if unable to create the key request data
* or key response data.
* @throws MslUserAuthException if unable to create the user authentication
* data or authenticate the user.
* @throws MslMasterTokenException if the header master token is not
* trusted and needs to be to accept this message header.
* @throws MslMessageException if the message does not contain an entity
* authentication data or a master token, the header data is
* missing or invalid, or the message ID is negative, or the
* message is not encrypted and contains user authentication data.
* @throws MslException if a token is improperly bound to another token.
*/
protected MessageHeader(final MslContext ctx, final byte[] headerdataBytes, final EntityAuthenticationData entityAuthData, final MasterToken masterToken, final byte[] signature, final Map<String,ICryptoContext> cryptoContexts) throws MslEncodingException, MslCryptoException, MslKeyExchangeException, MslUserAuthException, MslMasterTokenException, MslMessageException, MslEntityAuthException, MslException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] plaintext;
try {
this.entityAuthData = (masterToken == null) ? entityAuthData : null;
this.masterToken = masterToken;
if (entityAuthData == null && masterToken == null)
throw new MslMessageException(MslError.MESSAGE_ENTITY_NOT_FOUND);
// Create the correct crypto context.
if (masterToken != null) {
// Use a stored master token crypto context if we have one.
final ICryptoContext cachedCryptoContext = ctx.getMslStore().getCryptoContext(masterToken);
// If there was no stored crypto context try making one from
// the master token. We can only do this if we can open up the
// master token.
if (cachedCryptoContext == null) {
if (!masterToken.isVerified() || !masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
this.messageCryptoContext = new SessionCryptoContext(ctx, masterToken);
} else {
this.messageCryptoContext = cachedCryptoContext;
}
} else {
try {
final EntityAuthenticationScheme scheme = entityAuthData.getScheme();
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(scheme);
if (factory == null)
throw new MslEntityAuthException(MslError.ENTITYAUTH_FACTORY_NOT_FOUND, scheme.name());
this.messageCryptoContext = factory.getCryptoContext(ctx, entityAuthData);
} catch (final MslCryptoException e) {
e.setEntityAuthenticationData(entityAuthData);
throw e;
} catch (final MslEntityAuthException e) {
e.setEntityAuthenticationData(entityAuthData);
throw e;
}
}
// Verify and decrypt the header data.
//
// Throw different errors depending on whether or not a master
// token was used.
if (!this.messageCryptoContext.verify(headerdataBytes, signature, encoder)) {
if (masterToken != null)
throw new MslCryptoException(MslError.MESSAGE_MASTERTOKENBASED_VERIFICATION_FAILED);
else
throw new MslCryptoException(MslError.MESSAGE_ENTITYDATABASED_VERIFICATION_FAILED);
}
plaintext = this.messageCryptoContext.decrypt(headerdataBytes, encoder);
} catch (final MslCryptoException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
throw e;
} catch (final MslEntityAuthException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
throw e;
}
try {
headerdata = encoder.parseObject(plaintext);
// Pull the message ID first because any error responses need to
// use it.
this.messageId = headerdata.getLong(KEY_MESSAGE_ID);
if (this.messageId < 0 || this.messageId > MslConstants.MAX_LONG_VALUE)
throw new MslMessageException(MslError.MESSAGE_ID_OUT_OF_RANGE, "headerdata " + headerdata).setMasterToken(masterToken).setEntityAuthenticationData(entityAuthData);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "headerdata " + Base64.encode(plaintext), e).setMasterToken(masterToken).setEntityAuthenticationData(entityAuthData);
}
try {
this.timestamp = (headerdata.has(KEY_TIMESTAMP)) ? headerdata.getLong(KEY_TIMESTAMP) : null;
// Pull key response data.
final MasterToken tokenVerificationMasterToken;
if (headerdata.has(KEY_KEY_RESPONSE_DATA)) {
this.keyResponseData = KeyResponseData.create(ctx, headerdata.getMslObject(KEY_KEY_RESPONSE_DATA, encoder));
// The key response data master token is used for token
// verification in a trusted services network. Otherwise it
// will be used for peer token verification, which is handled
// below.
tokenVerificationMasterToken = (!ctx.isPeerToPeer())
? this.keyResponseData.getMasterToken()
: masterToken;
} else {
this.keyResponseData = null;
tokenVerificationMasterToken = masterToken;
}
// User ID tokens are always authenticated by a master token.
this.userIdToken = (headerdata.has(KEY_USER_ID_TOKEN))
? new UserIdToken(ctx, headerdata.getMslObject(KEY_USER_ID_TOKEN, encoder), tokenVerificationMasterToken)
: null;
// Pull user authentication data.
this.userAuthData = (headerdata.has(KEY_USER_AUTHENTICATION_DATA))
? UserAuthenticationData.create(ctx, tokenVerificationMasterToken, headerdata.getMslObject(KEY_USER_AUTHENTICATION_DATA, encoder))
: null;
// Identify the user if any.
if (this.userAuthData != null) {
// Reject unencrypted messages containing user authentication data.
final boolean encrypted = (masterToken != null) ? true : entityAuthData.getScheme().encrypts();
if (!encrypted)
throw new MslMessageException(MslError.UNENCRYPTED_MESSAGE_WITH_USERAUTHDATA).setUserIdToken(userIdToken).setUserAuthenticationData(userAuthData);
// Verify the user authentication data.
final UserAuthenticationScheme scheme = this.userAuthData.getScheme();
final UserAuthenticationFactory factory = ctx.getUserAuthenticationFactory(scheme);
if (factory == null)
throw new MslUserAuthException(MslError.USERAUTH_FACTORY_NOT_FOUND, scheme.name()).setUserIdToken(userIdToken).setUserAuthenticationData(userAuthData);
final String identity = (this.masterToken != null) ? this.masterToken.getIdentity() : this.entityAuthData.getIdentity();
this.user = factory.authenticate(ctx, identity, this.userAuthData, this.userIdToken);
} else if (this.userIdToken != null) {
this.user = this.userIdToken.getUser();
} else {
this.user = null;
}
// Service tokens are authenticated by the master token if it
// exists or by the application crypto context.
final Set<ServiceToken> serviceTokens = new HashSet<ServiceToken>();
if (headerdata.has(KEY_SERVICE_TOKENS)) {
final MslArray tokens = headerdata.getMslArray(KEY_SERVICE_TOKENS);
for (int i = 0; i < tokens.size(); ++i) {
try {
serviceTokens.add(new ServiceToken(ctx, tokens.getMslObject(i, encoder), tokenVerificationMasterToken, this.userIdToken, cryptoContexts));
} catch (final MslException e) {
e.setMasterToken(tokenVerificationMasterToken).setUserIdToken(this.userIdToken).setUserAuthenticationData(userAuthData);
throw e;
}
}
}
this.serviceTokens = Collections.unmodifiableSet(serviceTokens);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "headerdata " + headerdata, e).setMasterToken(masterToken).setEntityAuthenticationData(entityAuthData).setMessageId(this.messageId);
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setMessageId(this.messageId);
throw e;
}
try {
this.nonReplayableId = (headerdata.has(KEY_NON_REPLAYABLE_ID)) ? headerdata.getLong(KEY_NON_REPLAYABLE_ID) : null;
this.renewable = headerdata.getBoolean(KEY_RENEWABLE);
// FIXME: Make handshake required once all MSL stacks are updated.
this.handshake = (headerdata.has(KEY_HANDSHAKE)) ? headerdata.getBoolean(KEY_HANDSHAKE) : false;
// Verify values.
if (nonReplayableId != null && (nonReplayableId < 0 || nonReplayableId > MslConstants.MAX_LONG_VALUE))
throw new MslMessageException(MslError.NONREPLAYABLE_ID_OUT_OF_RANGE, "headerdata " + headerdata);
// Pull message capabilities.
if (headerdata.has(KEY_CAPABILITIES)) {
final MslObject capabilitiesMo = headerdata.getMslObject(KEY_CAPABILITIES, encoder);
this.capabilities = new MessageCapabilities(capabilitiesMo);
} else {
this.capabilities = null;
}
// Pull key request data containers.
final Set<KeyRequestData> keyRequestData = new HashSet<KeyRequestData>();
if (headerdata.has(KEY_KEY_REQUEST_DATA)) {
final MslArray keyRequests = headerdata.getMslArray(KEY_KEY_REQUEST_DATA);
for (int i = 0; i < keyRequests.size(); ++i) {
keyRequestData.add(KeyRequestData.create(ctx, keyRequests.getMslObject(i, encoder)));
}
}
this.keyRequestData = Collections.unmodifiableSet(keyRequestData);
// Only process peer-to-peer tokens if in peer-to-peer mode.
if (ctx.isPeerToPeer()) {
// Pull peer master token.
this.peerMasterToken = (headerdata.has(KEY_PEER_MASTER_TOKEN))
? new MasterToken(ctx, headerdata.getMslObject(KEY_PEER_MASTER_TOKEN, encoder))
: null;
// The key response data master token is used for peer token
// verification if in peer-to-peer mode.
final MasterToken peerVerificationMasterToken;
if (this.keyResponseData != null)
peerVerificationMasterToken = this.keyResponseData.getMasterToken();
else
peerVerificationMasterToken = this.peerMasterToken;
// Pull peer user ID token. User ID tokens are always
// authenticated by a master token.
try {
this.peerUserIdToken = (headerdata.has(KEY_PEER_USER_ID_TOKEN))
? new UserIdToken(ctx, headerdata.getMslObject(KEY_PEER_USER_ID_TOKEN, encoder), peerVerificationMasterToken)
: null;
} catch (final MslException e) {
e.setMasterToken(peerVerificationMasterToken);
throw e;
}
// Peer service tokens are authenticated by the peer master
// token if it exists or by the application crypto context.
final Set<ServiceToken> peerServiceTokens = new HashSet<ServiceToken>();
if (headerdata.has(KEY_PEER_SERVICE_TOKENS)) {
final MslArray tokens = headerdata.getMslArray(KEY_PEER_SERVICE_TOKENS);
for (int i = 0; i < tokens.size(); ++i) {
try {
peerServiceTokens.add(new ServiceToken(ctx, tokens.getMslObject(i, encoder), peerVerificationMasterToken, this.peerUserIdToken, cryptoContexts));
} catch (final MslException e) {
e.setMasterToken(peerVerificationMasterToken).setUserIdToken(this.peerUserIdToken);
throw e;
}
}
}
this.peerServiceTokens = Collections.unmodifiableSet(peerServiceTokens);
} else {
this.peerMasterToken = null;
this.peerUserIdToken = null;
this.peerServiceTokens = Collections.emptySet();
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "headerdata " + headerdata.toString(), e)
.setMasterToken(masterToken)
.setEntityAuthenticationData(entityAuthData)
.setUserIdToken(this.userIdToken)
.setUserAuthenticationData(this.userAuthData)
.setMessageId(this.messageId);
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setUserIdToken(this.userIdToken);
e.setUserAuthenticationData(this.userAuthData);
e.setMessageId(this.messageId);
throw e;
}
}
/**
* @return true if the message header crypto context provides encryption.
* @see #getCryptoContext()
*/
public boolean isEncrypting() {
return masterToken != null || entityAuthData.getScheme().encrypts();
}
/**
* Returns the crypto context that was used to process the header data.
* This crypto context should also be used to process the payload data if
* no key response data is included in the message.
*
* @return the header data crypto context.
* @see #isEncrypting()
*/
public ICryptoContext getCryptoContext() {
return messageCryptoContext;
}
/**
* Returns the user if the user has been authenticated or a user ID token
* was provided.
*
* @return the user. May be null.
*/
public MslUser getUser() {
return user;
}
/**
* Returns the entity authentication data. May be null if the entity has
* already been authenticated and is using a master token instead.
*
* @return the entity authentication data.
*/
public EntityAuthenticationData getEntityAuthenticationData() {
return entityAuthData;
}
/**
* Returns the primary master token identifying the entity and containing
* the session keys. May be null if the entity has not been authenticated.
*
* @return the master token. May be null.
*/
public MasterToken getMasterToken() {
return masterToken;
}
/**
* @return the timestamp. May be null.
*/
public Date getTimestamp() {
return (timestamp != null) ? new Date(timestamp * MILLISECONDS_PER_SECOND) : null;
}
/**
* @return the message ID.
*/
public long getMessageId() {
return messageId;
}
/**
* @return the non-replayable ID. May be null.
*/
public Long getNonReplayableId() {
return nonReplayableId;
}
/**
* @return true if the message renewable flag is set.
*/
public boolean isRenewable() {
return renewable;
}
/**
* @return true if the message handshake flag is set.
*/
public boolean isHandshake() {
return handshake;
}
/**
* @return the message capabilities. May be null.
*/
public MessageCapabilities getMessageCapabilities() {
return capabilities;
}
/**
* @return key request data. May be empty.
*/
public Set<KeyRequestData> getKeyRequestData() {
return keyRequestData;
}
/**
* @return key response data. May be null.
*/
public KeyResponseData getKeyResponseData() {
return keyResponseData;
}
/**
* Returns the user authentication data. May be null if the user has
* already been authenticated and is using a user ID token or if there is
* no user authentication requested.
*
* @return the user authentication data. May be null.
*/
public UserAuthenticationData getUserAuthenticationData() {
return userAuthData;
}
/**
* Returns the primary user ID token identifying the user. May be null if
* the user has not been authenticated.
*
* @return the user ID token. May be null.
*/
public UserIdToken getUserIdToken() {
return userIdToken;
}
/**
* Returns the primary service tokens included in this message.
*
* The returned list is immutable.
*
* @return the service tokens. May be empty if no there are no service
* tokens.
*/
public Set<ServiceToken> getServiceTokens() {
return serviceTokens;
}
/**
* Returns the master token that should be used by an entity responding to
* this message. Will be null if the responding entity should use its own
* entity authentication data or the primary master token.
*
* @return the peer master token. May be null.
*/
public MasterToken getPeerMasterToken() {
return peerMasterToken;
}
/**
* Returns the user ID token that must be used by an entity responding to
* this message if an peer master token is provided. May be null if peer
* user authentication has not occurred. Will be null if there is no peer
* master token.
*
* @return the peer user ID token. May be null.
*/
public UserIdToken getPeerUserIdToken() {
return peerUserIdToken;
}
/**
* <p>Returns the service tokens that must be used by an entity responding
* to this message. May be null if the responding entity should use the
* primary service tokens.</p>
*
* <p>The returned list is immutable.</p>
*
* @return the peer service tokens. May be empty if no there are no peer
* service tokens.
*/
public Set<ServiceToken> getPeerServiceTokens() {
return peerServiceTokens;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
// Return any cached encoding.
if (encodings.containsKey(format))
return encodings.get(format);
// Encrypt and sign the header data.
final byte[] plaintext = encoder.encodeObject(headerdata, format);
final byte[] ciphertext;
try {
ciphertext = this.messageCryptoContext.encrypt(plaintext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error encrypting the header data.", e);
}
final byte[] signature;
try {
signature = this.messageCryptoContext.sign(ciphertext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error signging the header data.", e);
}
// Create the encoding.
final MslObject header = encoder.createObject();
if (masterToken != null)
header.put(Header.KEY_MASTER_TOKEN, masterToken);
else
header.put(Header.KEY_ENTITY_AUTHENTICATION_DATA, entityAuthData);
header.put(Header.KEY_HEADERDATA, ciphertext);
header.put(Header.KEY_SIGNATURE, signature);
final byte[] encoding = encoder.encodeObject(header, format);
// Cache and return the encoding.
encodings.put(format, encoding);
return encoding;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (!(obj instanceof MessageHeader)) return false;
final MessageHeader that = (MessageHeader) obj;
return (masterToken != null && masterToken.equals(that.masterToken) ||
entityAuthData != null && entityAuthData.equals(that.entityAuthData)) &&
(timestamp != null && timestamp.equals(that.timestamp) ||
timestamp == null && that.timestamp == null) &&
messageId == that.messageId &&
(nonReplayableId != null && nonReplayableId.equals(that.nonReplayableId) ||
nonReplayableId == null && that.nonReplayableId == null) &&
renewable == that.renewable &&
handshake == that.handshake &&
(capabilities != null && capabilities.equals(that.capabilities) ||
capabilities == that.capabilities) &&
keyRequestData.equals(that.keyRequestData) &&
(keyResponseData != null && keyResponseData.equals(that.keyResponseData) ||
keyResponseData == that.keyResponseData) &&
(userAuthData != null && userAuthData.equals(that.userAuthData) ||
userAuthData == that.userAuthData) &&
(userIdToken != null && userIdToken.equals(that.userIdToken) ||
userIdToken == that.userIdToken) &&
serviceTokens.equals(that.serviceTokens) &&
(peerMasterToken != null && peerMasterToken.equals(that.peerMasterToken) ||
peerMasterToken == that.peerMasterToken) &&
(peerUserIdToken != null && peerUserIdToken.equals(that.peerUserIdToken) ||
peerUserIdToken == that.peerUserIdToken) &&
peerServiceTokens.equals(that.peerServiceTokens);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return ((masterToken != null) ? masterToken.hashCode() : entityAuthData.hashCode()) ^
((timestamp != null) ? timestamp.hashCode() : 0) ^
Long.valueOf(messageId).hashCode() ^
((nonReplayableId != null) ? nonReplayableId.hashCode() : 0) ^
Boolean.valueOf(renewable).hashCode() ^
Boolean.valueOf(handshake).hashCode() ^
((capabilities != null) ? capabilities.hashCode() : 0) ^
keyRequestData.hashCode() ^
((keyResponseData != null) ? keyResponseData.hashCode() : 0) ^
((userAuthData != null) ? userAuthData.hashCode() : 0) ^
((userIdToken != null) ? userIdToken.hashCode() : 0) ^
serviceTokens.hashCode() ^
((peerMasterToken != null) ? peerMasterToken.hashCode() : 0) ^
((peerUserIdToken != null) ? peerUserIdToken.hashCode() : 0) ^
peerServiceTokens.hashCode();
}
/** Entity authentication data. */
protected final EntityAuthenticationData entityAuthData;
/** Master token. */
protected final MasterToken masterToken;
/** Header data. */
protected final MslObject headerdata;
/** Timestamp in seconds since the epoch. */
private final Long timestamp;
/** Message ID. */
private final long messageId;
/** Non-replayable ID. */
private final Long nonReplayableId;
/** Renewable. */
private final boolean renewable;
/** Handshake message. */
private final boolean handshake;
/** Message capabilities. */
private final MessageCapabilities capabilities;
/** Key request data. */
private final Set<KeyRequestData> keyRequestData;
/** Key response data. */
private final KeyResponseData keyResponseData;
/** User authentication data. */
private final UserAuthenticationData userAuthData;
/** User ID token. */
private final UserIdToken userIdToken;
/** Service tokens (immutable). */
private final Set<ServiceToken> serviceTokens;
/** Peer master token. */
private final MasterToken peerMasterToken;
/** Peer user ID token. */
private final UserIdToken peerUserIdToken;
/** Peer service tokens (immutable). */
private final Set<ServiceToken> peerServiceTokens;
/** User (if authenticated). */
private final MslUser user;
/** Message crypto context. */
protected final ICryptoContext messageCryptoContext;
/** Cached encodings. */
protected final Map<MslEncoderFormat,byte[]> encodings = new HashMap<MslEncoderFormat,byte[]>();
}
| 1,715 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/Header.java
|
/**
* Copyright (c) 2012-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.msg;
import java.util.Map;
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.MslMessageException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncodable;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* <p>A MSL header contains entity authentication data or a master token
* identifying the message sender and data used to authenticate the header
* data. Portions of the header may be encrypted.</p>
*
* <p>A message header is represented as
* {@code
* header = {
* "#mandatory" : [ "headerdata", "signature" ],
* "#conditions" : [ "entityauthdata xor mastertoken" ],
* "entityauthdata" : entityauthdata,
* "mastertoken" : mastertoken,
* "headerdata" : "binary",
* "signature" : "binary"
* }} where:
* <ul>
* <li>{@code entityauthdata} is the entity authentication data (mutually exclusive with mastertoken)</li>
* <li>{@code mastertoken} is the master token (mutually exclusive with entityauthdata)</li>
* <li>{@code headerdata} is the encrypted header data (headerdata)</li>
* <li>{@code signature} is the verification data of the header data</li>
* </ul></p>
*
* <p>An error header is represented as
* {@code
* errorheader = {
* "#mandatory" : [ "entityauthdata", "errordata", "signature" ],
* "entityauthdata" : entityauthdata,
* "errordata" : "binary",
* "signature" : "binary"
* }} where:
* <ul>
* <li>{@code entityauthdata} is the entity authentication data</li>
* <li>{@code errordata} is the encrypted error data (errordata)</li>
* <li>{@code signature} is the verification data of the error data</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class Header implements MslEncodable {
/** Key entity authentication data. */
public static final String KEY_ENTITY_AUTHENTICATION_DATA = "entityauthdata";
/** Key master token. */
public static final String KEY_MASTER_TOKEN = "mastertoken";
/** Key header data. */
public static final String KEY_HEADERDATA = "headerdata";
/** Key error data. */
public static final String KEY_ERRORDATA = "errordata";
/** Key signature. */
public static final String KEY_SIGNATURE = "signature";
/**
* <p>Construct a new header from the provided MSL object.</p>
*
* <p>Headers are encrypted and signed. If a master token is found, it will
* be used for this purpose. Otherwise the crypto context appropriate for
* the entity authentication scheme will be used.</p>
*
* <p>For message headers the master token or entity authentication data
* must be found. For error headers the entity authentication data must be
* found.</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 headerMo header MSL object.
* @param cryptoContexts the map of service token names onto crypto
* contexts used to decrypt and verify service tokens.
* @return the header.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException if there is an error decrypting or verifying
* the message.
* @throws MslEntityAuthException if unable to create the entity
* authentication data.
* @throws MslKeyExchangeException if unable to create the key request data
* or key response data.
* @throws MslUserAuthException if unable to create the user authentication
* data.
* @throws MslMessageException if the message does not contain an entity
* authentication data or a master token, the header data is
* missing or invalid, or the message ID is negative, or the
* message is not encrypted and contains user authentication data.
* @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 static Header parseHeader(final MslContext ctx, final MslObject headerMo, final Map<String,ICryptoContext> cryptoContexts) throws MslEncodingException, MslEntityAuthException, MslCryptoException, MslKeyExchangeException, MslUserAuthException, MslMessageException, MslException {
// Pull authentication data.
final EntityAuthenticationData entityAuthData;
final MasterToken masterToken;
final byte[] signature;
try {
// Pull message data.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
entityAuthData = (headerMo.has(Header.KEY_ENTITY_AUTHENTICATION_DATA))
? EntityAuthenticationData.create(ctx, headerMo.getMslObject(Header.KEY_ENTITY_AUTHENTICATION_DATA, encoder))
: null;
masterToken = (headerMo.has(Header.KEY_MASTER_TOKEN))
? new MasterToken(ctx, headerMo.getMslObject(Header.KEY_MASTER_TOKEN, encoder))
: null;
signature = headerMo.getBytes(Header.KEY_SIGNATURE);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "header/errormsg " + headerMo, e);
}
try {
// Process message headers.
if (headerMo.has(Header.KEY_HEADERDATA)) {
final byte[] headerdata = headerMo.getBytes(Header.KEY_HEADERDATA);
if (headerdata.length == 0)
throw new MslMessageException(MslError.HEADER_DATA_MISSING).setMasterToken(masterToken).setEntityAuthenticationData(entityAuthData);
return new MessageHeader(ctx, headerdata, entityAuthData, masterToken, signature, cryptoContexts);
}
// Process error headers.
else if (headerMo.has(Header.KEY_ERRORDATA)) {
final byte[] errordata = headerMo.getBytes(Header.KEY_ERRORDATA);
if (errordata.length == 0)
throw new MslMessageException(MslError.HEADER_DATA_MISSING).setMasterToken(masterToken).setEntityAuthenticationData(entityAuthData);
return new ErrorHeader(ctx, errordata, entityAuthData, signature);
}
// Unknown header.
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, headerMo.toString());
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "header/errormsg " + headerMo, e);
}
}
}
| 1,716 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/PublicMessageContext.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.msg;
/**
* <p>A message context implementation that can be extended for use with
* messages that do not require contents to be encrypted, only to be integrity
* protected. If encryption is possible the message contents will be
* encrypted.</p>
*
* <p>Example uses of the public message context would be for the broadcast of
* authenticated public announcements or the transmission of information that
* is useless after a short period of time.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class PublicMessageContext implements MessageContext {
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return false;
}
}
| 1,717 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/msg/ConsoleFilterStreamFactory.java
|
/**
* Copyright (c) 2013-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.msg;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The console filter stream factory will output the wrapped streams data to
* stdout.
*
* This class is thread-safe.
*
* @author Wesley Miaw <[email protected]>
*/
public class ConsoleFilterStreamFactory 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 {
final int c = in.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 {
final int r = in.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.write(b, off, len);
System.out.flush();
out.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();
out.write(b);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.FilterStreamFactory#getInputStream(java.io.InputStream)
*/
@Override
public InputStream getInputStream(final InputStream in) {
return new ConsoleInputStream(in);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.FilterStreamFactory#getOutputStream(java.io.OutputStream)
*/
@Override
public OutputStream getOutputStream(final OutputStream out) {
return new ConsoleOutputStream(out);
}
}
| 1,718 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/KeyResponseData.java
|
/**
* Copyright (c) 2012-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.keyx;
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.io.MslEncodable;
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.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* <p>Key response data contains all the data needed to facilitate a exchange of
* session keys from the responder.</p>
*
* <p>Specific key exchange mechanisms should define their own key response data
* types.</p>
*
* <p>Key response data is represented as
* {@code
* keyresponsedata = {
* "#mandatory" : [ "mastertoken", "scheme", "keydata" ],
* "mastertoken" : mastertoken,
* "scheme" : "string",
* "keydata" : object
* }} where:
* <ul>
* <li>{@code mastertoken} is the master token associated with the session keys</li>
* <li>{@code scheme} is the key exchange scheme</li>
* <li>{@code keydata} is the scheme-specific key data</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class KeyResponseData implements MslEncodable {
/** Key master token. */
private static final String KEY_MASTER_TOKEN = "mastertoken";
/** Key key exchange scheme. */
private static final String KEY_SCHEME = "scheme";
/** Key key data. */
private static final String KEY_KEYDATA = "keydata";
/**
* Create a new key response data object with the specified key exchange
* scheme and associated master token.
*
* @param masterToken the master token.
* @param scheme the key exchange scheme.
*/
protected KeyResponseData(final MasterToken masterToken, final KeyExchangeScheme scheme) {
this.masterToken = masterToken;
this.scheme = scheme;
}
/**
* Construct a new key response data instance of the correct type from the
* provided MSL object.
*
* @param ctx MSL context.
* @param keyResponseDataMo the MSL object.
* @return the key response data concrete instance.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if unable to create the key response
* data.
* @throws MslCryptoException if there is an error verifying the they key
* response data.
* @throws MslException if the key response master token expiration
* timestamp occurs before the renewal window.
*/
public static KeyResponseData create(final MslContext ctx, final MslObject keyResponseDataMo) throws MslEncodingException, MslCryptoException, MslKeyExchangeException, MslException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
try {
// Pull the key data.
final MasterToken masterToken = new MasterToken(ctx, keyResponseDataMo.getMslObject(KEY_MASTER_TOKEN, encoder));
final String schemeName = keyResponseDataMo.getString(KEY_SCHEME);
final KeyExchangeScheme scheme = ctx.getKeyExchangeScheme(schemeName);
if (scheme == null)
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_SCHEME, schemeName);
final MslObject keyData = keyResponseDataMo.getMslObject(KEY_KEYDATA, encoder);
// Construct an instance of the concrete subclass.
final KeyExchangeFactory factory = ctx.getKeyExchangeFactory(scheme);
if (factory == null)
throw new MslKeyExchangeException(MslError.KEYX_FACTORY_NOT_FOUND, scheme.name());
return factory.createResponseData(ctx, masterToken, keyData);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keyresponsedata " + keyResponseDataMo, e);
}
}
/**
* @return the master token.
*/
public MasterToken getMasterToken() {
return masterToken;
}
/**
* @return the key exchange scheme.
*/
public KeyExchangeScheme getKeyExchangeScheme() {
return scheme;
}
/**
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the key data MSL representation.
* @throws MslEncoderException if there was an error constructing the MSL
* representation.
*/
protected abstract MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException;
/** Master token. */
private final MasterToken masterToken;
/** Key exchange scheme. */
private final KeyExchangeScheme scheme;
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_MASTER_TOKEN, masterToken);
mo.put(KEY_SCHEME, scheme.name());
mo.put(KEY_KEYDATA, getKeydata(encoder, format));
return encoder.encodeObject(mo, format);
}
/* (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 KeyResponseData)) return false;
final KeyResponseData that = (KeyResponseData)obj;
return masterToken.equals(that.masterToken) && scheme.equals(that.scheme);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return masterToken.hashCode() ^ scheme.hashCode();
}
}
| 1,719 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/KeyExchangeScheme.java
|
/**
* Copyright (c) 2012-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.keyx;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* <p>Key exchange schemes.</p>
*
* <p>The scheme name is used to uniquely identify key exchange schemes.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class KeyExchangeScheme {
/** Map of names onto schemes. */
private static Map<String,KeyExchangeScheme> schemes = new HashMap<String,KeyExchangeScheme>();
/** Asymmetric key wrapped. */
public static final KeyExchangeScheme ASYMMETRIC_WRAPPED = new KeyExchangeScheme("ASYMMETRIC_WRAPPED");
/** Diffie-Hellman exchange (Netflix SHA-384 key derivation). */
public static final KeyExchangeScheme DIFFIE_HELLMAN = new KeyExchangeScheme("DIFFIE_HELLMAN");
/** JSON web encryption ladder exchange. */
public static final KeyExchangeScheme JWE_LADDER = new KeyExchangeScheme("JWE_LADDER");
/** JSON web key ladder exchange. */
public static final KeyExchangeScheme JWK_LADDER = new KeyExchangeScheme("JWK_LADDER");
/** Symmetric key wrapped. */
public static final KeyExchangeScheme SYMMETRIC_WRAPPED = new KeyExchangeScheme("SYMMETRIC_WRAPPED");
/**
* Define a key exchange scheme with the specified name.
*
* @param name the key exchange scheme name.
*/
protected KeyExchangeScheme(final String name) {
this.name = name;
// Add this scheme to the map.
synchronized (schemes) {
schemes.put(name, this);
}
}
/**
* @param name the key exchange scheme name.
* @return the scheme identified by the specified name or {@code null} if
* there is none.
*/
public static KeyExchangeScheme getScheme(final String name) {
return schemes.get(name);
}
/**
* @return all known key exchange schemes.
*/
public static Collection<KeyExchangeScheme> values() {
return schemes.values();
}
/**
* @return the scheme identifier.
*/
public String name() {
return name;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
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 KeyExchangeScheme)) return false;
final KeyExchangeScheme that = (KeyExchangeScheme)obj;
return this.name.equals(that.name);
}
/** Scheme name. */
private final String name;
}
| 1,720 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/DiffieHellmanExchange.java
|
/**
* Copyright (c) 2012-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.keyx;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.DHPublicKeySpec;
import javax.crypto.spec.SecretKeySpec;
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.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.CryptoCache;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.SessionCryptoContext;
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;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>Diffie-Hellman key exchange.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class DiffieHellmanExchange extends KeyExchangeFactory {
/** Key Diffie-Hellman parameters ID. */
private static final String KEY_PARAMETERS_ID = "parametersid";
/** Key Diffie-Hellman public key. */
private static final String KEY_PUBLIC_KEY = "publickey";
/**
* If the provided byte array begins with one and only one null byte this
* function simply returns the original array. Otherwise a new array is
* created that is a copy of the original array with exactly one null byte
* in position zero, and this new array is returned.
*
* @param b the original array.
* @return the resulting byte array.
*/
private static byte[] correctNullBytes(final byte[] b) {
// Count the number of leading nulls.
int leadingNulls = 0;
for (int i = 0; i < b.length; ++i) {
if (b[i] != 0x00)
break;
++leadingNulls;
}
// If there is exactly one leading null, return the original array.
if (leadingNulls == 1)
return b;
// Create a copy of the non-null bytes and prepend exactly one null
// byte.
final int copyLength = b.length - leadingNulls;
final byte[] result = new byte[copyLength + 1];
result[0] = 0x00;
System.arraycopy(b, leadingNulls, result, 1, copyLength);
return result;
}
/**
* <p>Diffie-Hellman key request data. </p>
*
* <p>
* {@code {
* "#mandatory" : [ "parametersid", "publickey" ],
* "parametersid" : "string",
* "publickey" : "binary",
* }} where:
* <ul>
* <li>{@code parametersid} identifies the Diffie-Hellman paramters to use</li>
* <li>{@code publickey} the public key used to generate the shared secret</li>
* </ul>
* </p>
*/
public static class RequestData extends KeyRequestData {
/**
* Create a new Diffie-Hellman request data repository with the
* specified parameters ID and public key. The private key is also
* required but is not included in the request data.
*
* @param parametersId the parameters ID.
* @param publicKey the public key Y-value.
* @param privateKey the private key.
*/
public RequestData(final String parametersId, final BigInteger publicKey, final DHPrivateKey privateKey) {
super(KeyExchangeScheme.DIFFIE_HELLMAN);
this.parametersId = parametersId;
this.publicKey = publicKey;
this.privateKey = privateKey;
}
/**
* Create a new Diffie-Hellman request data repository from the
* provided MSL object. The private key will be unknown.
*
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the public key is invalid.
*/
public RequestData(final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
super(KeyExchangeScheme.DIFFIE_HELLMAN);
try {
parametersId = keyDataMo.getString(KEY_PARAMETERS_ID);
final byte[] publicKeyY = keyDataMo.getBytes(KEY_PUBLIC_KEY);
if (publicKeyY.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_INVALID_PUBLIC_KEY, "keydata " + keyDataMo.toString());
publicKey = new BigInteger(correctNullBytes(publicKeyY));
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo.toString(), e);
} catch (final NumberFormatException e) {
throw new MslKeyExchangeException(MslError.KEYX_INVALID_PUBLIC_KEY, "keydata " + keyDataMo.toString(), e);
}
privateKey = null;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_PARAMETERS_ID, parametersId);
final byte[] publicKeyY = publicKey.toByteArray();
mo.put(KEY_PUBLIC_KEY, correctNullBytes(publicKeyY));
return mo;
}
/**
* @return the parameters ID.
*/
public String getParametersId() {
return parametersId;
}
/**
* @return the public key Y-value.
*/
public BigInteger getPublicKey() {
return publicKey;
}
/**
* @return the private key or null if unknown (reconstructed from a
* MSL object).
*/
public DHPrivateKey getPrivateKey() {
return privateKey;
}
/*
* (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 RequestData))
return false;
final RequestData that = (RequestData)obj;
final boolean privateKeysEqual =
privateKey == that.privateKey ||
(privateKey != null && that.privateKey != null && Arrays.equals(privateKey.getEncoded(), that.privateKey.getEncoded()));
return super.equals(obj) &&
parametersId.equals(that.parametersId) &&
publicKey.equals(that.publicKey) && privateKeysEqual;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
// Private keys are optional but must be considered.
final int privateKeyHashCode = (privateKey != null) ? Arrays.hashCode(privateKey.getEncoded()) : 0;
return super.hashCode() ^ parametersId.hashCode() ^
publicKey.hashCode() ^ privateKeyHashCode;
}
/** Diffie-Hellman parameters ID. */
private final String parametersId;
/** Diffie-Hellman public key Y-value. */
private final BigInteger publicKey;
/** Diffie-Hellman private key. */
private final DHPrivateKey privateKey;
}
/**
* <p>Diffie-Hellman key response data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "parametersid", "publickey" ],
* "parametersid" : "string",
* "publickey" : "binary",
* }} where:
* <ul>
* <li>{@code parametersid} identifies the Diffie-Hellman paramters to use</li>
* <li>{@code publickey} the public key used to generate the shared secret</li>
* </ul>
* </p>
*/
public static class ResponseData extends KeyResponseData {
/**
* Create a new Diffie-Hellman response data repository with the
* provided master token, specified parameters ID and public key.
*
* @param masterToken the master token.
* @param parametersId the parameters ID.
* @param publicKey the public key Y-value.
*/
public ResponseData(final MasterToken masterToken, final String parametersId, final BigInteger publicKey) {
super(masterToken, KeyExchangeScheme.DIFFIE_HELLMAN);
this.parametersId = parametersId;
this.publicKey = publicKey;
}
/**
* Create a new Diffie-Hellman response data repository with the
* provided master token from the provided MSL object.
*
* @param masterToken the master token.
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the public key is invalid.
*/
public ResponseData(final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
super(masterToken, KeyExchangeScheme.DIFFIE_HELLMAN);
try {
parametersId = keyDataMo.getString(KEY_PARAMETERS_ID);
final byte[] publicKeyY = keyDataMo.getBytes(KEY_PUBLIC_KEY);
if (publicKeyY.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_INVALID_PUBLIC_KEY, "keydata " + keyDataMo);
publicKey = new BigInteger(correctNullBytes(publicKeyY));
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
} catch (final NumberFormatException e) {
throw new MslKeyExchangeException(MslError.KEYX_INVALID_PUBLIC_KEY, "keydata " + keyDataMo, e);
}
}
/**
* @return the parameters ID.
*/
public String getParametersId() {
return parametersId;
}
/**
* @return the public key Y-value.
*/
public BigInteger getPublicKey() {
return publicKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_PARAMETERS_ID, parametersId);
final byte[] publicKeyY = publicKey.toByteArray();
mo.put(KEY_PUBLIC_KEY, correctNullBytes(publicKeyY));
return mo;
}
/*
* (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 ResponseData))
return false;
final ResponseData that = (ResponseData) obj;
return super.equals(obj) &&
parametersId.equals(that.parametersId) &&
publicKey.equals(that.publicKey);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ parametersId.hashCode() ^ publicKey.hashCode();
}
/** Diffie-Hellman parameters ID. */
private final String parametersId;
/** Diffie-Hellman public key. */
private final BigInteger publicKey;
}
/**
* Container struct for session keys.
*/
private static class SessionKeys {
/**
* @param encryptionKey the encryption key.
* @param hmacKey the HMAC key.
*/
public SessionKeys(final SecretKey encryptionKey, final SecretKey hmacKey) {
this.encryptionKey = encryptionKey;
this.hmacKey = hmacKey;
}
/** Encryption key. */
public final SecretKey encryptionKey;
/** HMAC key. */
public final SecretKey hmacKey;
}
/**
* Derives the encryption and HMAC session keys from a Diffie-Hellman
* shared secret.
*
* @param publicKey Diffie-Hellman public key.
* @param privateKey Diffie-Hellman private key.
* @param params Diffie-Hellman parameter specification.
* @return the derived session keys.
*/
private static SessionKeys deriveSessionKeys(final PublicKey publicKey, final PrivateKey privateKey, final DHParameterSpec params) {
// Compute Diffie-Hellman shared secret.
final byte[] sharedSecret;
try {
final KeyAgreement agreement = CryptoCache.getKeyAgreement("DiffieHellman");
agreement.init(privateKey, params);
agreement.doPhase(publicKey, true);
sharedSecret = correctNullBytes(agreement.generateSecret());
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidKeyException e) {
throw new MslInternalException("Diffie-Hellman private key or generated public key rejected by Diffie-Hellman key agreement.", e);
} catch (final InvalidAlgorithmParameterException e) {
throw new MslInternalException("Diffie-Hellman algorithm parameters rejected by Diffie-Hellman key agreement.", e);
}
// Derive encryption and HMAC keys.
final MessageDigest sha384;
try {
sha384 = CryptoCache.getMessageDigest("SHA-384");
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("SHA-384 algorithm not found.", e);
}
final byte[] hash = sha384.digest(sharedSecret);
final byte[] kcedata = new byte[128 / Byte.SIZE];
System.arraycopy(hash, 0, kcedata, 0, kcedata.length);
final byte[] kchdata = new byte[256 / Byte.SIZE];
System.arraycopy(hash, kcedata.length, kchdata, 0, kchdata.length);
// Return encryption and HMAC keys.
final SecretKey encryptionKey = new SecretKeySpec(kcedata, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(kchdata, JcaAlgorithm.HMAC_SHA256);
return new SessionKeys(encryptionKey, hmacKey);
}
/**
* Create a new Diffie-Hellman key exchange factory.
*
* @param params Diffie-Hellman parameters.
* @param authutils authentication utilities.
*/
public DiffieHellmanExchange(final DiffieHellmanParameters params, final AuthenticationUtils authutils) {
super(KeyExchangeScheme.DIFFIE_HELLMAN);
this.params = params;
this.authutils = authutils;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createRequestData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslKeyExchangeException, MslCryptoException {
return new RequestData(keyRequestMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createResponseData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
return new ResponseData(masterToken, keyDataMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData) keyRequestData;
// If the master token was not issued by the local entity then we
// should not be generating a key response for it.
if (!masterToken.isVerified())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
// Verify the scheme is permitted.
final String identity = masterToken.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setMasterToken(masterToken);
// Load matching Diffie-Hellman parameter specification.
final String parametersId = request.getParametersId();
final DHParameterSpec paramSpec = params.getParameterSpec(parametersId);
if (paramSpec == null)
throw new MslKeyExchangeException(MslError.UNKNOWN_KEYX_PARAMETERS_ID, parametersId);
// Reconstitute request public key.
final PublicKey requestPublicKey;
try {
final KeyFactory factory = CryptoCache.getKeyFactory("DiffieHellman");
final BigInteger y = request.getPublicKey();
final DHPublicKeySpec publicKeySpec = new DHPublicKeySpec(y, paramSpec.getP(), paramSpec.getG());
requestPublicKey = factory.generatePublic(publicKeySpec);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidKeySpecException e) {
throw new MslInternalException("Diffie-Hellman public key specification rejected by Diffie-Hellman key factory.", e);
}
// Generate public/private key pair.
final DHPublicKey responsePublicKey;
final DHPrivateKey responsePrivateKey;
try {
final KeyPairGenerator generator = CryptoCache.getKeyPairGenerator("DH");
generator.initialize(paramSpec);
final KeyPair keyPair = generator.generateKeyPair();
responsePublicKey = (DHPublicKey)keyPair.getPublic();
responsePrivateKey = (DHPrivateKey)keyPair.getPrivate();
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidAlgorithmParameterException e) {
throw new MslInternalException("Diffie-Hellman algorithm parameters rejected by Diffie-Hellman key agreement.", e);
}
// Construct encryption and HMAC keys.
final SessionKeys sessionKeys = deriveSessionKeys(requestPublicKey, responsePrivateKey, paramSpec);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.renewMasterToken(ctx, masterToken, sessionKeys.encryptionKey, sessionKeys.hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, parametersId, responsePublicKey.getY());
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final EntityAuthenticationData entityAuthData) throws MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = entityAuthData.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setEntityAuthenticationData(entityAuthData);
// Load matching Diffie-Hellman parameter specification.
final String parametersId = request.getParametersId();
final DHParameterSpec paramSpec = params.getParameterSpec(parametersId);
if (paramSpec == null)
throw new MslKeyExchangeException(MslError.UNKNOWN_KEYX_PARAMETERS_ID, parametersId).setEntityAuthenticationData(entityAuthData);
// Reconstitute request public key.
final PublicKey requestPublicKey;
try {
final KeyFactory factory = CryptoCache.getKeyFactory("DiffieHellman");
final BigInteger y = request.getPublicKey();
final DHPublicKeySpec publicKeySpec = new DHPublicKeySpec(y, paramSpec.getP(), paramSpec.getG());
requestPublicKey = factory.generatePublic(publicKeySpec);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidKeySpecException e) {
throw new MslInternalException("Diffie-Hellman public key specification rejected by Diffie-Hellman key factory.", e);
}
// Generate public/private key pair.
final DHPublicKey responsePublicKey;
final DHPrivateKey responsePrivateKey;
try {
final KeyPairGenerator generator = KeyPairGenerator.getInstance("DH");
generator.initialize(paramSpec);
final KeyPair keyPair = generator.generateKeyPair();
responsePublicKey = (DHPublicKey)keyPair.getPublic();
responsePrivateKey = (DHPrivateKey)keyPair.getPrivate();
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidAlgorithmParameterException e) {
throw new MslInternalException("Diffie-Hellman algorithm parameters rejected by Diffie-Hellman key agreement.", e);
}
// Construct encryption and HMAC keys.
final SessionKeys sessionKeys = deriveSessionKeys(requestPublicKey, responsePrivateKey, paramSpec);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken masterToken = tokenFactory.createMasterToken(ctx, entityAuthData, sessionKeys.encryptionKey, sessionKeys.hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext;
try {
cryptoContext = new SessionCryptoContext(ctx, masterToken);
} catch (final MslMasterTokenException e) {
throw new MslInternalException("Master token constructed by token factory is not trusted.", e);
}
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(masterToken, parametersId, responsePublicKey.getY());
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.keyx.KeyResponseData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
if (!(keyResponseData instanceof ResponseData))
throw new MslInternalException("Key response data " + keyResponseData.getClass().getName() + " was not created by this factory.");
final ResponseData response = (ResponseData)keyResponseData;
// Verify response matches request.
final String requestParametersId = request.getParametersId();
final String responseParametersId = response.getParametersId();
if (!requestParametersId.equals(responseParametersId))
throw new MslKeyExchangeException(MslError.KEYX_RESPONSE_REQUEST_MISMATCH, "request " + requestParametersId + "; response " + responseParametersId).setMasterToken(masterToken);
// Reconstitute response public key.
final DHPrivateKey privateKey = request.getPrivateKey();
if (privateKey == null)
throw new MslKeyExchangeException(MslError.KEYX_PRIVATE_KEY_MISSING, "request Diffie-Hellman private key").setMasterToken(masterToken);
final DHParameterSpec params = privateKey.getParams();
final PublicKey publicKey;
try {
final KeyFactory factory = CryptoCache.getKeyFactory("DiffieHellman");
final BigInteger y = response.getPublicKey();
final DHPublicKeySpec publicKeySpec = new DHPublicKeySpec(y, params.getP(), params.getG());
publicKey = factory.generatePublic(publicKeySpec);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidKeySpecException e) {
throw new MslKeyExchangeException(MslError.KEYX_INVALID_PUBLIC_KEY, "Diffie-Hellman public key specification rejected by Diffie-Hellman key factory.", e);
}
// Create crypto context.
final String identity = ctx.getEntityAuthenticationData(null).getIdentity();
final SessionKeys sessionKeys = deriveSessionKeys(publicKey, privateKey, params);
final MasterToken responseMasterToken = response.getMasterToken();
return new SessionCryptoContext(ctx, responseMasterToken, identity, sessionKeys.encryptionKey, sessionKeys.hmacKey);
}
/** Diffie-Hellman parameters. */
private final DiffieHellmanParameters params;
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 1,721 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/KeyRequestData.java
|
/**
* Copyright (c) 2012-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.keyx;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.io.MslEncodable;
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.util.MslContext;
/**
* <p>Key request data contains all the data needed to facilitate a exchange of
* session keys with the requesting entity.</p>
*
* <p>Specific key exchange mechanisms should define their own key request data
* types.</p>
*
* <p>Key request data is represented as
* {@code
* keyrequestdata = {
* "#mandatory" : [ "scheme", "keydata" ],
* "scheme" : "string",
* "keydata" : object
* }} where:
* <ul>
* <li>{@code scheme} is the key exchange scheme</li>
* <li>{@code keydata} is the scheme-specific key data</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class KeyRequestData implements MslEncodable {
/** Key key exchange scheme. */
private static final String KEY_SCHEME = "scheme";
/** Key key request data. */
private static final String KEY_KEYDATA = "keydata";
/**
* Create a new key request data object with the specified key exchange
* scheme.
*
* @param scheme the key exchange scheme.
*/
protected KeyRequestData(final KeyExchangeScheme scheme) {
this.scheme = scheme;
}
/**
* Construct a new key request data instance of the correct type from the
* provided MSL object.
*
* @param ctx MSL context.
* @param keyRequestDataMo the MSL object.
* @return the key request data concrete instance.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException if there is an error verifying the key
* request data.
* @throws MslEntityAuthException if the entity authentication data could
* not be created.
* @throws MslKeyExchangeException if unable to create the key request
* data.
*/
public static KeyRequestData create(final MslContext ctx, final MslObject keyRequestDataMo) throws MslEncodingException, MslCryptoException, MslEntityAuthException, MslKeyExchangeException {
try {
// Pull the key data.
final String schemeName = keyRequestDataMo.getString(KEY_SCHEME);
final KeyExchangeScheme scheme = ctx.getKeyExchangeScheme(schemeName);
if (scheme == null)
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_SCHEME, schemeName);
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject keyData = keyRequestDataMo.getMslObject(KEY_KEYDATA, encoder);
// Construct an instance of the concrete subclass.
final KeyExchangeFactory keyFactory = ctx.getKeyExchangeFactory(scheme);
if (keyFactory == null)
throw new MslKeyExchangeException(MslError.KEYX_FACTORY_NOT_FOUND, scheme.name());
return keyFactory.createRequestData(ctx, keyData);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keyrequestdata " + keyRequestDataMo, e);
}
}
/**
* @return the key exchange scheme.
*/
public KeyExchangeScheme getKeyExchangeScheme() {
return scheme;
}
/**
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the key data MSL representation.
* @throws MslEncoderException if there was an error constructing the MSL
* representation.
*/
protected abstract MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException;
/** Key exchange scheme. */
private final KeyExchangeScheme scheme;
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public final byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_SCHEME, scheme.name());
mo.put(KEY_KEYDATA, getKeydata(encoder, format));
return encoder.encodeObject(mo, format);
}
/* (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 KeyRequestData)) return false;
final KeyRequestData that = (KeyRequestData)obj;
return scheme.equals(that.scheme);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return scheme.hashCode();
}
}
| 1,722 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/JsonWebEncryptionLadderExchange.java
|
/**
* Copyright (c) 2013-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.keyx;
import java.nio.charset.Charset;
import java.util.Arrays;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
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.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.AesKwCryptoContext;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.CekCryptoContext;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.Encryption;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.Format;
import com.netflix.msl.crypto.JsonWebKey;
import com.netflix.msl.crypto.JsonWebKey.Algorithm;
import com.netflix.msl.crypto.JsonWebKey.Usage;
import com.netflix.msl.crypto.SessionCryptoContext;
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.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>JSON Web Encryption ladder key exchange.</p>
*
* <p>The key ladder consists of a symmetric wrapping key used to protect the
* session keys. The wrapping key is only permitted to wrap and unwrap data. It
* cannot be used for encrypt/decrypt or sign/verify operations.</p>
*
* <p>The wrapping key is protected by wrapping it with a known common key
* (e.g. preshared keys) or the previously used wrapping key. The previous
* wrapping key must be provided by the requesting entity in the form found in
* the response data.</p>
*
* <p>The wrapping key is always an AES-128 key for AES key wrap/unwrap.</p>
*
* <p>This key exchange scheme does not provide perfect forward secrecy and
* should only be used if necessary to satisfy other security requirements.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class JsonWebEncryptionLadderExchange extends KeyExchangeFactory {
/** Encoding charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/** Wrapping key wrap mechanism. */
public enum Mechanism {
/** Wrapping key wrapped by PSK (AES-128 key wrap). */
PSK,
/** Wrapping key wrapped by previous wrapping key (AES-128 key wrap). */
WRAP,
}
/**
* <p>JSON Web Encryption ladder key request data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "mechanism" ],
* "mechanism" : "enum(PSK|MGK|WRAP)",
* "wrapdata" : "binary",
* }} where:
* <ul>
* <li>{@code mechanism} identifies the mechanism for wrapping and unwrapping the wrapping key</li>
* <li>{@code wrapdata} the wrapping data for the previous wrapping key</li>
* </ul></p>
*/
public static class RequestData extends KeyRequestData {
/** Key wrap key wrapping mechanism. */
private static final String KEY_MECHANISM = "mechanism";
/** Key wrap data. */
private static final String KEY_WRAPDATA = "wrapdata";
/**
* <p>Create a new JSON Web Encryption ladder key request data instance
* with the specified mechanism and wrapping key data.</p>
*
* <p>Arguments not applicable to the specified mechanism are
* ignored.</p>
*
* @param mechanism the wrap key wrapping mechanism.
* @param wrapdata the wrap data for reconstructing the previous
* wrapping key. May be null if the mechanism does not use the
* previous wrapping key.
* @throws MslInternalException if the mechanism requires wrap data and
* the required argument is null.
*/
public RequestData(final Mechanism mechanism, final byte[] wrapdata) {
super(KeyExchangeScheme.JWE_LADDER);
this.mechanism = mechanism;
switch (mechanism) {
case WRAP:
if (wrapdata == null)
throw new MslInternalException("Previous wrapping key based key exchange requires the previous wrapping key data and ID.");
this.wrapdata = wrapdata;
break;
default:
this.wrapdata = null;
break;
}
}
/**
* Create a new JSON Web Encryption ladder key request data instance
* from the provided MSL object.
*
* @param keyRequestMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException the wrapped key data cannot be verified
* or decrypted, or the specified mechanism is not supported.
* @throws MslKeyExchangeException if the specified mechanism is not
* recognized or the wrap data is missing or invalid.
*/
public RequestData(final MslObject keyRequestMo) throws MslCryptoException, MslKeyExchangeException, MslEncodingException {
super(KeyExchangeScheme.JWE_LADDER);
try {
final String mechanismName = keyRequestMo.getString(KEY_MECHANISM);
try {
mechanism = Mechanism.valueOf(mechanismName);
} catch (final IllegalArgumentException e) {
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_MECHANISM, mechanismName, e);
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyRequestMo, e);
}
try {
switch (mechanism) {
case PSK:
{
wrapdata = null;
break;
}
case WRAP:
{
wrapdata = keyRequestMo.getBytes(KEY_WRAPDATA);
if (wrapdata.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING, "keydata " + keyRequestMo);
break;
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyRequestMo, e);
}
}
/**
* @return the wrap key wrapping mechanism.
*/
public Mechanism getMechanism() {
return mechanism;
}
/**
* @return the previous wrapping key data or null if not applicable.
*/
public byte[] getWrapdata() {
return wrapdata;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_MECHANISM, mechanism.name());
if (wrapdata != null) mo.put(KEY_WRAPDATA, wrapdata);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof RequestData)) return false;
final RequestData that = (RequestData)obj;
final boolean wrapdataEqual = Arrays.equals(wrapdata, that.wrapdata);
return super.equals(obj) &&
mechanism.equals(that.mechanism) &&
wrapdataEqual;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#hashCode()
*/
@Override
public int hashCode() {
final int wrapdataHashCode = (wrapdata != null) ? Arrays.hashCode(wrapdata) : 0;
return super.hashCode() ^
mechanism.hashCode() ^
wrapdataHashCode;
}
/** Wrap key wrapping mechanism. */
private final Mechanism mechanism;
/** Wrap data. */
private final byte[] wrapdata;
}
/**
* <p>JSON Web Encryption ladder key response data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "wrapkey", "wrapdata", "encryptionkey", "hmackey" ],
* "wrapkey" : "binary",
* "wrapdata" : "binary",
* "encryptionkey" : "binary",
* "hmackey" : "binary",
* }} where:
* <ul>
* <li>{@code wrapkey} the new wrapping key in JWE format, wrapped by the wrapping key</li>
* <li>{@code wrapdata} the wrapping key data for use in subsequent key request data</li>
* <li>{@code encryptionkey} the session encryption key in JWE format, wrapped with the new wrapping key</li>
* <li>{@code hmackey} the session HMAC key in JWE format, wrapped with the new wrapping key</li>
* </ul></p>
*/
public static class ResponseData extends KeyResponseData {
/** Key wrapping key. */
private static final String KEY_WRAP_KEY = "wrapkey";
/** Key wrapping key data. */
private static final String KEY_WRAPDATA = "wrapdata";
/** Key encrypted encryption key. */
private static final String KEY_ENCRYPTION_KEY = "encryptionkey";
/** Key encrypted HMAC key. */
private static final String KEY_HMAC_KEY = "hmackey";
/**
* Create a new JSON Web Encryption ladder key response data instance
* with the provided master token and wrapped keys.
*
* @param masterToken the master token.
* @param wrapKey the wrapped wrap key.
* @param wrapdata the wrap data for reconstructing the wrap key.
* @param encryptionKey the wrap key wrapped encryption key.
* @param hmacKey the wrap key wrapped HMAC key.
*/
public ResponseData(final MasterToken masterToken, final byte[] wrapKey, final byte[] wrapdata, final byte[] encryptionKey, final byte[] hmacKey) {
super(masterToken, KeyExchangeScheme.JWE_LADDER);
this.wrapKey = wrapKey;
this.wrapdata = wrapdata;
this.encryptionKey = encryptionKey;
this.hmacKey = hmacKey;
}
/**
* Create a new JSON Web Encryption ladder key response data instance
* with the provided master token from the provided MSL object.
*
* @param masterToken the master token.
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the mechanism is not recognized,
* any of the keys are invalid, or if the wrap data is invalid.
*/
public ResponseData(final MasterToken masterToken, final MslObject keyDataMo) throws MslKeyExchangeException, MslEncodingException {
super(masterToken, KeyExchangeScheme.JWE_LADDER);
try {
wrapKey = keyDataMo.getBytes(KEY_WRAP_KEY);
wrapdata = keyDataMo.getBytes(KEY_WRAPDATA);
encryptionKey = keyDataMo.getBytes(KEY_ENCRYPTION_KEY);
hmacKey = keyDataMo.getBytes(KEY_HMAC_KEY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
}
}
/**
* @return the session key wrapping key.
*/
public byte[] getWrapKey() {
return wrapKey;
}
/**
* @return the session key wrapping key data.
*/
public byte[] getWrapdata() {
return wrapdata;
}
/**
* @return the wrapped session encryption key.
*/
public byte[] getEncryptionKey() {
return encryptionKey;
}
/**
* @return the wrapped session HMAC key.
*/
public byte[] getHmacKey() {
return hmacKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) {
final MslObject mo = encoder.createObject();
mo.put(KEY_WRAP_KEY, wrapKey);
mo.put(KEY_WRAPDATA, wrapdata);
mo.put(KEY_ENCRYPTION_KEY, encryptionKey);
mo.put(KEY_HMAC_KEY, hmacKey);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof ResponseData)) return false;
final ResponseData that = (ResponseData)obj;
return super.equals(obj) &&
Arrays.equals(wrapKey, that.wrapKey) &&
Arrays.equals(wrapdata, that.wrapdata) &&
Arrays.equals(encryptionKey, that.encryptionKey) &&
Arrays.equals(hmacKey, that.hmacKey);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^
Arrays.hashCode(wrapKey) ^
Arrays.hashCode(wrapdata) ^
Arrays.hashCode(encryptionKey) ^
Arrays.hashCode(hmacKey);
}
/** Wrapped wrap key. */
private final byte[] wrapKey;
/** Wrap data. */
private final byte[] wrapdata;
/** Wrapped encryption key. */
private final byte[] encryptionKey;
/** Wrapped HMAC key. */
private final byte[] hmacKey;
}
/**
* Create the crypto context identified by the mechanism.
*
* @param ctx MSL context.
* @param mechanism the wrap key wrapping mechanism.
* @param wrapdata the wrap key previous wrapping key data. May be null.
* @param identity the entity identity.
* @return the crypto context.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslKeyExchangeException if the mechanism is unsupported.
* @throws MslEntityAuthException if there is a problem with the entity
* identity.
*/
private static ICryptoContext createCryptoContext(final MslContext ctx, final Mechanism mechanism, final byte[] wrapdata, final String identity) throws MslKeyExchangeException, MslCryptoException, MslEntityAuthException {
switch (mechanism) {
case PSK:
{
final EntityAuthenticationData authdata = new PresharedAuthenticationData(identity);
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(EntityAuthenticationScheme.PSK);
if (factory == null)
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
final ICryptoContext cryptoContext = factory.getCryptoContext(ctx, authdata);
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(cryptoContext);
return new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
}
case WRAP:
{
final ICryptoContext cryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapBytes = cryptoContext.unwrap(wrapdata, encoder);
if (wrapBytes == null || wrapBytes.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(wrapKey);
return new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
}
default:
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
}
/**
* Create a new JSON Web Encryption ladder key exchange factory.
*
* @param repository the wrapping key crypto context repository.
* @param authutils authentication utilities.
*/
public JsonWebEncryptionLadderExchange(final WrapCryptoContextRepository repository, final AuthenticationUtils authutils) {
super(KeyExchangeScheme.JWE_LADDER);
this.repository = repository;
this.authutils = authutils;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createRequestData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslKeyExchangeException, MslCryptoException {
return new RequestData(keyRequestMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createResponseData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
return new ResponseData(masterToken, keyDataMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException, MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// If the master token was not issued by the local entity then we
// should not be generating a key response for it.
if (!masterToken.isVerified())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
// Verify the scheme is permitted.
final String identity = masterToken.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setMasterToken(masterToken);
// Create random AES-128 wrapping key with a random key ID.
final String wrapKeyId = String.valueOf(ctx.getRandom().nextLong());
final byte[] wrapBytes = new byte[16];
ctx.getRandom().nextBytes(wrapBytes);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
// Create the wrap data.
final ICryptoContext mslCryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapdata = mslCryptoContext.wrap(wrapBytes, encoder, format);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Grab the request data.
final Mechanism mechanism = request.getMechanism();
final byte[] prevWrapdata = request.getWrapdata();
// Wrap wrapping key using specified wrapping key.
final JsonWebKey wrapJwk = new JsonWebKey(Usage.wrap, Algorithm.A128KW, false, wrapKeyId, wrapKey);
final byte[] wrapJwkBytes = wrapJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final ICryptoContext wrapKeyCryptoContext = createCryptoContext(ctx, mechanism, prevWrapdata, identity);
final byte[] wrappedWrapJwk = wrapKeyCryptoContext.wrap(wrapJwkBytes, encoder, format);
// Wrap session keys inside JSON Web Key objects with the wrapping key.
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(wrapKey);
final ICryptoContext wrapCryptoContext = new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
final JsonWebKey encryptionJwk = new JsonWebKey(Usage.enc, Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(Usage.sig, Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] wrappedEncryptionJwk = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
final byte[] wrappedHmacJwk = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.renewMasterToken(ctx, masterToken, encryptionKey, hmacKey, null);
// Create session crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, wrappedWrapJwk, wrapdata, wrappedEncryptionJwk, wrappedHmacJwk);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData,final EntityAuthenticationData entityAuthData) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslEntityAuthException, MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = entityAuthData.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication Sscheme for entity not permitted " + identity + ":" + this.getScheme()).setEntityAuthenticationData(entityAuthData);
// Create random AES-128 wrapping key with a random key ID.
final String wrapKeyId = String.valueOf(ctx.getRandom().nextLong());
final byte[] wrapBytes = new byte[16];
ctx.getRandom().nextBytes(wrapBytes);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
// Create the wrap data.
final ICryptoContext mslCryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapdata = mslCryptoContext.wrap(wrapBytes, encoder, format);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Grab the request data.
final Mechanism mechanism = request.getMechanism();
final byte[] prevWrapdata = request.getWrapdata();
// Wrap wrapping key using specified wrapping key.
final JsonWebKey wrapJwk = new JsonWebKey(Usage.wrap, Algorithm.A128KW, false, wrapKeyId, wrapKey);
final byte[] wrapJwkBytes = wrapJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final ICryptoContext wrapKeyCryptoContext = createCryptoContext(ctx, mechanism, prevWrapdata, identity);
final byte[] wrappedWrapJwk = wrapKeyCryptoContext.wrap(wrapJwkBytes, encoder, format);
// Wrap session keys inside JSON Web Key objects with the wrapping key.
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(wrapKey);
final ICryptoContext wrapCryptoContext = new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
final JsonWebKey encryptionJwk = new JsonWebKey(Usage.enc, Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(Usage.sig, Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] wrappedEncryptionJwk = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
final byte[] wrappedHmacJwk = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.createMasterToken(ctx, entityAuthData, encryptionKey, hmacKey, null);
// Create session crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, wrappedWrapJwk, wrapdata, wrappedEncryptionJwk, wrappedHmacJwk);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.keyx.KeyResponseData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
if (!(keyResponseData instanceof ResponseData))
throw new MslInternalException("Key response data " + keyResponseData.getClass().getName() + " was not created by this factory.");
final ResponseData response = (ResponseData)keyResponseData;
// Unwrap new wrapping key.
final Mechanism mechanism = request.getMechanism();
final byte[] requestWrapdata = request.getWrapdata();
final EntityAuthenticationData entityAuthData = ctx.getEntityAuthenticationData(null);
final String identity = entityAuthData.getIdentity();
final ICryptoContext wrapKeyCryptoContext;
switch (mechanism) {
case PSK:
{
final EntityAuthenticationData authdata = new PresharedAuthenticationData(identity);
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(EntityAuthenticationScheme.PSK);
if (factory == null)
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name()).setEntityAuthenticationData(entityAuthData);
final ICryptoContext cryptoContext = factory.getCryptoContext(ctx, authdata);
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(cryptoContext);
wrapKeyCryptoContext = new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
break;
}
case WRAP:
{
wrapKeyCryptoContext = repository.getCryptoContext(requestWrapdata);
if (wrapKeyCryptoContext == null)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING, Base64.encode(requestWrapdata)).setEntityAuthenticationData(entityAuthData);
break;
}
default:
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name()).setEntityAuthenticationData(entityAuthData);
}
// Unwrap wrapping key.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] unwrappedWrapJwk = wrapKeyCryptoContext.unwrap(response.getWrapKey(), encoder);
final JsonWebKey wrapJwk;
try {
final MslObject wrapJwkMo = encoder.parseObject(unwrappedWrapJwk);
wrapJwk = new JsonWebKey(wrapJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedWrapJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
final SecretKey wrapKey = wrapJwk.getSecretKey();
// Unwrap session keys with wrapping key.
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(wrapKey);
final ICryptoContext unwrapCryptoContext = new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
final byte[] unwrappedEncryptionJwk = unwrapCryptoContext.unwrap(response.getEncryptionKey(), encoder);
final byte[] unwrappedHmacJwk = unwrapCryptoContext.unwrap(response.getHmacKey(), encoder);
final JsonWebKey encryptionJwk;
try {
final MslObject encryptionJwkMo = encoder.parseObject(unwrappedEncryptionJwk);
encryptionJwk = new JsonWebKey(encryptionJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedEncryptionJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
final JsonWebKey hmacJwk;
try {
final MslObject hmacJwkMo = encoder.parseObject(unwrappedHmacJwk);
hmacJwk = new JsonWebKey(hmacJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedHmacJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
// Deliver wrap data to wrap key repository.
final byte[] wrapdata = response.getWrapdata();
repository.addCryptoContext(wrapdata, unwrapCryptoContext);
if (requestWrapdata != null)
repository.removeCryptoContext(requestWrapdata);
// Create crypto context.
final MasterToken responseMasterToken = response.getMasterToken();
final SecretKey encryptionKey = encryptionJwk.getSecretKey();
final SecretKey hmacKey = hmacJwk.getSecretKey();
return new SessionCryptoContext(ctx, responseMasterToken, identity, encryptionKey, hmacKey);
}
/** Wrapping keys crypto context repository. */
private final WrapCryptoContextRepository repository;
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 1,723 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/JsonWebKeyLadderExchange.java
|
/**
* Copyright (c) 2013-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.keyx;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
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.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.CryptoCache;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.JsonWebKey;
import com.netflix.msl.crypto.JsonWebKey.Algorithm;
import com.netflix.msl.crypto.JsonWebKey.KeyOp;
import com.netflix.msl.crypto.SessionCryptoContext;
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.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>JSON Web Key ladder key exchange.</p>
*
* <p>The key ladder consists of a symmetric wrapping key used to protect the
* session keys. The wrapping key is only permitted to wrap and unwrap data. It
* cannot be used for encrypt/decrypt or sign/verify operations.</p>
*
* <p>The wrapping key is protected by wrapping it with a known common key
* (e.g. preshared keys) or the previously used wrapping key. The previous
* wrapping key must be provided by the requesting entity in the form found in
* the response data.</p>
*
* <p>The wrapping key is always an AES-128 key for AES key wrap/unwrap.</p>
*
* <p>This key exchange scheme does not provide perfect forward secrecy and
* should only be used if necessary to satisfy other security requirements.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class JsonWebKeyLadderExchange extends KeyExchangeFactory {
/** Encoding charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/** Dummy wrapping key ID. */
private static final String WRAP_KEY_ID = "wrapKeyId";
/** Encrypt/decrypt key operations. */
private static final Set<KeyOp> ENCRYPT_DECRYPT = new HashSet<KeyOp>(Arrays.asList(KeyOp.encrypt, KeyOp.decrypt));
/** Wrap/unwrap key operations. */
private static final Set<KeyOp> WRAP_UNWRAP = new HashSet<KeyOp>(Arrays.asList(KeyOp.wrapKey, KeyOp.unwrapKey));
/** Sign/verify key operations. */
private static final Set<KeyOp> SIGN_VERIFY = new HashSet<KeyOp>(Arrays.asList(KeyOp.sign, KeyOp.verify));
/** Wrapping key wrap mechanism. */
public enum Mechanism {
/** Wrapping key wrapped by PSK (AES-128 key wrap). */
PSK,
/** Wrapping key wrapped by previous wrapping key (AES-128 key wrap). */
WRAP,
}
/**
* <p>JSON Web Key ladder key request data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "mechanism" ],
* "mechanism" : "enum(PSK|MGK|WRAP)",
* "wrapdata" : "binary",
* }} where:
* <ul>
* <li>{@code mechanism} identifies the mechanism for wrapping and unwrapping the wrapping key</li>
* <li>{@code wrapdata} the wrapping data for the previous wrapping key</li>
* </ul></p>
*/
public static class RequestData extends KeyRequestData {
/** Key wrap key wrapping mechanism. */
private static final String KEY_MECHANISM = "mechanism";
/** Key wrap data. */
private static final String KEY_WRAPDATA = "wrapdata";
/**
* <p>Create a new JSON Web Key ladder key request data instance
* with the specified mechanism and wrapping key data.</p>
*
* <p>Arguments not applicable to the specified mechanism are
* ignored.</p>
*
* @param mechanism the wrap key wrapping mechanism.
* @param wrapdata the wrap data for reconstructing the previous
* wrapping key. May be null if the mechanism does not use the
* previous wrapping key.
* @throws MslInternalException if the mechanism requires wrap data and
* the required argument is null.
*/
public RequestData(final Mechanism mechanism, final byte[] wrapdata) {
super(KeyExchangeScheme.JWK_LADDER);
this.mechanism = mechanism;
switch (mechanism) {
case WRAP:
if (wrapdata == null)
throw new MslInternalException("Previous wrapping key based key exchange requires the previous wrapping key data and ID.");
this.wrapdata = wrapdata;
break;
default:
this.wrapdata = null;
break;
}
}
/**
* Create a new JSON Web Key ladder key request data instance
* from the provided MSL object.
*
* @param keyRequestMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException the wrapped key data cannot be verified
* or decrypted, or the specified mechanism is not supported.
* @throws MslKeyExchangeException if the specified mechanism is not
* recognized or the wrap data is missing or invalid.
*/
public RequestData(final MslObject keyRequestMo) throws MslCryptoException, MslKeyExchangeException, MslEncodingException {
super(KeyExchangeScheme.JWK_LADDER);
try {
final String mechanismName = keyRequestMo.getString(KEY_MECHANISM);
try {
mechanism = Mechanism.valueOf(mechanismName);
} catch (final IllegalArgumentException e) {
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_MECHANISM, mechanismName, e);
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyRequestMo, e);
}
try {
switch (mechanism) {
case PSK:
{
wrapdata = null;
break;
}
case WRAP:
{
wrapdata = keyRequestMo.getBytes(KEY_WRAPDATA);
if (wrapdata.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING, "keydata " + keyRequestMo);
break;
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyRequestMo, e);
}
}
/**
* @return the wrap key wrapping mechanism.
*/
public Mechanism getMechanism() {
return mechanism;
}
/**
* @return the previous wrapping key data or null if not applicable.
*/
public byte[] getWrapdata() {
return wrapdata;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_MECHANISM, mechanism.name());
if (wrapdata != null) mo.put(KEY_WRAPDATA, wrapdata);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof RequestData)) return false;
final RequestData that = (RequestData)obj;
final boolean wrapdataEqual = Arrays.equals(wrapdata, that.wrapdata);
return super.equals(obj) &&
mechanism.equals(that.mechanism) &&
wrapdataEqual;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#hashCode()
*/
@Override
public int hashCode() {
final int wrapdataHashCode = (wrapdata != null) ? Arrays.hashCode(wrapdata) : 0;
return super.hashCode() ^
mechanism.hashCode() ^
wrapdataHashCode;
}
/** Wrap key wrapping mechanism. */
private final Mechanism mechanism;
/** Wrap data. */
private final byte[] wrapdata;
}
/**
* <p>JSON Web Key ladder key response data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "wrapkey", "wrapdata", "encryptionkey", "hmackey" ],
* "wrapkey" : "binary",
* "wrapdata" : "binary",
* "encryptionkey" : "binary",
* "hmackey" : "binary",
* }} where:
* <ul>
* <li>{@code wrapkey} the new wrapping key in JWK format, wrapped by the wrapping key</li>
* <li>{@code wrapdata} the wrapping key data for use in subsequent key request data</li>
* <li>{@code encryptionkey} the session encryption key in JWK format, wrapped with the new wrapping key</li>
* <li>{@code hmackey} the session HMAC key in JWK format, wrapped with the new wrapping key</li>
* </ul></p>
*/
public static class ResponseData extends KeyResponseData {
/** Key wrapping key. */
private static final String KEY_WRAP_KEY = "wrapkey";
/** Key wrapping key data. */
private static final String KEY_WRAPDATA = "wrapdata";
/** Key encrypted encryption key. */
private static final String KEY_ENCRYPTION_KEY = "encryptionkey";
/** Key encrypted HMAC key. */
private static final String KEY_HMAC_KEY = "hmackey";
/**
* Create a new JSON Web Key ladder key response data instance
* with the provided master token and wrapped keys.
*
* @param masterToken the master token.
* @param wrapKey the wrapped wrap key.
* @param wrapdata the wrap data for reconstructing the wrap key.
* @param encryptionKey the wrap key wrapped encryption key.
* @param hmacKey the wrap key wrapped HMAC key.
*/
public ResponseData(final MasterToken masterToken, final byte[] wrapKey, final byte[] wrapdata, final byte[] encryptionKey, final byte[] hmacKey) {
super(masterToken, KeyExchangeScheme.JWK_LADDER);
this.wrapKey = wrapKey;
this.wrapdata = wrapdata;
this.encryptionKey = encryptionKey;
this.hmacKey = hmacKey;
}
/**
* Create a new JSON Web Key ladder key response data instance
* with the provided master token from the provided MSL object.
*
* @param masterToken the master token.
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the mechanism is not recognized.
*/
public ResponseData(final MasterToken masterToken, final MslObject keyDataMo) throws MslKeyExchangeException, MslEncodingException {
super(masterToken, KeyExchangeScheme.JWK_LADDER);
try {
wrapKey = keyDataMo.getBytes(KEY_WRAP_KEY);
wrapdata = keyDataMo.getBytes(KEY_WRAPDATA);
encryptionKey = keyDataMo.getBytes(KEY_ENCRYPTION_KEY);
hmacKey = keyDataMo.getBytes(KEY_HMAC_KEY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
}
}
/**
* @return the session key wrapping key.
*/
public byte[] getWrapKey() {
return wrapKey;
}
/**
* @return the session key wrapping key data.
*/
public byte[] getWrapdata() {
return wrapdata;
}
/**
* @return the wrapped session encryption key.
*/
public byte[] getEncryptionKey() {
return encryptionKey;
}
/**
* @return the wrapped session HMAC key.
*/
public byte[] getHmacKey() {
return hmacKey;
}
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_WRAP_KEY, wrapKey);
mo.put(KEY_WRAPDATA, wrapdata);
mo.put(KEY_ENCRYPTION_KEY, encryptionKey);
mo.put(KEY_HMAC_KEY, hmacKey);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof ResponseData)) return false;
final ResponseData that = (ResponseData)obj;
return super.equals(obj) &&
Arrays.equals(wrapKey, that.wrapKey) &&
Arrays.equals(wrapdata, that.wrapdata) &&
Arrays.equals(encryptionKey, that.encryptionKey) &&
Arrays.equals(hmacKey, that.hmacKey);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^
Arrays.hashCode(wrapKey) ^
Arrays.hashCode(wrapdata) ^
Arrays.hashCode(encryptionKey) ^
Arrays.hashCode(hmacKey);
}
/** Wrapped wrap key. */
private final byte[] wrapKey;
/** Wrap data. */
private final byte[] wrapdata;
/** Wrapped encryption key. */
private final byte[] encryptionKey;
/** Wrapped HMAC key. */
private final byte[] hmacKey;
}
/**
* <p>A specialized crypto context for wrapping and unwrapping JSON web
* keys.</p>
*
* <p>Implementations of this class must add and remove padding to the JSON
* web key string representation's binary encoding for compatibility with
* the wrapping algorithm used.</p>
*/
public static abstract class JwkCryptoContext extends ICryptoContext {
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.ENCRYPT_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED);
}
}
/**
* AES key wrap JSON web key crypto context.
*/
public static class AesKwJwkCryptoContext extends JwkCryptoContext {
/** AES key wrap cipher transform. */
private static final String A128_KW_TRANSFORM = "AESWrap";
/** AES key wrap block size in bytes. */
private static final int AES_KW_BLOCK_SIZE = 8;
/** Space character. */
private static final byte SPACE = (byte)' ';
/**
* Create an AES key wrap JSON web key crypto context. The provided
* crypto context must perform AES key wrap for its wrap and unwrap
* functions.
*
* @param cryptoContext the backing crypto context.
*/
public AesKwJwkCryptoContext(final ICryptoContext cryptoContext) {
this.key = null;
this.cryptoContext = cryptoContext;
}
/**
* Create an AES key wrap JSON web key crypto context with the provided
* key.
*
* @param key AES secret key.
*/
public AesKwJwkCryptoContext(final SecretKey key) {
if (!key.getAlgorithm().equals(JcaAlgorithm.AESKW))
throw new IllegalArgumentException("Secret key must be an " + JcaAlgorithm.AESKW + " key.");
this.key = key;
this.cryptoContext = null;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
// Compute the number of bytes that are not aligned to the block
// size.
final int unalignedBytes = data.length % AES_KW_BLOCK_SIZE;
// If there are no unaligned bytes then we're good. Otherwise add
// spaces after the opening brace as padding. This assumes the data
// is actually the UTF-8 binary representation of a JSON web key.
final byte[] alignedJwk;
if (unalignedBytes == 0) {
alignedJwk = data;
} else {
final int paddingCount = AES_KW_BLOCK_SIZE - unalignedBytes;
alignedJwk = new byte[data.length + paddingCount];
alignedJwk[0] = '{';
final int dataOffset = 1 + paddingCount;
Arrays.fill(alignedJwk, 1, dataOffset, SPACE);
System.arraycopy(data, 1, alignedJwk, dataOffset, data.length - 1);
}
// If a secret key is provided use it.
if (key != null) {
try {
// Encrypt plaintext.
final Cipher cipher = CryptoCache.getCipher(A128_KW_TRANSFORM);
cipher.init(Cipher.WRAP_MODE, key);
// The wrap() function requires a key object, but the data
// we are trying to wrap is not necessarily a key. However
// it should be aligned to the AES key wrap block size so
// we can use the AES key wrap algorithm.
final Key secretKey = new SecretKeySpec(alignedJwk, JcaAlgorithm.AESKW);
return cipher.wrap(secretKey);
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Zero-length plaintext provided.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
}
}
// Otherwise use the backing crypto context.
return cryptoContext.wrap(alignedJwk, encoder, format);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
// If a secret key is provided use it.
if (key != null) {
try {
// Decrypt ciphertext.
final Cipher cipher = CryptoCache.getCipher(A128_KW_TRANSFORM);
cipher.init(Cipher.UNWRAP_MODE, key);
return cipher.unwrap(data, "AES", Cipher.SECRET_KEY).getEncoded();
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
}
}
// Otherwise use the backing crypto context.
return cryptoContext.unwrap(data, encoder);
}
/** AES secret key. */
private final SecretKey key;
/** AES key wrap crypto context. */
private final ICryptoContext cryptoContext;
}
/**
* Create the JSON web key crypto context identified by the mechanism.
*
* @param ctx MSL context.
* @param mechanism the wrap key wrapping mechanism.
* @param wrapdata the wrap key previous wrapping key data. May be null.
* @param identity the entity identity.
* @return the JSON web key crypto context.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslKeyExchangeException if the mechanism is unsupported.
* @throws MslEntityAuthException if there is a problem with the entity
* identity.
*/
private static JwkCryptoContext createCryptoContext(final MslContext ctx, final Mechanism mechanism, final byte[] wrapdata, final String identity) throws MslKeyExchangeException, MslCryptoException, MslEntityAuthException {
switch (mechanism) {
case PSK:
{
final EntityAuthenticationData authdata = new PresharedAuthenticationData(identity);
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(EntityAuthenticationScheme.PSK);
if (factory == null)
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
final ICryptoContext aesKwCryptoContext = factory.getCryptoContext(ctx, authdata);
return new AesKwJwkCryptoContext(aesKwCryptoContext);
}
case WRAP:
{
final ICryptoContext cryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapBytes = cryptoContext.unwrap(wrapdata, encoder);
if (wrapBytes == null || wrapBytes.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
return new AesKwJwkCryptoContext(wrapKey);
}
default:
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
}
/**
* Create a new JSON Web Key ladder key exchange factory.
*
* @param repository the wrapping key crypto context repository.
* @param authutils authentication utilities.
*/
public JsonWebKeyLadderExchange(final WrapCryptoContextRepository repository, final AuthenticationUtils authutils) {
super(KeyExchangeScheme.JWK_LADDER);
this.repository = repository;
this.authutils = authutils;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createRequestData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslKeyExchangeException, MslCryptoException {
return new RequestData(keyRequestMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createResponseData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyResponseMo) throws MslEncodingException, MslKeyExchangeException {
return new ResponseData(masterToken, keyResponseMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException, MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// If the master token was not issued by the local entity then we
// should not be generating a key response for it.
if (!masterToken.isVerified())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
// Grab the request data.
final Mechanism mechanism = request.getMechanism();
final byte[] prevWrapdata = request.getWrapdata();
final String identity = masterToken.getIdentity();
// Verify the scheme is permitted.
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setMasterToken(masterToken);
// Create random AES-128 wrapping key.
final byte[] wrapBytes = new byte[16];
ctx.getRandom().nextBytes(wrapBytes);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
// Create the wrap data.
final ICryptoContext mslCryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapdata = mslCryptoContext.wrap(wrapBytes, encoder, format);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Wrap wrapping key using specified wrapping key.
final JsonWebKey wrapJwk = new JsonWebKey(WRAP_UNWRAP, Algorithm.A128KW, false, WRAP_KEY_ID, wrapKey);
final byte[] wrapJwkBytes = wrapJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final ICryptoContext wrapKeyCryptoContext = createCryptoContext(ctx, mechanism, prevWrapdata, identity);
final byte[] wrappedWrapJwk = wrapKeyCryptoContext.wrap(wrapJwkBytes, encoder, format);
// Wrap session keys inside JSON Web Key objects with the wrapping key.
final ICryptoContext wrapCryptoContext = new AesKwJwkCryptoContext(wrapKey);
final JsonWebKey encryptionJwk = new JsonWebKey(ENCRYPT_DECRYPT, Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(SIGN_VERIFY, Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] wrappedEncryptionJwk = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
final byte[] wrappedHmacJwk = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.renewMasterToken(ctx, masterToken, encryptionKey, hmacKey, null);
// Create session crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, wrappedWrapJwk, wrapdata, wrappedEncryptionJwk, wrappedHmacJwk);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData,final EntityAuthenticationData entityAuthData) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslEntityAuthException, MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = entityAuthData.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setEntityAuthenticationData(entityAuthData);
// Create random AES-128 wrapping key.
final byte[] wrapBytes = new byte[16];
ctx.getRandom().nextBytes(wrapBytes);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
// Create the wrap data.
final ICryptoContext mslCryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapdata = mslCryptoContext.wrap(wrapBytes, encoder, format);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Grab the request data.
final Mechanism mechanism = request.getMechanism();
final byte[] prevWrapdata = request.getWrapdata();
// Wrap wrapping key using specified wrapping key.
final JsonWebKey wrapJwk = new JsonWebKey(WRAP_UNWRAP, Algorithm.A128KW, false, WRAP_KEY_ID, wrapKey);
final byte[] wrapJwkBytes = wrapJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final ICryptoContext wrapKeyCryptoContext = createCryptoContext(ctx, mechanism, prevWrapdata, identity);
final byte[] wrappedWrapJwk = wrapKeyCryptoContext.wrap(wrapJwkBytes, encoder, format);
// Wrap session keys inside JSON Web Key objects with the wrapping key.
final ICryptoContext wrapCryptoContext = new AesKwJwkCryptoContext(wrapKey);
final JsonWebKey encryptionJwk = new JsonWebKey(ENCRYPT_DECRYPT, Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(SIGN_VERIFY, Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] wrappedEncryptionJwk = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
final byte[] wrappedHmacJwk = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.createMasterToken(ctx, entityAuthData, encryptionKey, hmacKey, null);
// Create session crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, wrappedWrapJwk, wrapdata, wrappedEncryptionJwk, wrappedHmacJwk);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.keyx.KeyResponseData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
if (!(keyResponseData instanceof ResponseData))
throw new MslInternalException("Key response data " + keyResponseData.getClass().getName() + " was not created by this factory.");
final ResponseData response = (ResponseData)keyResponseData;
// Unwrap new wrapping key.
final Mechanism mechanism = request.getMechanism();
final byte[] requestWrapdata = request.getWrapdata();
final EntityAuthenticationData entityAuthData = ctx.getEntityAuthenticationData(null);
final String identity = entityAuthData.getIdentity();
final ICryptoContext wrapKeyCryptoContext;
switch (mechanism) {
case PSK:
{
final EntityAuthenticationData authdata = new PresharedAuthenticationData(identity);
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(EntityAuthenticationScheme.PSK);
if (factory == null)
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name()).setEntityAuthenticationData(entityAuthData);
final ICryptoContext cryptoContext = factory.getCryptoContext(ctx, authdata);
wrapKeyCryptoContext = new AesKwJwkCryptoContext(cryptoContext);
break;
}
case WRAP:
{
wrapKeyCryptoContext = repository.getCryptoContext(requestWrapdata);
if (wrapKeyCryptoContext == null)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING, Base64.encode(requestWrapdata)).setEntityAuthenticationData(entityAuthData);
break;
}
default:
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name()).setEntityAuthenticationData(entityAuthData);
}
// Unwrap wrapping key.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] unwrappedWrapJwk = wrapKeyCryptoContext.unwrap(response.getWrapKey(), encoder);
final JsonWebKey wrapJwk;
try {
final MslObject wrapJwkMo = encoder.parseObject(unwrappedWrapJwk);
wrapJwk = new JsonWebKey(wrapJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedWrapJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
final SecretKey wrapKey = wrapJwk.getSecretKey();
// Unwrap session keys with wrapping key.
final ICryptoContext unwrapCryptoContext = new AesKwJwkCryptoContext(wrapKey);
final byte[] unwrappedEncryptionJwk = unwrapCryptoContext.unwrap(response.getEncryptionKey(), encoder);
final byte[] unwrappedHmacJwk = unwrapCryptoContext.unwrap(response.getHmacKey(), encoder);
final JsonWebKey encryptionJwk;
try {
final MslObject encryptionJwkMo = encoder.parseObject(unwrappedEncryptionJwk);
encryptionJwk = new JsonWebKey(encryptionJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedEncryptionJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
final JsonWebKey hmacJwk;
try {
final MslObject hmacJwkMo = encoder.parseObject(unwrappedHmacJwk);
hmacJwk = new JsonWebKey(hmacJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedHmacJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
// Deliver wrap data to wrap key repository.
final byte[] wrapdata = response.getWrapdata();
repository.addCryptoContext(wrapdata, unwrapCryptoContext);
if (requestWrapdata != null)
repository.removeCryptoContext(requestWrapdata);
// Create crypto context.
final MasterToken responseMasterToken = response.getMasterToken();
final SecretKey encryptionKey = encryptionJwk.getSecretKey();
final SecretKey hmacKey = hmacJwk.getSecretKey();
return new SessionCryptoContext(ctx, responseMasterToken, identity, encryptionKey, hmacKey);
}
/** Wrapping keys crypto context repository. */
private final WrapCryptoContextRepository repository;
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 1,724 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/AsymmetricWrappedExchange.java
|
/**
* Copyright (c) 2012-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.keyx;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.SecretKeySpec;
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.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.AsymmetricCryptoContext;
import com.netflix.msl.crypto.CryptoCache;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.CekCryptoContext;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.Format;
import com.netflix.msl.crypto.JsonWebKey;
import com.netflix.msl.crypto.JsonWebKey.KeyOp;
import com.netflix.msl.crypto.JsonWebKey.Usage;
import com.netflix.msl.crypto.SessionCryptoContext;
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;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>Asymmetric key wrapped key exchange.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class AsymmetricWrappedExchange extends KeyExchangeFactory {
/** Encrypt/decrypt key operations. */
private static final Set<KeyOp> ENCRYPT_DECRYPT = new HashSet<KeyOp>(Arrays.asList(KeyOp.encrypt, KeyOp.decrypt));
/** Sign/verify key operations. */
private static final Set<KeyOp> SIGN_VERIFY = new HashSet<KeyOp>(Arrays.asList(KeyOp.sign, KeyOp.verify));
/**
* <p>An RSA wrapping crypto context is unique in that it treats its wrap/
* unwrap operations as encrypt/decrypt respectively. This is compatible
* with the Web Crypto API.</p>
*/
private static class RsaWrappingCryptoContext extends AsymmetricCryptoContext {
/** JWK RSA crypto context mode. */
public static enum Mode {
/** RSA-OAEP wrap/unwrap */
WRAP_UNWRAP_OAEP,
/** RSA PKCS#1 wrap/unwrap */
WRAP_UNWRAP_PKCS1,
}
/**
* <p>Create a new RSA wrapping crypto context for the specified mode
* using the provided public and private keys. The mode identifies the
* operations to enable. All other operations are no-ops and return the
* data unmodified.</p>
*
* @param ctx MSL context.
* @param id key pair identity.
* @param privateKey the private key. May be null.
* @param publicKey the public key. May be null.
* @param mode crypto context mode.
*/
public RsaWrappingCryptoContext(final MslContext ctx, final String id, final PrivateKey privateKey, final PublicKey publicKey, final Mode mode) {
super(id, privateKey, publicKey, NULL_OP, null, NULL_OP);
switch (mode) {
case WRAP_UNWRAP_OAEP:
wrapTransform = "RSA/ECB/OAEPPadding";
wrapParams = OAEPParameterSpec.DEFAULT;
break;
case WRAP_UNWRAP_PKCS1:
wrapTransform = "RSA/ECB/PKCS1Padding";
wrapParams = null;
break;
default:
throw new MslInternalException("RSA wrapping crypto context mode " + mode + " not supported.");
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.AsymmetricCryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (NULL_OP.equals(wrapTransform))
return data;
if (publicKey == null)
throw new MslCryptoException(MslError.WRAP_NOT_SUPPORTED, "no public key");
Throwable reset = null;
try {
// Encrypt plaintext.
final Cipher cipher = CryptoCache.getCipher(wrapTransform);
cipher.init(Cipher.ENCRYPT_MODE, publicKey, wrapParams);
return cipher.doFinal(data);
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_BAD_PADDING, "not expected when encrypting", e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(wrapTransform);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.AsymmetricCryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
if (NULL_OP.equals(wrapTransform))
return data;
if (privateKey == null)
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED, "no private key");
Throwable reset = null;
try {
// Decrypt ciphertext.
final Cipher cipher = CryptoCache.getCipher(wrapTransform);
cipher.init(Cipher.DECRYPT_MODE, privateKey, wrapParams);
return cipher.doFinal(data);
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PRIVATE_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_BAD_PADDING, e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(wrapTransform);
}
}
/** Wrap/unwrap transform. */
private final String wrapTransform;
/** Wrap/unwrap algorithm parameters. */
private final AlgorithmParameterSpec wrapParams;
}
/**
* <p>Asymmetric key wrapped key request data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "keypairid", "mechanism", "publickey" ],
* "keypairid" : "string",
* "mechanism" : "string",
* "publickey" : "binary"
* }} where:
* <ul>
* <li>{@code keypairid} identifies the key pair for wrapping and unwrapping the session keys</li>
* <li>{@code mechanism} the public key cryptographic mechanism of the key pair</li>
* <li>{@code publickey} the public key used to wrap the session keys</li>
* </ul></p>
*/
public static class RequestData extends KeyRequestData {
public enum Mechanism {
/** RSA-OAEP encrypt/decrypt */
RSA,
/** ECIES */
ECC,
/** JSON Web Encryption with RSA-OAEP */
JWE_RSA,
/** JSON Web Encryption JSON Serialization with RSA-OAEP */
JWEJS_RSA,
/** JSON Web Key with RSA-OAEP */
JWK_RSA,
/** JSON Web Key with RSA-PKCS v1.5 */
JWK_RSAES,
}
/** Key key pair ID. */
private static final String KEY_KEY_PAIR_ID = "keypairid";
/** Key mechanism. */
private static final String KEY_MECHANISM = "mechanism";
/** Key public key. */
private static final String KEY_PUBLIC_KEY = "publickey";
/**
* Create a new asymmetric key wrapped key request data instance with
* the specified key pair ID and public key. The private key is also
* required but is not included in the request data.
*
* @param keyPairId the public/private key pair ID.
* @param mechanism the key exchange mechanism.
* @param publicKey the public key.
* @param privateKey the private key.
*/
public RequestData(final String keyPairId, final Mechanism mechanism, final PublicKey publicKey, final PrivateKey privateKey) {
super(KeyExchangeScheme.ASYMMETRIC_WRAPPED);
this.keyPairId = keyPairId;
this.mechanism = mechanism;
this.publicKey = publicKey;
this.privateKey = privateKey;
}
/**
* Create a new asymmetric key wrapped key request data instance from
* the provided MSL object. The private key will be unknown.
*
* @param keyRequestMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException if the encoded key is invalid or the
* specified mechanism is not supported.
* @throws MslKeyExchangeException if the specified mechanism is not
* recognized.
*/
public RequestData(final MslObject keyRequestMo) throws MslEncodingException, MslCryptoException, MslKeyExchangeException {
super(KeyExchangeScheme.ASYMMETRIC_WRAPPED);
final byte[] encodedKey;
try {
keyPairId = keyRequestMo.getString(KEY_KEY_PAIR_ID);
final String mechanismName = keyRequestMo.getString(KEY_MECHANISM);
try {
mechanism = Mechanism.valueOf(mechanismName);
} catch (final IllegalArgumentException e) {
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_MECHANISM, mechanismName, e);
}
encodedKey = keyRequestMo.getBytes(KEY_PUBLIC_KEY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyRequestMo, e);
}
try {
switch (mechanism) {
case RSA:
case JWE_RSA:
case JWEJS_RSA:
case JWK_RSA:
case JWK_RSAES:
{
final KeyFactory factory = CryptoCache.getKeyFactory("RSA");
final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
publicKey = factory.generatePublic(keySpec);
break;
}
/* Does not currently work.
case ECC:
{
final KeyFactory factory = CryptoCache.getKeyFactory("ECDSA");
final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
publicKey = factory.generatePublic(keySpec);
break;
}
*/
default:
throw new MslCryptoException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
} catch (final NullPointerException e) {
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, "keydata " + keyRequestMo.toString(), e);
} catch (final NoSuchAlgorithmException e) {
throw new MslCryptoException(MslError.UNSUPPORTED_KEYX_MECHANISM, "keydata " + keyRequestMo.toString(), e);
} catch (final InvalidKeySpecException e) {
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, "keydata " + keyRequestMo.toString(), e);
}
privateKey = null;
}
/**
* @return the key pair ID.
*/
public String getKeyPairId() {
return keyPairId;
}
/**
* @return the key mechanism.
*/
public Mechanism getMechanism() {
return mechanism;
}
/**
* @return the public key.
*/
public PublicKey getPublicKey() {
return publicKey;
}
/**
* @return the private key.
*/
public PrivateKey getPrivateKey() {
return privateKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) {
final MslObject mo = encoder.createObject();
mo.put(KEY_KEY_PAIR_ID, keyPairId);
mo.put(KEY_MECHANISM, mechanism.name());
mo.put(KEY_PUBLIC_KEY, publicKey.getEncoded());
return mo;
}
/* (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 RequestData)) return false;
final RequestData that = (RequestData)obj;
// Private keys are optional but must be considered.
final boolean privateKeysEqual =
privateKey == that.privateKey ||
(privateKey != null && that.privateKey != null &&
Arrays.equals(privateKey.getEncoded(), that.privateKey.getEncoded()));
return super.equals(obj) &&
keyPairId.equals(that.keyPairId) &&
mechanism.equals(that.mechanism) &&
Arrays.equals(publicKey.getEncoded(), that.publicKey.getEncoded()) &&
privateKeysEqual;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
// Private keys are optional but must be considered.
final int privateKeyHashCode = (privateKey != null)
? Arrays.hashCode(privateKey.getEncoded()) : 0;
return super.hashCode() ^
keyPairId.hashCode() ^
mechanism.hashCode() ^
Arrays.hashCode(publicKey.getEncoded()) ^
privateKeyHashCode;
}
/** Public/private key pair ID. */
private final String keyPairId;
/** Key mechanism. */
private final Mechanism mechanism;
/** Public key. */
private final PublicKey publicKey;
/** Private key. */
private final PrivateKey privateKey;
}
/**
* <p>Asymmetric key wrapped key response data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "keypairid", "encryptionkey", "hmackey" ],
* "keypairid" : "string",
* "encryptionkey" : "binary",
* "hmackey" : "binary"
* }} where:
* <ul>
* <li>{@code keypairid} identifies the key pair for wrapping and unwrapping the session keys</li>
* <li>{@code encryptionkey} the wrapped session encryption key</li>
* <li>{@code hmackey} the wrapped session HMAC key</li>
* </ul></p>
*/
public static class ResponseData extends KeyResponseData {
/** Key key pair ID. */
private static final String KEY_KEY_PAIR_ID = "keypairid";
/** Key encrypted encryption key. */
private static final String KEY_ENCRYPTION_KEY = "encryptionkey";
/** Key encrypted HMAC key. */
private static final String KEY_HMAC_KEY = "hmackey";
/**
* Create a new asymmetric key wrapped key response data instance with
* the provided master token, specified key pair ID, and public
* key-encrypted encryption and HMAC keys.
*
* @param masterToken the master token.
* @param keyPairId the public/private key pair ID.
* @param encryptionKey the public key-encrypted encryption key.
* @param hmacKey the public key-encrypted HMAC key.
*/
public ResponseData(final MasterToken masterToken, final String keyPairId, final byte[] encryptionKey, final byte[] hmacKey) {
super(masterToken, KeyExchangeScheme.ASYMMETRIC_WRAPPED);
this.keyPairId = keyPairId;
this.encryptionKey = encryptionKey;
this.hmacKey = hmacKey;
}
/**
* Create a new asymmetric key wrapped key response data instance with
* the provided master token from the provided MSL object.
*
* @param masterToken the master token.
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if a session key is invalid.
*/
public ResponseData(final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
super(masterToken, KeyExchangeScheme.ASYMMETRIC_WRAPPED);
try {
keyPairId = keyDataMo.getString(KEY_KEY_PAIR_ID);
encryptionKey = keyDataMo.getBytes(KEY_ENCRYPTION_KEY);
hmacKey = keyDataMo.getBytes(KEY_HMAC_KEY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
}
}
/**
* @return the key pair ID.
*/
public String getKeyPairId() {
return keyPairId;
}
/**
* @return the public key-encrypted encryption key.
*/
public byte[] getEncryptionKey() {
return encryptionKey;
}
/**
* @return the public key-encrypted HMAC key.
*/
public byte[] getHmacKey() {
return hmacKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_KEY_PAIR_ID, keyPairId);
mo.put(KEY_ENCRYPTION_KEY, encryptionKey);
mo.put(KEY_HMAC_KEY, hmacKey);
return mo;
}
/* (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 ResponseData)) return false;
final ResponseData that = (ResponseData)obj;
return super.equals(obj) &&
keyPairId.equals(that.keyPairId) &&
Arrays.equals(encryptionKey, that.encryptionKey)&&
Arrays.equals(hmacKey, that.hmacKey);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ keyPairId.hashCode() ^ Arrays.hashCode(encryptionKey) ^ Arrays.hashCode(hmacKey);
}
/** Public/private key pair ID. */
private final String keyPairId;
/** Public key-encrypted encryption key. */
private final byte[] encryptionKey;
/** Public key-encrypted HMAC key. */
private final byte[] hmacKey;
}
/**
* Create the crypto context identified by the key ID, mechanism, and
* provided keys.
*
* @param ctx MSL context.
* @param keyPairId the key pair ID.
* @param mechanism the key mechanism.
* @param privateKey the private key. May be null.
* @param publicKey the public key. May be null.
* @return the crypto context.
* @throws MslCryptoException if the key mechanism is unsupported.
*/
private static ICryptoContext createCryptoContext(final MslContext ctx, final String keyPairId, final RequestData.Mechanism mechanism, final PrivateKey privateKey, final PublicKey publicKey) throws MslCryptoException {
switch (mechanism) {
case JWE_RSA:
{
final CekCryptoContext cryptoContext = new JsonWebEncryptionCryptoContext.RsaOaepCryptoContext(privateKey, publicKey);
return new JsonWebEncryptionCryptoContext(ctx, cryptoContext, JsonWebEncryptionCryptoContext.Encryption.A128GCM, Format.JWE_CS);
}
case JWEJS_RSA:
{
final CekCryptoContext cryptoContext = new JsonWebEncryptionCryptoContext.RsaOaepCryptoContext(privateKey, publicKey);
return new JsonWebEncryptionCryptoContext(ctx, cryptoContext, JsonWebEncryptionCryptoContext.Encryption.A128GCM, Format.JWE_JS);
}
case RSA:
case JWK_RSA:
{
return new RsaWrappingCryptoContext(ctx, keyPairId, privateKey, publicKey, RsaWrappingCryptoContext.Mode.WRAP_UNWRAP_OAEP);
}
case JWK_RSAES:
{
return new RsaWrappingCryptoContext(ctx, keyPairId, privateKey, publicKey, RsaWrappingCryptoContext.Mode.WRAP_UNWRAP_PKCS1);
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
}
/**
* Create a new asymmetric wrapped key exchange factory.
*
* @param authutils authentication utilities.
*/
public AsymmetricWrappedExchange(final AuthenticationUtils authutils) {
super(KeyExchangeScheme.ASYMMETRIC_WRAPPED);
this.authutils = authutils;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createRequestData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslCryptoException, MslKeyExchangeException {
return new RequestData(keyRequestMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createResponseData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
return new ResponseData(masterToken, keyDataMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslMasterTokenException, MslEncodingException, MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// If the master token was not issued by the local entity then we
// should not be generating a key response for it.
if (!masterToken.isVerified())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
// Verify the scheme is permitted.
final String identity = masterToken.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setMasterToken(masterToken);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey, hmacKey;
try {
encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.SESSION_KEY_CREATION_FAILURE, e).setMasterToken(masterToken);
}
// Wrap session keys with public key.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final String keyPairId = request.getKeyPairId();
final RequestData.Mechanism mechanism = request.getMechanism();
final PublicKey publicKey = request.getPublicKey();
final ICryptoContext wrapCryptoContext = createCryptoContext(ctx, keyPairId, mechanism, null, publicKey);
final byte[] wrappedEncryptionKey, wrappedHmacKey;
switch (mechanism) {
case JWE_RSA:
case JWEJS_RSA:
{
final JsonWebKey encryptionJwk = new JsonWebKey(Usage.enc, JsonWebKey.Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(Usage.sig, JsonWebKey.Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
break;
}
case JWK_RSA:
case JWK_RSAES:
{
final JsonWebKey encryptionJwk = new JsonWebKey(ENCRYPT_DECRYPT, JsonWebKey.Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(SIGN_VERIFY, JsonWebKey.Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
break;
}
default:
{
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacBytes, encoder, format);
break;
}
}
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.renewMasterToken(ctx, masterToken, encryptionKey, hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, request.getKeyPairId(), wrappedEncryptionKey, wrappedHmacKey);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final EntityAuthenticationData entityAuthData) throws MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = entityAuthData.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setEntityAuthenticationData(entityAuthData);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Wrap session keys with public key.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final String keyPairId = request.getKeyPairId();
final RequestData.Mechanism mechanism = request.getMechanism();
final PublicKey publicKey = request.getPublicKey();
final ICryptoContext wrapCryptoContext = createCryptoContext(ctx, keyPairId, mechanism, null, publicKey);
final byte[] wrappedEncryptionKey, wrappedHmacKey;
switch (mechanism) {
case JWE_RSA:
case JWEJS_RSA:
{
final JsonWebKey encryptionJwk = new JsonWebKey(Usage.enc, JsonWebKey.Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(Usage.sig, JsonWebKey.Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
break;
}
case JWK_RSA:
case JWK_RSAES:
{
final JsonWebKey encryptionJwk = new JsonWebKey(ENCRYPT_DECRYPT, JsonWebKey.Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(SIGN_VERIFY, JsonWebKey.Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
break;
}
default:
{
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacBytes, encoder, format);
break;
}
}
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken masterToken = tokenFactory.createMasterToken(ctx, entityAuthData, encryptionKey, hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext;
try {
cryptoContext = new SessionCryptoContext(ctx, masterToken);
} catch (final MslMasterTokenException e) {
throw new MslInternalException("Master token constructed by token factory is not trusted.", e);
}
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(masterToken, request.getKeyPairId(), wrappedEncryptionKey, wrappedHmacKey);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.keyx.KeyResponseData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
if (!(keyResponseData instanceof ResponseData))
throw new MslInternalException("Key response data " + keyResponseData.getClass().getName() + " was not created by this factory.");
final ResponseData response = (ResponseData)keyResponseData;
// Verify response matches request.
final String requestKeyPairId = request.getKeyPairId();
final String responseKeyPairId = response.getKeyPairId();
if (!requestKeyPairId.equals(responseKeyPairId))
throw new MslKeyExchangeException(MslError.KEYX_RESPONSE_REQUEST_MISMATCH, "request " + requestKeyPairId + "; response " + responseKeyPairId);
// Unwrap session keys with identified key.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final PrivateKey privateKey = request.getPrivateKey();
if (privateKey == null)
throw new MslKeyExchangeException(MslError.KEYX_PRIVATE_KEY_MISSING, "request Asymmetric private key");
final RequestData.Mechanism mechanism = request.getMechanism();
final ICryptoContext unwrapCryptoContext = createCryptoContext(ctx, requestKeyPairId, mechanism, privateKey, null);
final SecretKey encryptionKey, hmacKey;
switch (mechanism) {
case JWE_RSA:
case JWEJS_RSA:
case JWK_RSA:
case JWK_RSAES:
{
final byte[] encryptionJwkBytes = unwrapCryptoContext.unwrap(response.getEncryptionKey(), encoder);
final byte[] hmacJwkBytes = unwrapCryptoContext.unwrap(response.getHmacKey(), encoder);
final MslObject encryptionJwkMo, hmacJwkMo;
try {
encryptionJwkMo = encoder.parseObject(encryptionJwkBytes);
hmacJwkMo = encoder.parseObject(hmacJwkBytes);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.SESSION_KEY_CREATION_FAILURE, e).setMasterToken(masterToken);
}
encryptionKey = new JsonWebKey(encryptionJwkMo).getSecretKey();
hmacKey = new JsonWebKey(hmacJwkMo).getSecretKey();
break;
}
default:
{
final byte[] unwrappedEncryptionKey = unwrapCryptoContext.unwrap(response.getEncryptionKey(), encoder);
final byte[] unwrappedHmacKey = unwrapCryptoContext.unwrap(response.getHmacKey(), encoder);
try {
encryptionKey = new SecretKeySpec(unwrappedEncryptionKey, JcaAlgorithm.AES);
hmacKey = new SecretKeySpec(unwrappedHmacKey, JcaAlgorithm.HMAC_SHA256);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.SESSION_KEY_CREATION_FAILURE, e).setMasterToken(masterToken);
}
break;
}
}
// Create crypto context.
final String identity = ctx.getEntityAuthenticationData(null).getIdentity();
final MasterToken responseMasterToken = response.getMasterToken();
return new SessionCryptoContext(ctx, responseMasterToken, identity, encryptionKey, hmacKey);
}
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 1,725 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/DiffieHellmanParameters.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.keyx;
import java.util.Map;
import javax.crypto.spec.DHParameterSpec;
import com.netflix.msl.MslKeyExchangeException;
/**
* Diffie-Hellman parameters by parameter ID.
*
* @author Wesley Miaw <[email protected]>
*/
public interface DiffieHellmanParameters {
/**
* @return the map of Diffie-Hellman parameters by parameter ID.
* @throws MslKeyExchangeException if there is an error accessing the
* parameters.
*/
public Map<String,DHParameterSpec> getParameterSpecs() throws MslKeyExchangeException;
/**
* Returns the Diffie-Hellman parameter specification identified by the
* parameters ID.
*
* @param id the parameters ID.
* @return the parameter specification or null if the parameters ID is
* not recognized.
* @throws MslKeyExchangeException if there is an error accessing the
* parameter specification.
*/
public DHParameterSpec getParameterSpec(final String id) throws MslKeyExchangeException;
}
| 1,726 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/KeyExchangeFactory.java
|
/**
* Copyright (c) 2012-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.keyx;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* A key exchange factory creates key request and response data instances for
* a specific key exchange scheme.
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class KeyExchangeFactory {
/**
* The key exchange data struct contains key response data and a crypto
* context for the exchanged keys.
*/
public static class KeyExchangeData {
/**
* Create a new key key exhange data struct with the provided key
* response data, master token, and crypto context.
*
* @param keyResponseData the key response data.
* @param cryptoContext the crypto context.
*/
public KeyExchangeData(final KeyResponseData keyResponseData, final ICryptoContext cryptoContext) {
this.keyResponseData = keyResponseData;
this.cryptoContext = cryptoContext;
}
/** Key response data. */
public final KeyResponseData keyResponseData;
/** Crypto context for the exchanged keys. */
public final ICryptoContext cryptoContext;
}
/**
* Create a new key exchange factory for the specified scheme.
*
* @param scheme the key exchange scheme.
*/
protected KeyExchangeFactory(final KeyExchangeScheme scheme) {
this.scheme = scheme;
}
/**
* @return the key exchange scheme this factory is for.
*/
public KeyExchangeScheme getScheme() {
return scheme;
}
/**
* Construct a new key request data instance from the provided MSL object.
*
* @param ctx MSL context.
* @param keyRequestMo the MSL object.
* @return the key request data.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if there is an error creating the key
* request data.
* @throws MslCryptoException if the keying material cannot be created.
*/
protected abstract KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslKeyExchangeException, MslCryptoException;
/**
* Construct a new key response data instance from the provided MSL object.
*
* @param ctx MSL context.
* @param masterToken the master token for the new key response data.
* @param keyDataMo the MSL object.
* @return the key response data.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if there is an error creating the key
* response data.
*/
protected abstract KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException;
/**
* <p>Generate a new key response data instance and crypto context in
* response to the provided key request data. The key request data will be
* from the the remote entity.</p>
*
* <p>The provided master token should be renewed by incrementing its
* sequence number but maintaining its serial number by using the MSL
* context's token factory.</p>
*
* @param ctx MSL context.
* @param format MSL encoder format.
* @param keyRequestData the key request data.
* @param masterToken the master token to renew.
* @return the key response data and crypto context or {@code null} if the
* factory chooses not to perform key exchange.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslEncodingException if there is an error parsing or encoding
* the data.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be.
* @throws MslEntityAuthException if there is a problem with the master
* token identity.
* @throws MslException if there is an error renewing the master token.
*/
public abstract KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException, MslException;
/**
* <p>Generate a new key response data instance and crypto context in
* response to the provided key request data and entity authentication
* data. The key request data will be from the the remote entity.</p>
*
* @param ctx MSL context.
* @param format MSL encoder format.
* @param keyRequestData the key request data.
* @param entityAuthData the entity authentication data.
* @return the key response data and crypto context or {@code null} if the
* factory chooses not to perform key exchange.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslEncodingException if there is an error parsing or encoding
* the data.
* @throws MslEntityAuthException if there is a problem with the entity
* identity.
* @throws MslException if there is an error creating the master token.
*/
public abstract KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final EntityAuthenticationData entityAuthData) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslEntityAuthException, MslException;
/**
* Create a crypto context from the provided key request data and key
* response data. The key request data will be from the local entity and
* the key response data from the remote entity.
*
* @param ctx MSL context.
* @param keyRequestData the key request data.
* @param keyResponseData the key response data.
* @param masterToken the current master token (not the one inside the key
* response data). May be null.
* @return the crypto context.
* @throws MslKeyExchangeException if there is an error with the key
* request data or key response data.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be.
* @throws MslEntityAuthException if there is a problem with the master
* token identity.
*/
public abstract ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException;
/** The factory's key exchange scheme. */
private final KeyExchangeScheme scheme;
}
| 1,727 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/SymmetricWrappedExchange.java
|
/**
* Copyright (c) 2012-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.keyx;
import java.util.Arrays;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
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.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.SessionCryptoContext;
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.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>Symmetric key wrapped key exchange.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SymmetricWrappedExchange extends KeyExchangeFactory {
/** Key ID. */
public enum KeyId {
PSK,
SESSION,
}
/**
* <p>Symmetric key wrapped key request data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "keyid" ],
* "keyid" : "string",
* }} where:
* <ul>
* <li>{@code keyid} identifies the key that should be used to wrap the session keys</li>
* </ul></p>
*/
public static class RequestData extends KeyRequestData {
/** Key symmetric key ID. */
private static final String KEY_KEY_ID = "keyid";
/**
* Create a new symmetric key wrapped key request data instance with
* the specified key ID.
*
* @param keyId symmetric key identifier.
*/
public RequestData(final KeyId keyId) {
super(KeyExchangeScheme.SYMMETRIC_WRAPPED);
this.keyId = keyId;
}
/**
* Create a new symmetric key wrapped key request data instance from
* the provided MSL object.
*
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the key ID is not recognized.
*/
public RequestData(final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
super(KeyExchangeScheme.SYMMETRIC_WRAPPED);
try {
final String keyIdName = keyDataMo.getString(KEY_KEY_ID);
try {
keyId = KeyId.valueOf(keyIdName);
} catch (final IllegalArgumentException e) {
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_KEY_ID, keyIdName, e);
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
}
}
/**
* @return the wrapping key ID.
*/
public KeyId getKeyId() {
return keyId;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_KEY_ID, keyId.name());
return mo;
}
/* (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 RequestData)) return false;
final RequestData that = (RequestData)obj;
return super.equals(obj) && keyId.equals(that.keyId);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ keyId.hashCode();
}
/** Symmetric key ID. */
private final KeyId keyId;
}
/**
* <p>Symmetric key wrapped key response data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "keyid", "encryptionkey", "hmackey" ],
* "keyid" : "string",
* "encryptionkey" : "binary",
* "hmackey" : "binary"
* }} where:
* <ul>
* <li>{@code keyid} identifies the key that was used to wrap the session keys</li>
* <li>{@code encryptionkey} the wrapped session encryption key</li>
* <li>{@code hmackey} the wrapped session HMAC key</li>
* </ul></p>
*/
public static class ResponseData extends KeyResponseData {
/** Key symmetric key ID. */
private static final String KEY_KEY_ID = "keyid";
/** Key wrapped encryption key. */
private static final String KEY_ENCRYPTION_KEY = "encryptionkey";
/** Key wrapped HMAC key. */
private static final String KEY_HMAC_KEY = "hmackey";
/**
* Create a new symmetric key wrapped key response data instance with
* the provided master token, specified key ID and wrapped encryption
* and HMAC keys.
*
* @param masterToken the master token.
* @param keyId the wrapping key ID.
* @param encryptionKey the wrapped encryption key.
* @param hmacKey the wrapped HMAC key.
*/
public ResponseData(final MasterToken masterToken, final KeyId keyId, final byte[] encryptionKey, final byte[] hmacKey) {
super(masterToken, KeyExchangeScheme.SYMMETRIC_WRAPPED);
this.keyId = keyId;
this.encryptionKey = encryptionKey;
this.hmacKey = hmacKey;
}
/**
* Create a new symmetric key wrapped key response data instance with
* the provided master token from the provided MSL object.
*
* @param masterToken the master token.
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the key ID is not recognized or
* a session key is invalid.
*/
public ResponseData(final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
super(masterToken, KeyExchangeScheme.SYMMETRIC_WRAPPED);
try {
final String keyIdName = keyDataMo.getString(KEY_KEY_ID);
try {
keyId = KeyId.valueOf(keyIdName);
} catch (final IllegalArgumentException e) {
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_KEY_ID, keyIdName, e);
}
encryptionKey = keyDataMo.getBytes(KEY_ENCRYPTION_KEY);
hmacKey = keyDataMo.getBytes(KEY_HMAC_KEY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
}
}
/**
* @return the wrapping key ID.
*/
public KeyId getKeyId() {
return keyId;
}
/**
* @return the wrapped encryption key.
*/
public byte[] getEncryptionKey() {
return encryptionKey;
}
/**
* @return the wrapped HMAC key.
*/
public byte[] getHmacKey() {
return hmacKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) {
final MslObject mo = encoder.createObject();
mo.put(KEY_KEY_ID, keyId.name());
mo.put(KEY_ENCRYPTION_KEY, encryptionKey);
mo.put(KEY_HMAC_KEY, hmacKey);
return mo;
}
/* (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 ResponseData)) return false;
final ResponseData that = (ResponseData)obj;
return super.equals(obj) &&
keyId.equals(that.keyId) &&
Arrays.equals(encryptionKey, that.encryptionKey) &&
Arrays.equals(hmacKey, that.hmacKey);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^
keyId.hashCode() ^
Arrays.hashCode(encryptionKey) ^
Arrays.hashCode(hmacKey);
}
/** Symmetric key ID. */
private final KeyId keyId;
/** Wrapped encryption key. */
private final byte[] encryptionKey;
/** Wrapped HMAC key. */
private final byte[] hmacKey;
}
/**
* Create the crypto context identified by the key ID.
*
* @param ctx MSL context.
* @param keyId the key ID.
* @param masterToken the existing master token. May be null.
* @param identity the entity identity.
* @return the crypto context.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslMasterTokenException if the master token is not trusted.
* @throws MslKeyExchangeException if the key ID is unsupported.
* @throws MslEntityAuthException if there is an problem with the entity
* identity.
*/
private static ICryptoContext createCryptoContext(final MslContext ctx, final KeyId keyId, final MasterToken masterToken, final String identity) throws MslCryptoException, MslKeyExchangeException, MslEntityAuthException, MslMasterTokenException {
switch (keyId) {
case SESSION:
{
// If the master token is null session wrapped is unsupported.
if (masterToken == null)
throw new MslKeyExchangeException(MslError.KEYX_MASTER_TOKEN_MISSING, keyId.name());
// Use a stored master token crypto context if we have one.
final ICryptoContext cachedCryptoContext = ctx.getMslStore().getCryptoContext(masterToken);
if (cachedCryptoContext != null)
return cachedCryptoContext;
// If there was no stored crypto context try making one from
// the master token. We can only do this if we can open up the
// master token.
if (!masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken);
return cryptoContext;
}
case PSK:
{
final EntityAuthenticationData authdata = new PresharedAuthenticationData(identity);
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(EntityAuthenticationScheme.PSK);
if (factory == null)
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_KEY_ID, keyId.name());
return factory.getCryptoContext(ctx, authdata);
}
default:
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_KEY_ID, keyId.name());
}
}
/**
* Create a new symmetric wrapped key exchange factory.
*
* @param authutils authentication utiliites.
*/
public SymmetricWrappedExchange(final AuthenticationUtils authutils) {
super(KeyExchangeScheme.SYMMETRIC_WRAPPED);
this.authutils = authutils;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createRequestData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslKeyExchangeException {
return new RequestData(keyRequestMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createResponseData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
return new ResponseData(masterToken, keyDataMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = masterToken.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication Scheme for Device Type Not Supported " + identity + ":" + this.getScheme()).setMasterToken(masterToken);
// If the master token was not issued by the local entity then we
// should not be generating a key response for it.
if (!masterToken.isVerified())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken).setMasterToken(masterToken);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Wrap session keys with identified key...
final KeyId keyId = request.getKeyId();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final ICryptoContext wrapCryptoContext = createCryptoContext(ctx, keyId, masterToken, masterToken.getIdentity());
final byte[] wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionBytes, encoder, format);
final byte[] wrappedHmacKey = wrapCryptoContext.wrap(hmacBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.renewMasterToken(ctx, masterToken, encryptionKey, hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, keyId, wrappedEncryptionKey, wrappedHmacKey);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final EntityAuthenticationData entityAuthData) throws MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = entityAuthData.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication Scheme for Device Type Not Supported " + identity + ":" + this.getScheme());
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Wrap session keys with identified key.
final KeyId keyId = request.getKeyId();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final ICryptoContext wrapCryptoContext;
try {
wrapCryptoContext = createCryptoContext(ctx, keyId, null, identity);
} catch (final MslMasterTokenException e) {
throw new MslInternalException("Master token exception thrown when the master token is null.", e);
}
final byte[] wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionBytes, encoder, format);
final byte[] wrappedHmacKey = wrapCryptoContext.wrap(hmacBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken masterToken = tokenFactory.createMasterToken(ctx, entityAuthData, encryptionKey, hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext;
try {
cryptoContext = new SessionCryptoContext(ctx, masterToken);
} catch (final MslMasterTokenException e) {
throw new MslInternalException("Master token constructed by token factory is not trusted.", e);
}
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(masterToken, keyId, wrappedEncryptionKey, wrappedHmacKey);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.keyx.KeyResponseData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
if (!(keyResponseData instanceof ResponseData))
throw new MslInternalException("Key response data " + keyResponseData.getClass().getName() + " was not created by this factory.");
final ResponseData response = (ResponseData)keyResponseData;
// Verify response matches request.
final KeyId requestKeyId = request.getKeyId();
final KeyId responseKeyId = response.getKeyId();
if (!requestKeyId.equals(responseKeyId))
throw new MslKeyExchangeException(MslError.KEYX_RESPONSE_REQUEST_MISMATCH, "request " + requestKeyId + "; response " + responseKeyId).setMasterToken(masterToken);
// Unwrap session keys with identified key.
final EntityAuthenticationData entityAuthData = ctx.getEntityAuthenticationData(null);
final String identity = entityAuthData.getIdentity();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final ICryptoContext unwrapCryptoContext = createCryptoContext(ctx, responseKeyId, masterToken, identity);
final byte[] unwrappedEncryptionKey = unwrapCryptoContext.unwrap(response.getEncryptionKey(), encoder);
final byte[] unwrappedHmacKey = unwrapCryptoContext.unwrap(response.getHmacKey(), encoder);
// Create crypto context.
final SecretKey encryptionKey = new SecretKeySpec(unwrappedEncryptionKey, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(unwrappedHmacKey, JcaAlgorithm.HMAC_SHA256);
final MasterToken responseMasterToken = response.getMasterToken();
return new SessionCryptoContext(ctx, responseMasterToken, identity, encryptionKey, hmacKey);
}
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 1,728 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/WrapCryptoContextRepository.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.keyx;
import com.netflix.msl.crypto.ICryptoContext;
/**
* <p>The wrap crypto context repository provides access to wrapping key crypto
* contexts and is used by key exchange factories that make use of intermediate
* wrapping keys to deliver new wrapping key data to the application. The
* wrapping key data and its corresponding crypto context can then be used in
* future key request data.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public interface WrapCryptoContextRepository {
/**
* Add a new wrapping key crypto context and wrap data. The wrap data
* should be used in key request data to request a new wrapping key
* wrapped with this wrapping key.
*
* @param wrapdata wrapping key wrap data.
* @param cryptoContext wrapping key crypto context.
*/
public void addCryptoContext(final byte[] wrapdata, final ICryptoContext cryptoContext);
/**
* Return the wrapping key crypto context identified by the specified
* wrap data.
*
* @param wrapdata wrapping key wrap data.
* @return the wrapping key crypto context or null if none exists.
*/
public ICryptoContext getCryptoContext(final byte[] wrapdata);
/**
* Remove the wrapping key crypto context identified by the specified
* key wrap data. This is called after calling
* {@link #addCryptoContext(byte[], ICryptoContext)} to
* indicate the old wrapping crypto context should no longer be
* necessary.
*
* @param wrapdata wrapping key wrap data.
*/
public void removeCryptoContext(final byte[] wrapdata);
}
| 1,729 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslEncoderException.java
|
/**
* Copyright (c) 2015-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.io;
/**
* <p>A MSL encoder exception is thrown by the MSL encoding abstraction classes
* when there is a problem.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MslEncoderException extends Exception {
private static final long serialVersionUID = -6338714624096298489L;
/**
* <p>Construct a new MSL encoder exception with the provided message.</p>
*
* @param message the detail message.
*/
public MslEncoderException(final String message) {
super(message);
}
/**
* <p>Construct a new MSL encoder exception with the provided cause.</p>
*
* @param cause the cause of the exception.
*/
public MslEncoderException(final Throwable cause) {
super(cause);
}
/**
* <p>Construct a new MSL encoder exception with the provided message and
* cause.</p>
*
* @param message the detail message.
* @param cause the cause of the exception.
*/
public MslEncoderException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 1,730 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslEncoderFactory.java
|
/**
* Copyright (c) 2015-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.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.util.Base64;
/**
* <p>An abstract factory class for producing {@link MslTokenizer},
* {@link MslObject}, and {@link MslArray} instances of various encoder
* formats.</p>
*
* <p>A concrete implementations must identify its supported and preferred
* encoder formats and provide implementations for encoding and decoding those
* formats.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class MslEncoderFactory {
/**
* <p>Escape and quote a string for print purposes.</p>
*
* <p>This is based on the org.json {@code MslObject.quote()} code.</p>
*
* @param string the string to quote. May be {@code null}.
* @return the quoted string.
*/
static String quote(final String string) {
final StringBuilder sb = new StringBuilder();
// Return "" for null or zero-length string.
if (string == null || string.length() == 0) {
sb.append("\"\"");
return sb.toString();
}
char c = 0;
final int len = string.length();
sb.append('"');
for (int i = 0; i < len; i += 1) {
final char b = c;
c = string.charAt(i);
switch (c) {
case '\\':
case '"':
sb.append('\\');
sb.append(c);
break;
case '/':
if (b == '<') {
sb.append('\\');
}
sb.append(c);
break;
case '\b':
sb.append("\\b");
break;
case '\t':
sb.append("\\t");
break;
case '\n':
sb.append("\\n");
break;
case '\f':
sb.append("\\f");
break;
case '\r':
sb.append("\\r");
break;
default:
if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
|| (c >= '\u2000' && c < '\u2100'))
{
sb.append("\\u");
final String hhhh = Integer.toHexString(c);
sb.append("0000", 0, 4 - hhhh.length());
sb.append(hhhh);
} else {
sb.append(c);
}
}
}
sb.append('"');
return sb.toString();
}
/**
* <p>Convert a value to a string for print purposes.</p>
*
* <p>This is based on the org.json {@code MslObject.writeValue()} code.</p>
*
* @param value the value to convert to a string. May be {@code null}.
* @return the string.
*/
@SuppressWarnings("unchecked")
static String stringify(final Object value) {
if (value == null || value.equals(null)) {
return "null";
} else if (value instanceof MslObject || value instanceof MslArray) {
return value.toString();
} else if (value instanceof Map) {
return new MslObject((Map<?,?>)value).toString();
} else if (value instanceof Collection) {
return new MslArray((Collection<Object>)value).toString();
} else if (value instanceof Object[]) {
return new MslArray((Object[])value).toString();
} else if (value instanceof Number || value instanceof Boolean) {
return value.toString();
} else if (value instanceof byte[]) {
return Base64.encode((byte[])value);
} else {
return quote(value.toString());
}
}
/**
* Returns the most preferred encoder format from the provided set of
* formats.
*
* @param formats the set of formats to choose from. May be {@code null} or
* empty.
* @return the preferred format from the provided set or the default format
* if format set is {@code null} or empty.
*/
public abstract MslEncoderFormat getPreferredFormat(final Set<MslEncoderFormat> formats);
/**
* Create a new {@link MslTokenizer}. The encoder format will be
* determined by inspecting the byte stream identifier located in the first
* byte.
*
* @param source the binary data to tokenize.
* @return the {@link MslTokenizer}.
* @throws IOException if there is a problem reading the byte stream
* identifier.
* @throws MslEncoderException if the encoder format is not recognized or
* is not supported.
*/
public MslTokenizer createTokenizer(final InputStream source) throws IOException, MslEncoderException {
// Read the byte stream identifier (and only the identifier).
final InputStream bufferedSource = source.markSupported() ? source : new UnsynchronizedBufferedInputStream(source);
bufferedSource.mark(1);
final byte id = (byte)bufferedSource.read();
if (id == -1)
throw new MslEncoderException("End of stream reached when attempting to read the byte stream identifier.");
// Identify the encoder format.
final MslEncoderFormat format = MslEncoderFormat.getFormat(id);
if (format == null)
throw new MslEncoderException("Unidentified encoder format ID: (byte)" + id + ".");
// Reset the input stream and return the tokenizer.
bufferedSource.reset();
return generateTokenizer(bufferedSource, format);
}
/**
* Create a new {@link MslTokenizer} of the specified encoder format.
*
* @param source the binary data to tokenize.
* @param format the encoder format.
* @return the {@link MslTokenizer}.
* @throws MslEncoderException if the encoder format is not supported.
*/
protected abstract MslTokenizer generateTokenizer(final InputStream source, final MslEncoderFormat format) throws MslEncoderException;
/**
* Create a new {@link MslObject}.
*
* @return the {@link MslObject}.
*/
public MslObject createObject() {
return createObject(null);
}
/**
* Create a new {@link MslObject} populated with the provided map.
*
* @param map the map of name/value pairs. This must be a map of
* {@code String}s onto {@code Object}s. May be {@code null}.
* @return the {@link MslObject}.
* @throws IllegalArgumentException if one of the values is of an
* unsupported type.
*/
public MslObject createObject(final Map<String,Object> map) {
return new MslObject(map);
}
/**
* Identify the encoder format of the {@link MslObject} of the encoded
* data. The format will be identified by inspecting the byte stream
* identifier located in the first byte.
*
* @param encoding the encoded data.
* @return the encoder format.
* @throws MslEncoderException if the encoder format cannot be identified
* or there is an error parsing the encoder format ID.
*/
public MslEncoderFormat parseFormat(final byte[] encoding) throws MslEncoderException {
// Fail if the encoding is too short.
if (encoding.length < 1)
throw new MslEncoderException("No encoding identifier found.");
// Identify the encoder format.
final byte id = encoding[0];
final MslEncoderFormat format = MslEncoderFormat.getFormat(id);
if (format == null)
throw new MslEncoderException("Unidentified encoder format ID: (byte)" + id + ".");
return format;
}
/**
* Parse a {@link MslObject} from encoded data. The encoder format will be
* determined by inspecting the byte stream identifier located in the first
* byte.
*
* @param encoding the encoded data to parse.
* @return the {@link MslObject}.
* @throws MslEncoderException if the encoder format is not supported or
* there is an error parsing the encoded data.
*/
public abstract MslObject parseObject(final byte[] encoding) throws MslEncoderException;
/**
* Encode a {@link MslObject} into the specified encoder format.
*
* @param object the {@link MslObject} to encode.
* @param format the encoder format.
* @return the encoded data.
* @throws MslEncoderException if the encoder format is not supported or
* there is an error encoding the object.
*/
public abstract byte[] encodeObject(final MslObject object, final MslEncoderFormat format) throws MslEncoderException;
/**
* Create a new {@link MslArray}.
*
* @return the {@link MslArray}.
*/
public MslArray createArray() {
return createArray(null);
}
/**
* Create a new {@link MslArray} populated with the provided values.
*
* @param collection the collection of values. May be {@code null}.
* @return the {@link MslArray}.
* @throws IllegalArgumentException if one of the values is of an
* unsupported type.
*/
public MslArray createArray(final Collection<?> collection) {
return new MslArray(collection);
}
}
| 1,731 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/JsonMslObject.java
|
/**
* Copyright (c) 2015-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.io;
import java.nio.charset.Charset;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.util.Base64;
/**
* <p>A {@code MslObject} that encodes its data as UTF-8 JSON.</p>
*
* <p>This implementation is backed by {@code org.json}.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class JsonMslObject extends MslObject implements JSONString {
/** UTF-8 charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/**
* Returns a JSON MSL encoding of provided MSL object.
*
* @param encoder the encoder factory.
* @param object the MSL object.
* @return the encoded data.
* @throws MslEncoderException if there is an error encoding the data.
*/
public static byte[] getEncoded(final MslEncoderFactory encoder, final MslObject object) throws MslEncoderException {
if (object instanceof JsonMslObject)
return ((JsonMslObject)object).toJSONString().getBytes(UTF_8);
final JsonMslObject jsonObject = new JsonMslObject(encoder, object);
return jsonObject.toJSONString().getBytes(UTF_8);
}
/**
* Create a new {@code JsonMslObject} from the given {@code MslObject}.
*
* @param encoder the encoder factory.
* @param o the {@code MslObject}.
* @throws MslEncoderException if the MSL object contains an unsupported
* type.
*/
public JsonMslObject(final MslEncoderFactory encoder, final MslObject o) throws MslEncoderException {
this.encoder = encoder;
try {
for (final String key : o.getKeys())
put(key, o.opt(key));
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL object encoding.", e);
}
}
/**
* Create a new {@code JsonMslObject} from the given {@code JSONObject}.
*
* @param encoder the encoder factory.
* @param jo the {@code JSONObject}.
* @throws MslEncoderException if the JSON object contains an unsupported
* type.
*/
public JsonMslObject(final MslEncoderFactory encoder, final JSONObject jo) throws MslEncoderException {
this.encoder = encoder;
try {
for (final Object key : jo.keySet()) {
if (!(key instanceof String))
throw new MslEncoderException("Invalid JSON object encoding.");
put((String)key, jo.opt((String)key));
}
} catch (final JSONException e) {
throw new MslEncoderException("Invalid JSON object encoding.", e);
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL object encoding.", e);
}
}
/**
* Create a new {@code JsonMslObject} from its encoded representation.
*
* @param encoder the encoder factory.
* @param encoding the encoded data.
* @throws MslEncoderException if the data is malformed or invalid.
*/
public JsonMslObject(final MslEncoderFactory encoder, final byte[] encoding) throws MslEncoderException {
this.encoder = encoder;
try {
final String json = new String(encoding, UTF_8);
final JSONObject jo = new JSONObject(json);
for (final Object key : jo.keySet()) {
if (!(key instanceof String))
throw new MslEncoderException("Invalid JSON object encoding.");
put((String)key, jo.opt((String)key));
}
} catch (final JSONException e) {
throw new MslEncoderException("Invalid JSON object encoding.", e);
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL object encoding.", e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslObject#put(java.lang.String, java.lang.Object)
*/
@Override
public MslObject put(final String key, final Object value) {
final Object o;
try {
// Convert JSONObject to MslObject.
if (value instanceof JSONObject)
o = new JsonMslObject(encoder, (JSONObject)value);
// Convert JSONArray to a MslArray.
else if (value instanceof JSONArray)
o = new JsonMslArray(encoder, (JSONArray)value);
// All other types are OK as-is.
else
o = value;
} catch (final MslEncoderException e) {
throw new IllegalArgumentException("Unsupported JSON object or array representation.", e);
}
return super.put(key, o);
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslObject#getBytes(java.lang.String)
*/
@Override
public byte[] getBytes(final String key) throws MslEncoderException {
// When a JsonMslObject is decoded, there's no way for us to know if a
// value is supposed to be a String to byte[]. Therefore interpret
// Strings as Base64-encoded data consistent with the toJSONString()
// and getEncoded().
final Object value = get(key);
if (value instanceof byte[])
return (byte[])value;
if (value instanceof String) {
try {
return Base64.decode((String)value);
} catch (final IllegalArgumentException e) {
// Fall through.
}
}
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not binary data.");
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslObject#optBytes(java.lang.String)
*/
@Override
public byte[] optBytes(final String key) {
return optBytes(key, new byte[0]);
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslObject#optBytes(java.lang.String, byte[])
*/
@Override
public byte[] optBytes(final String key, final byte[] defaultValue) {
// When a JsonMslObject is decoded, there's no way for us to know if a
// value is supposed to be a String to byte[]. Therefore interpret
// Strings as Base64-encoded data consistent with the toJSONString()
// and getEncoded().
final Object value = opt(key);
if (value instanceof byte[])
return (byte[])value;
if (value instanceof String) {
try {
return Base64.decode((String)value);
} catch (final IllegalArgumentException e) {
// Fall through.
}
}
return defaultValue;
}
/* (non-Javadoc)
* @see org.json.JSONString#toJSONString()
*/
@Override
public String toJSONString() {
try {
final JSONObject jo = new JSONObject();
final Set<String> keys = getKeys();
for (final String key : keys) {
final Object value = opt(key);
if (value instanceof byte[]) {
jo.put(key, Base64.encode((byte[])value));
} else if (value instanceof JsonMslObject || value instanceof JsonMslArray) {
jo.put(key, value);
} else if (value instanceof MslObject) {
final JsonMslObject jsonValue = new JsonMslObject(encoder, (MslObject)value);
jo.put(key, jsonValue);
} else if (value instanceof MslArray) {
final JsonMslArray jsonValue = new JsonMslArray(encoder, (MslArray)value);
jo.put(key, jsonValue);
} else if (value instanceof MslEncodable) {
final byte[] json = ((MslEncodable)value).toMslEncoding(encoder, MslEncoderFormat.JSON);
final JsonMslObject jsonValue = new JsonMslObject(encoder, json);
jo.put(key, jsonValue);
} else {
jo.put(key, value);
}
}
return jo.toString();
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
} catch (final MslEncoderException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
} catch (final JSONException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslObject#toString()
*/
@Override
public String toString() {
return toJSONString();
}
/** MSL encoder factory. */
private final MslEncoderFactory encoder;
}
| 1,732 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/ThriftyUtf8Reader.java
|
/**
* Copyright (c) 2017-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.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
/**
* <p>A specialized UTF-8 reader that only reads exactly the number of bytes
* necessary to decode the character, and does not close the underlying input
* stream. This ensures any unneeded bytes remain on the input stream, which
* can then be reused.</p>
*
* <p>Based on Andy Clark's
* {@code com.sun.org.apache.xerces.internal.impl.io.UTF8Reader}.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class ThriftyUtf8Reader extends Reader {
/** Default byte buffer size (8192). */
public static final int DEFAULT_BUFFER_SIZE = 16384;
/** Malformed replacement character. */
public static final char MALFORMED_CHAR = 0xFFFD;
/** Input stream. */
private final InputStream fInputStream;
/** Byte buffer. */
private final byte[] fBuffer = new byte[DEFAULT_BUFFER_SIZE];
/** Current buffer read position. */
private int fIndex = 0;
/** Number of valid bytes in the buffer. */
private int fOffset = 0;
/** Pending character. */
private int fPending = -1;
/** Surrogate character. */
private int fSurrogate = -1;
/**
* Create a new thrifty UTF-8 reader that will read data off the provided
* input stream.
*
* @param inputStream the underlying input stream.
*/
public ThriftyUtf8Reader(final InputStream inputStream) {
fInputStream = inputStream;
}
@Override
public int read() throws IOException {
// Return any surrogate.
if (fSurrogate != -1) {
final int c = fSurrogate;
fSurrogate = -1;
return c;
}
// Read the first byte or use the pending character.
final int b0;
if (fPending != -1) {
b0 = fPending;
fPending = -1;
} else {
b0 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b0 == -1)
return -1;
}
// UTF-8: [0xxx xxxx]
// Unicode: [0000 0000] [0xxx xxxx]
if (b0 < 0x80)
return (char)b0;
// UTF-8: [110y yyyy] [10xx xxxx]
// Unicode: [0000 0yyy] [yyxx xxxx]
if ((b0 & 0xE0) == 0xC0) {
final int b1 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b1 == -1)
return MALFORMED_CHAR;
if ((b1 & 0xC0) != 0x80) {
fPending = b1;
return MALFORMED_CHAR;
}
// Make sure the decoded value is not below the first code point of
// a 2-byte sequence.
if ((b0 & 0x1E) == 0)
return MALFORMED_CHAR;
return ((b0 << 6) & 0x07C0) | (b1 & 0x003F);
}
// UTF-8: [1110 zzzz] [10yy yyyy] [10xx xxxx]
// Unicode: [zzzz yyyy] [yyxx xxxx]
if ((b0 & 0xF0) == 0xE0) {
final int b1 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b1 == -1)
return MALFORMED_CHAR;
if ((b1 & 0xC0) != 0x80) {
fPending = b1;
return MALFORMED_CHAR;
}
final int b2 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b2 == -1)
return MALFORMED_CHAR;
if ((b2 & 0xC0) != 0x80) {
fPending = b2;
return MALFORMED_CHAR;
}
// Make sure the decoded value is not:
//
// 1. A surrogate character (0xD800 - 0xDFFF).
// 2. Below the first code point of a 3-byte sequence.
// 3. Equal to 0xFFFE or 0xFFFF.
if ((b0 == 0xED && b1 >= 0xA0)
|| ((b0 & 0x0F) == 0 && (b1 & 0x20) == 0)
|| (b0 == 0xEF && (b1 & 0x3F) == 0x3F && (b2 & 0x3E) == 0x3E))
{
return MALFORMED_CHAR;
}
return ((b0 << 12) & 0xF000) | ((b1 << 6) & 0x0FC0) | (b2 & 0x003F);
}
// UTF-8: [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]*
// Unicode: [1101 10ww] [wwzz zzyy] (high surrogate)
// [1101 11yy] [yyxx xxxx] (low surrogate)
// * uuuuu = wwww + 1
if ((b0 & 0xF8) == 0xF0) {
final int b1 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b1 == -1)
return MALFORMED_CHAR;
if ((b1 & 0xC0) != 0x80) {
fPending = b1;
return MALFORMED_CHAR;
}
final int b2 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b2 == -1)
return MALFORMED_CHAR;
if ((b2 & 0xC0) != 0x80) {
fPending = b2;
return MALFORMED_CHAR;
}
final int b3 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b3 == -1)
return MALFORMED_CHAR;
if ((b3 & 0xC0) != 0x80) {
fPending = b3;
return MALFORMED_CHAR;
}
// Make sure the decoded value is not below the first code point of
// a 4-byte sequence.
if ((b0 & 0x07) == 0 && (b1 & 0x30) == 0)
return MALFORMED_CHAR;
final int uuuuu = ((b0 << 2) & 0x001C) | ((b1 >> 4) & 0x0003);
// Make sure the decoded value is not above the Unicode plane 0x10.
if (uuuuu > 0x10)
return MALFORMED_CHAR;
final int wwww = uuuuu - 1;
final int hs = 0xD800 |
((wwww << 6) & 0x03C0) | ((b1 << 2) & 0x003C) |
((b2 >> 4) & 0x0003);
final int ls = 0xDC00 | ((b2 << 6) & 0x03C0) | (b3 & 0x003F);
fSurrogate = ls;
return hs;
}
// UTF-8: [1111 10uu] [10uu zzzz] [10yy yyyy] [10xx xxxx] [10ww wwww]
// Unicode: invalid
if ((b0 & 0xFC) == 0xF8) {
final int b1 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b1 == -1)
return MALFORMED_CHAR;
if ((b1 & 0xC0) != 0x80) {
fPending = b1;
return MALFORMED_CHAR;
}
final int b2 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b2 == -1)
return MALFORMED_CHAR;
if ((b2 & 0xC0) != 0x80) {
fPending = b2;
return MALFORMED_CHAR;
}
final int b3 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b3 == -1)
return MALFORMED_CHAR;
if ((b3 & 0xC0) != 0x80) {
fPending = b3;
return MALFORMED_CHAR;
}
final int b4 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b4 == -1)
return MALFORMED_CHAR;
if ((b4 & 0xC0) != 0x80) {
fPending = b4;
return MALFORMED_CHAR;
}
return MALFORMED_CHAR;
}
// UTF-8: [1111 110u] [10uu zzzz] [10yy yyyy] [10xx xxxx] [10ww wwww] [10vv vvvv]
// Unicode: invalid
if ((b0 & 0xFE) == 0xFC) {
final int b1 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b1 == -1)
return MALFORMED_CHAR;
if ((b1 & 0xC0) != 0x80) {
fPending = b1;
return MALFORMED_CHAR;
}
final int b2 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b2 == -1)
return MALFORMED_CHAR;
if ((b2 & 0xC0) != 0x80) {
fPending = b2;
return MALFORMED_CHAR;
}
final int b3 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b3 == -1)
return MALFORMED_CHAR;
if ((b3 & 0xC0) != 0x80) {
fPending = b3;
return MALFORMED_CHAR;
}
final int b4 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b4 == -1)
return MALFORMED_CHAR;
if ((b4 & 0xC0) != 0x80) {
fPending = b4;
return MALFORMED_CHAR;
}
final int b5 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b5 == -1)
return MALFORMED_CHAR;
if ((b5 & 0xC0) != 0x80) {
fPending = b5;
return MALFORMED_CHAR;
}
return MALFORMED_CHAR;
}
// Error.
return MALFORMED_CHAR;
}
@Override
public int read(final char ch[], int offset, int length) throws IOException {
int numRead = 0;
// Start with any surrogate.
if (fSurrogate != -1) {
ch[offset++] = (char)fSurrogate;
fSurrogate = -1;
--length;
++numRead;
}
// If there are no available bytes in the buffer...
if (fIndex >= fOffset) {
// Read at most buffer size bytes.
if (length > fBuffer.length)
length = fBuffer.length;
final int count = fInputStream.read(fBuffer, 0, length);
// If we could not read anymore, return the number of characters
// read so far or end-of-stream.
if (count == -1)
return (numRead > 0) ? numRead : -1;
// Start reading from the beginning of the buffer, up to the number
// of valid bytes.
fIndex = 0;
fOffset = count;
}
// Read bytes (out of the buffer) until the buffer is empty or we have
// all of the characters requested.
while (fIndex < fOffset && numRead < length) {
final int c = read();
// If we could not read anymore, return the number of characters
// read so far or end-of-stream.
if (c == -1)
return (numRead > 0) ? numRead : -1;
// Populate the character array.
ch[offset++] = (char)c;
++numRead;
}
// To avoid recursing forever or from blocking too long, return with
// what we have so far.
return numRead;
}
@Override
public long skip(final long n) throws IOException {
// Don't pass skip down to the backing input stream since we're being
// asked to skip characters and not bytes.
long remaining = n;
final char[] ch = new char[fBuffer.length];
do {
final int length = ch.length < remaining ? ch.length : (int)remaining;
final int count = read(ch, 0, length);
if (count > 0)
remaining -= count;
else
break;
} while (remaining > 0);
final long skipped = n - remaining;
return skipped;
}
/**
* Tell whether this stream supports the mark() operation.
*/
@Override
public boolean markSupported() {
return fInputStream.markSupported();
}
@Override
public void mark(final int readLimit) throws IOException {
// This is complicated because the read limit is in characters but the
// backing input stream is in bytes. If we really want to be safe then
// we need to multiply by the maximum number of bytes per character.
// Account for overflow.
final long byteLimit = 6 * readLimit;
final int safeLimit = (byteLimit < 0 || byteLimit > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int)byteLimit;
fInputStream.mark(safeLimit);
}
@Override
public void reset() throws IOException {
fOffset = 0;
fSurrogate = -1;
fInputStream.reset();
}
@Override
public void close() {
// Explicitly do not close the backing input stream for our use case.
// This is because we are using ThriftyUtf8Reader inside a stream
// parser.
}
}
| 1,733 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/Url.java
|
/**
* Copyright (c) 2012-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.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The URL interface provides access to an input stream and output stream tied
* to a specific URL.
*
* @author Wesley Miaw <[email protected]>
*/
public interface Url {
/**
* The Connection interface represents a communication link between the
* application and a URL.
*/
public static interface Connection {
/**
* <p>Returns an input stream that reads from this connection.</p>
*
* <p>Asking for the input stream must not prevent use of the output
* stream, but reading from the input stream may prevent further
* writing to the output stream.</p>
*
* <p>The returned input stream must support
* {@link InputStream#mark(int)}, {@link InputStream#reset()}, and
* {@link InputStream#skip(long)} if you wish to use it for more than
* one MSL message.</p>
*
* @return an input stream that reads from this connection.
* @throws IOException if an I/O error occurs while creating the input
* stream.
*/
public InputStream getInputStream() throws IOException;
/**
* <p>Returns an output stream that writes to this connection.</p>
*
* <p>Asking for the output stream must not prevent use of the input
* stream, but writing to the output stream may prevent further reading
* from the input stream.</p>
*
* @return an output stream that writes to this connection.
* @throws IOException if an I/O error occurs while creating the output
* stream.
*/
public OutputStream getOutputStream() throws IOException;
}
/**
* Set the timeout.
*
* @param timeout connect/read/write timeout in milliseconds.
*/
public void setTimeout(final int timeout);
/**
* Open a new connection to the target location.
*
* @return a {@link Connection} linking to the URL.
* @throws IOException if an I/O exception occurs.
*/
public Connection openConnection() throws IOException;
}
| 1,734 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/LZWInputStream.java
|
/**
* Copyright (c) 2013-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.io;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* <p>This class implements a stream filter for reading compressed data in the
* LZW format.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class LZWInputStream extends InputStream {
/** Maximum number of values represented by a byte. */
private static final int BYTE_RANGE = 256;
/** The initial dictionary. */
private static final Map<Integer,byte[]> INITIAL_DICTIONARY = new HashMap<Integer,byte[]>(BYTE_RANGE);
static {
for (int i = 0; i < BYTE_RANGE; ++i) {
byte[] data = { (byte)i };
INITIAL_DICTIONARY.put(i, data);
}
}
/**
* Creates a new input stream.
*
* @param in the input stream.
*/
public LZWInputStream(final InputStream in) {
this.in = in;
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
/* (non-Javadoc)
* @see java.io.InputStream#close()
*/
@Override
public void close() throws IOException {
if (!closed) {
closed = true;
in.close();
}
}
/* (non-Javadoc)
* @see java.io.InputStream#read()
*/
@Override
public int read() throws IOException {
if (closed)
throw new IOException("Input stream is closed.");
// Grab another byte if we need one. Check for end of stream.
if (buffer.size() == 0) {
final byte[] b = new byte[1];
int available = decompress(b, 0, 1);
if (available == -1)
return -1;
return b[0];
}
// Return the next byte.
return buffer.remove();
}
/* (non-Javadoc)
* @see java.io.InputStream#read(byte[], int, int)
*/
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
if (closed)
throw new IOException("Input stream is closed.");
if (off > 0)
throw new IndexOutOfBoundsException("Specified offset cannot be negative.");
if (len < 0)
throw new IndexOutOfBoundsException("Specified length cannot be negative.");
if (len > b.length - off)
throw new IndexOutOfBoundsException("Requested length exceeds buffer size at offset.");
// Copy as many bytes as we have buffered.
int offset = off;
int needed = len;
while (needed > 0 && buffer.size() > 0) {
b[offset++] = buffer.remove();
--needed;
}
// If we don't need any more then we're done.
if (needed == 0)
return len;
// Grab any more bytes that we need. Check for end of stream.
int read = decompress(b, offset, needed);
if (read == -1) {
if (needed == len)
return -1;
return len - needed;
}
needed -= read;
// Return the number of bytes we read.
return len - needed;
}
/**
* Reads compressed data from the underlying input stream and decompresses
* the codes to the original data.
*
* @param b the buffer into which the data is read.
* @param off the start offset in array b at which the data is written.
* @param len the maximum number of bytes to read.
* @return the number of bytes decoded into the buffer.
* @throws IOException if there is an error reading from the code stream.
*/
private int decompress(final byte[] b, final int off, final int len) throws IOException {
int totalRead = 0;
while (totalRead < len) {
// The number of bytes we need is equal to the number of bits we
// need rounded up to the next full byte.
final int bitsAvailable = codes.size() * Byte.SIZE - codeOffset;
final int bitsNeeded = bits - bitsAvailable;
final int bytesNeeded = (bitsNeeded / Byte.SIZE) + (bitsNeeded % 8 != 0 ? 1 : 0);
// Read bytes until we have enough for a code value. If we aren't
// able to read enough then we've hit end of stream.
final byte[] codeBytes = new byte[bytesNeeded];
int bytesRead = 0;
while (bytesRead < bytesNeeded) {
int read = in.read(codeBytes, bytesRead, codeBytes.length - bytesRead);
if (read == -1) {
// If we haven't buffered anything then return end of
// stream.
if (totalRead == 0) return -1;
return totalRead;
}
bytesRead += read;
}
// Append read bytes to the buffered code bytes.
for (final byte codeByte : codeBytes)
codes.add(codeByte);
// Now decode the next code.
int value = 0;
int bitsDecoded = 0;
while (bitsDecoded < bits) {
// Read the next batch of bits.
final int bitlen = Math.min(bits - bitsDecoded, Byte.SIZE - codeOffset);
int msbits = codes.peek();
// First shift left to erase the most significant bits then
// shift right to get the correct number of bits.
msbits <<= codeOffset;
msbits &= 0xff;
msbits >>>= Byte.SIZE - bitlen;
// If we read to the end of this byte then zero the code bit
// offset and remove the byte.
bitsDecoded += bitlen;
codeOffset += bitlen;
if (codeOffset == Byte.SIZE) {
codeOffset = 0;
codes.remove();
}
// Shift left by the number of bits remaining to decode and add
// the current bits to the value.
value |= (msbits & 0xff) << (bits - bitsDecoded);
}
// Grab the bytes for this code.
byte[] data = dictionary.get(value);
// This is the first iteration. The next code will have a larger
// bit length.
if (prevdata.size() == 0) {
++bits;
}
// If there is previous data then add the previous data plus this
// data's first character to the dictionary.
else {
// If the code was not in the dictionary then we have
// encountered the code that we are going to enter into the
// dictionary right now.
//
// This is the odd case where the decoder is one code behind
// the encoder in populating the dictionary and the byte that
// will be added to create the sequence is equal to the first
// byte of the previous sequence.
if (data == null) {
final byte[] prevbytes = prevdata.toByteArray();
prevdata.write(prevbytes[0]);
} else {
prevdata.write(data[0]);
}
// Add the dictionary entry.
dictionary.put(dictionary.size(), prevdata.toByteArray());
prevdata.reset();
// If we just generated the code for 2^p - 1 then increment the
// code bit length.
if (dictionary.size() == (1 << bits))
++bits;
// If the code was not in the dictionary before, it should be
// now. Grab the data.
if (data == null)
data = dictionary.get(value);
}
// Append the decoded bytes to the provided buffer or the internal
// buffer.
for (final byte d : data) {
if (totalRead < len)
b[off + totalRead++] = d;
else
buffer.add(d);
}
// Save this data for the next iteration.
prevdata.write(data);
}
// Return the number of bytes decoded.
return totalRead;
}
/** Input stream. */
private final InputStream in;
/** The dictionary of bytes keyed off codes. */
private final Map<Integer,byte[]> dictionary = new HashMap<Integer,byte[]>(INITIAL_DICTIONARY);
/** Buffered code bytes. */
private final LinkedList<Byte> codes = new LinkedList<Byte>();
/** Current codebyte bit offset. */
private int codeOffset = 0;
/** Current bit length. */
private int bits = Byte.SIZE;
/** Buffered bytes pending read. */
private final LinkedList<Byte> buffer = new LinkedList<Byte>();
/** Previously buffered bytes. */
private final ByteArrayOutputStream prevdata = new ByteArrayOutputStream();
/** Stream closed. */
private boolean closed = false;
}
| 1,735 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslObject.java
|
/**
* Copyright (c) 2015-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.io;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* <p>A {@code MslObject} is an unordered collection of name/value pairs. It is
* functionally equivalent to a JSON object, in that it encodes the pair data
* without imposing any specific order and may contain more or less pairs than
* explicitly defined.</p>
*
* <p>The values can be any of these types: <code>Boolean</code>,
* <code>Byte[]</code> <code>MslArray</code>, <code>MslObject</code>,
* <code>Number</code>, or <code>String</code>. <code>Enum</code> is also
* accepted and will be converted to a <code>String</code> using its
* {@code name()} method.</p>
*
* <p>The generic <code>get()</code> and <code>opt()</code> methods return
* an object, which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and type
* coercion for you. The opt methods differ from the get methods in that they
* do not throw. Instead, they return a specified value, such as null.</p>
*
* <p>The <code>put</code> methods add or replace values in an object.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MslObject {
/**
* Create a new empty {@code MslObject}.
*/
public MslObject() {
}
/**
* Create a new {@code MslObject} from the given map.
*
* @param map the map of name/value pairs. This must be a map of
* {@code String}s onto values. May be {@code null}.
* @throws IllegalArgumentException if one of the values is of an
* unsupported type.
*/
public MslObject(final Map<?,?> map) {
if (map != null) {
for (final Map.Entry<?, ?> entry : map.entrySet()) {
final Object key = entry.getKey();
if (!(key instanceof String))
throw new IllegalArgumentException("Map key is not a string.");
final Object value = entry.getValue();
put((String)key, value);
}
}
}
/** Object map. */
private final Map<String,Object> map = new HashMap<String,Object>();
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of a proper
* type or the value is {@code null}.
*/
@SuppressWarnings("unchecked")
public Object get(final String key) throws MslEncoderException {
if (key == null)
throw new IllegalArgumentException("Null key.");
final Object o = map.get(key);
if (o == null)
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] not found.");
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
return o;
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public boolean getBoolean(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof Boolean)
return (Boolean)o;
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a boolean.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public byte[] getBytes(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof byte[])
return (byte[])o;
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not binary data.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public double getDouble(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof Number)
return ((Number)o).doubleValue();
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a number.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public int getInt(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof Number)
return ((Number)o).intValue();
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a number.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public MslArray getMslArray(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof MslArray)
return (MslArray)o;
if (o instanceof Object[])
return new MslArray((Object[])o);
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a MslArray.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @param encoder the MSL encoder factory.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public MslObject getMslObject(final String key, final MslEncoderFactory encoder) throws MslEncoderException {
final Object o = get(key);
if (o instanceof MslObject)
return (MslObject)o;
/* FIXME: How should we handle MslEncodable?
if (o instanceof MslEncodable)
return ((MslEncodable)o).toMslObject(encoder);
*/
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof byte[]) {
try {
return encoder.parseObject((byte[])o);
} catch (final MslEncoderException e) {
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a MslObject.");
}
}
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a MslObject.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public long getLong(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof Number)
return ((Number)o).longValue();
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a number.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public String getString(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof String)
return (String)o;
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a string.");
}
/**
* Return true if the specified key exists. The value may be {@code null}.
*
* @param key the key.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public boolean has(final String key) {
if (key == null)
throw new IllegalArgumentException("Null key.");
return map.containsKey(key);
}
/**
* Return the value associated with the specified key or {@code null} if
* the key is unknown or the value is an unsupported type.
*
* @param key the key.
* @return the value. May be {@code null}.
* @throws IllegalArgumentException if the key is {@code null}.
*/
@SuppressWarnings("unchecked")
public Object opt(final String key) {
if (key == null)
throw new IllegalArgumentException("Null key.");
final Object o = map.get(key);
try {
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
} catch (final IllegalArgumentException e) {
return null;
}
return o;
}
/**
* Return the value associated with the specified key or {@code false} if
* the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public boolean optBoolean(final String key) {
return optBoolean(key, false);
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public boolean optBoolean(final String key, final boolean defaultValue) {
final Object o = opt(key);
if (o instanceof Boolean)
return (Boolean)o;
return defaultValue;
}
/**
* Return the value associated with the specified key or an empty byte
* array if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public byte[] optBytes(final String key) {
return optBytes(key, new byte[0]);
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public byte[] optBytes(final String key, final byte[] defaultValue) {
final Object o = opt(key);
if (o instanceof byte[])
return (byte[])o;
return defaultValue;
}
/**
* Return the value associated with the specified key or {@code NaN} if
* the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public double optDouble(final String key) {
return optDouble(key, Double.NaN);
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public double optDouble(final String key, final double defaultValue) {
final Object o = opt(key);
if (o instanceof Number)
return ((Number)o).doubleValue();
return defaultValue;
}
/**
* Return the value associated with the specified key or zero if
* the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public int optInt(final String key) {
return optInt(key, 0);
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public int optInt(final String key, final int defaultValue) {
final Object o = opt(key);
if (o instanceof Number)
return ((Number)o).intValue();
return defaultValue;
}
/**
* Return the {@code MslArray} associated with the specified key or
* {@code null} if the key is unknown or the value is not of the correct
* type.
*
* @param key the key.
* @return the {@code MslArray} or {@code null}.
* @throws IllegalArgumentException if the key is {@code null}.
*/
@SuppressWarnings("unchecked")
public MslArray optMslArray(final String key) {
final Object o = opt(key);
if (o instanceof MslArray)
return (MslArray)o;
try {
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
} catch (final IllegalArgumentException e) {
return null;
}
return null;
}
/**
* Return the {@code MslObject} associated with the specified key or
* {@code null} if the key unknown or the value is not of the correct type.
*
* @param key the key.
* @param encoder the MSL encoder factory.
* @return the {@code MslObject} or {@code null}.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject optMslObject(final String key, final MslEncoderFactory encoder) {
final Object o = opt(key);
if (o instanceof MslObject)
return (MslObject)o;
/* FIXME: How should we handle MslEncodable?
if (o instanceof MslEncodable) {
try {
return ((MslEncodable)o).toMslObject(encoder);
} catch (final MslEncoderException e) {
// Drop through.
}
}
*/
if (o instanceof Map) {
try {
return new MslObject((Map<?,?>)o);
} catch (final IllegalArgumentException e) {
return null;
}
}
if (o instanceof byte[]) {
try {
return encoder.parseObject((byte[])o);
} catch (final MslEncoderException e) {
return null;
}
}
return null;
}
/**
* Return the value associated with the specified key or zero if
* the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public long optLong(final String key) {
return optLong(key, 0);
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public long optLong(final String key, final long defaultValue) {
final Object o = opt(key);
if (o instanceof Number)
return ((Number)o).longValue();
return defaultValue;
}
/**
* Return the value associated with the specified key or the empty string
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public String optString(final String key) {
return optString(key, "");
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public String optString(final String key, final String defaultValue) {
final Object o = opt(key);
if (o instanceof String)
return (String)o;
return defaultValue;
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null} or the
* value is of an unsupported type.
*/
@SuppressWarnings("unchecked")
public MslObject put(final String key, final Object value) {
if (key == null)
throw new IllegalArgumentException("Null key.");
// Remove if requested.
if (value == null) {
map.remove(key);
return this;
}
// Otherwise set.
if (value instanceof Boolean ||
value instanceof byte[] ||
value instanceof Number ||
value instanceof MslObject ||
value instanceof MslArray ||
value instanceof String ||
value instanceof MslEncodable)
{
map.put(key, value);
}
else if (value instanceof Map)
map.put(key, new MslObject((Map<?,?>)value));
else if (value instanceof Collection)
map.put(key, new MslArray((Collection<Object>)value));
else if (value instanceof Object[])
map.put(key, new MslArray((Object[])value));
else if (value instanceof Enum)
map.put(key, ((Enum<?>)value).name());
else
throw new IllegalArgumentException("Value [" + value.getClass() + "] is an unsupported type.");
return this;
}
/**
* <p><p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putBoolean(final String key, final Boolean value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putBytes(final String key, final byte[] value) {
return put(key, value);
}
/**
* Put a key/value pair into the {@code MslObject}. The collection of
* elements will be transformed into a {@code MslArray}. If the value is
* {@code null} the key will be removed.
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null} or the value
* contains an unsupported type.
*/
public MslObject putCollection(final String key, final Collection<Object> value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putDouble(final String key, final Double value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putInt(final String key, final Integer value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putLong(final String key, final Long value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. The map of strings
* onto objects will be transformed into a {@code MslObject}. If the value
* is {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null} or one of
* the values in the map is an unsupported type.
*/
public MslObject putMap(final String key, final Map<String,Object> value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putString(final String key, final String value) {
return put(key, value);
}
/**
* Remove a key and its associated value from the {@code MslObject}.
*
* @param key the key.
* @return the removed value. May be {@code null}.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public Object remove(final String key) {
if (key == null)
throw new IllegalArgumentException("Null key.");
final Object value = opt(key);
map.remove(key);
return value;
}
/**
* Return an unmodifiable set of the {@code MslObject} keys.
*
* @return the unmodifiable set of the {@code MslObject} keys.
*/
public Set<String> getKeys() {
return Collections.unmodifiableSet(map.keySet());
}
/**
* Return an unmodifiable map of the {@code MslObject} contents.
*
* @return the unmodifiable map of {@code MslObject} contents.
*/
public Map<String,Object> getMap() {
return Collections.unmodifiableMap(map);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (!(obj instanceof MslObject)) return false;
final MslObject that = (MslObject)obj;
try {
return MslEncoderUtils.equalObjects(this, that);
} catch (final MslEncoderException e) {
return false;
}
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return MslEncoderUtils.hashObject(this);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// This is based on the org.json {@code MslObject.write()} code.
final StringBuilder sb = new StringBuilder();
boolean commanate = false;
final int length = map.size();
final Iterator<String> keys = map.keySet().iterator();
sb.append('{');
if (length == 1) {
final String key = keys.next();
sb.append(MslEncoderFactory.quote(key));
sb.append(':');
sb.append(MslEncoderFactory.stringify(this.map.get(key)));
} else if (length != 0) {
while (keys.hasNext()) {
final String key = keys.next();
if (commanate) {
sb.append(',');
}
sb.append(MslEncoderFactory.quote(key));
sb.append(':');
sb.append(MslEncoderFactory.stringify(this.map.get(key)));
commanate = true;
}
}
sb.append('}');
return sb.toString();
}
}
| 1,736 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslTokenizer.java
|
/**
* Copyright (c) 2015-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.io;
/**
* <p>A {@code MslTokenizer} takes in a binary source and parses out
* {@link MslObject} and {@link MslArray} instances.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class MslTokenizer {
/**
* <p>Closes the tokenizer, cleaning up any resources and preventing future
* use.</p>
*
* @throws MslEncoderException if there is an error closing the tokenizer.
*/
public void close() throws MslEncoderException {
closed = true;
}
/**
* <p>Aborts future reading off the tokenizer.</p>
*/
public void abort() {
aborted = true;
}
/**
* <p>Returns true if more objects can be read from the data source. This
* method determines that by actually trying to read the next object.</p>
*
* @param timeout read timeout in milliseconds or -1 for no timeout.
* @return true if more objects are available from the data source, false
* if the tokenizer has been aborted or closed.
* @throws MslEncoderException if the next object cannot be read or the
* source data at the current position is invalid.
*/
public boolean more(final int timeout) throws MslEncoderException {
if (aborted || closed) return false;
if (next != null) return true;
next = nextObject(timeout);
return (next != null);
}
/**
* <p>Return the next object (should be an instance of {@link MslObject} or
* {@link MslArray}) from the source data.</p>
*
* <p>If the source data's current position cannot be parsed as an object,
* an exception is thrown and the source data position's new position is
* undefined. Subsequent calls to this function should not re-throw the
* exception and instead should look for the next object. The algorithm
* used to search for the next object, and how the position should be set
* to do so, is up to the implementer and may depend upon the encoding.</p>
*
* @param timeout read timeout in milliseconds or -1 for no timeout.
* @return the next object or {@code null} if there are no more.
* @throws MslEncoderException if the next object cannot be read or the
* source data at the current position is invalid.
*/
protected abstract MslObject next(final int timeout) throws MslEncoderException;
/**
* <p>Return the next object.</p>
*
* @param timeout read timeout in milliseconds or -1 for no timeout.
* @return the next object or {@code null} if there are no more or the
* tokenizer has been aborted or closed.
* @throws MslEncoderException if the next object cannot be read or the
* source data at the current position is invalid.
*/
public MslObject nextObject(final int timeout) throws MslEncoderException {
if (aborted || closed) return null;
if (next != null) {
final MslObject mo = next;
next = null;
return mo;
}
return next(timeout);
}
/** Closed. */
private boolean closed = false;
/** Aborted. */
private boolean aborted = false;
/** Cached next object. */
private MslObject next = null;
}
| 1,737 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslEncodable.java
|
/**
* Copyright (c) 2015-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.io;
/**
* <p>This interface allows a class to override the default behavior when being
* encoded into a {@link MslObject} or {@link MslArray}.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public interface MslEncodable {
/**
* Returns the requested encoding of a MSL object representing the
* implementing class.
*
* @param encoder the encoder factory.
* @param format the encoder format.
* @return a MSL encoding of the MSL object.
* @throws MslEncoderException if the encoder format is not supported or
* there is an error encoding the data.
*/
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException;
}
| 1,738 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/JsonMslArray.java
|
/**
* Copyright (c) 2015-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.io;
import java.nio.charset.Charset;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.util.Base64;
/**
* <p>A {@code MslArray} that encodes its data as UTF-8 JSON.</p>
*
* <p>This implementation is backed by {@code org.json}.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class JsonMslArray extends MslArray implements JSONString {
/** UTF-8 charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/**
* Create a new {@code JsonMslArray} from the given {@code MslArray}.
*
* @param encoder the encoder factory.
* @param a the {@code MslArray}.
* @throws MslEncoderException if the MSL array contains an unsupported
* type.
*/
public JsonMslArray(final MslEncoderFactory encoder, final MslArray a) throws MslEncoderException {
this.encoder = encoder;
try {
for (int i = 0; i < a.size(); ++i)
put(i, a.opt(i));
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL array encoding.", e);
}
}
/**
* Create a new {@code JsonMslArray} from the given {@code JSONArray}.
*
* @param encoder the encoder factory.
* @param ja the {@code JSONArray}.
* @throws MslEncoderException if the JSON array contains an unsupported
* type.
*/
public JsonMslArray(final MslEncoderFactory encoder, final JSONArray ja) throws MslEncoderException {
this.encoder = encoder;
try {
for (int i = 0; i < ja.length(); ++i)
put(-1, ja.opt(i));
} catch (final JSONException e) {
throw new MslEncoderException("Invalid JSON array encoding.", e);
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL array encoding.", e);
}
}
/**
* Create a new {@code JsonMslArray} from its encoded representation.
*
* @param encoder the encoder factory.
* @param encoding the encoded data.
* @throws MslEncoderException if the data is malformed or invalid.
*/
public JsonMslArray(final MslEncoderFactory encoder, final byte[] encoding) throws MslEncoderException {
this.encoder = encoder;
try {
final String json = new String(encoding, UTF_8);
final JSONArray ja = new JSONArray(json);
for (int i = 0; i < ja.length(); ++i)
put(-1, ja.opt(i));
} catch (final JSONException e) {
throw new MslEncoderException("Invalid JSON array encoding.", e);
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL array encoding.", e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslArray#put(int, java.lang.Object)
*/
@Override
public MslArray put(final int index, final Object value) {
final Object o;
try {
// Convert JSONObject to MslObject.
if (value instanceof JSONObject)
o = new JsonMslObject(encoder, (JSONObject)value);
// Convert JSONarray to a MslArray.
else if (value instanceof JSONArray)
o = new JsonMslArray(encoder, (JSONArray)value);
// All other types are OK as-is.
else
o = value;
} catch (final MslEncoderException e) {
throw new IllegalArgumentException("Unsupported JSON object or array representation.", e);
}
return super.put(index, o);
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslArray#getBytes(int)
*/
@Override
public byte[] getBytes(final int index) throws MslEncoderException {
// When a JsonMslArray is decoded, there's no way for us to know if a
// value is supposed to be a String to byte[]. Therefore interpret
// Strings as Base64-encoded data consistent with the toJSONString()
// and getEncoded().
final Object value = get(index);
if (value instanceof byte[])
return (byte[])value;
if (value instanceof String) {
try {
return Base64.decode((String)value);
} catch (final IllegalArgumentException e) {
// Fall through.
}
}
throw new MslEncoderException("MslArray[" + index + "] is not binary data.");
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslArray#optBytes(int)
*/
@Override
public byte[] optBytes(final int index) {
return optBytes(index, new byte[0]);
}
public byte[] optBytes(final int index, final byte[] defaultValue) {
// When a JsonMslArray is decoded, there's no way for us to know if a
// value is supposed to be a String to byte[]. Therefore interpret
// Strings as Base64-encoded data consistent with the toJSONString()
// and getEncoded().
final Object value = opt(index);
if (value instanceof byte[])
return (byte[])value;
if (value instanceof String) {
try {
return Base64.decode((String)value);
} catch (final IllegalArgumentException e) {
// Fall through.
}
}
return defaultValue;
}
/* (non-Javadoc)
* @see org.json.JSONString#toJSONString()
*/
@Override
public String toJSONString() {
try {
final JSONArray ja = new JSONArray();
final int size = size();
for (int i = 0; i < size; ++i) {
final Object value = opt(i);
if (value instanceof byte[]) {
ja.put(i, Base64.encode((byte[])value));
} else if (value instanceof JsonMslObject || value instanceof JsonMslArray) {
ja.put(i, value);
} else if (value instanceof MslObject) {
final JsonMslObject jsonValue = new JsonMslObject(encoder, (MslObject)value);
ja.put(i, jsonValue);
} else if (value instanceof MslArray) {
final JsonMslArray jsonValue = new JsonMslArray(encoder, (MslArray)value);
ja.put(i, jsonValue);
} else if (value instanceof MslEncodable) {
final byte[] json = ((MslEncodable)value).toMslEncoding(encoder, MslEncoderFormat.JSON);
final JsonMslObject jsonValue = new JsonMslObject(encoder, json);
ja.put(i, jsonValue);
} else {
ja.put(i, value);
}
}
return ja.toString();
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
} catch (final MslEncoderException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
} catch (final JSONException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslArray#toString()
*/
@Override
public String toString() {
return toJSONString();
}
/** MSL encoder factory. */
private final MslEncoderFactory encoder;
}
| 1,739 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslEncoderFormat.java
|
/**
* Copyright (c) 2015-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.io;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* <p>MSL encoder formats.</p>
*
* <p>The format name is used to uniquely identify encoder formats.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MslEncoderFormat {
/** Map of names onto formats. */
private static Map<String,MslEncoderFormat> formatsByName = new HashMap<String,MslEncoderFormat>();
/** Map of identifiers onto formats. */
private static Map<Byte,MslEncoderFormat> formatsById = new HashMap<Byte,MslEncoderFormat>();
/** UTF-8 JSON. */
public static final MslEncoderFormat JSON = new MslEncoderFormat("JSON", (byte)'{');
/**
* Define an encoder format with the specified name and byte stream
* identifier.
*
* @param name the encoder format name.
* @param identifier the byte stream identifier.
*/
protected MslEncoderFormat(final String name, final byte identifier) {
this.name = name;
this.identifier = identifier;
// Add this format to the map.
synchronized (formatsByName) {
formatsByName.put(name, this);
}
synchronized (formatsById) {
formatsById.put(Byte.valueOf(identifier), this);
}
}
/**
* @param name the encoder format name.
* @return the encoder format identified by the specified name or
* {@code null} if there is none.
*/
public static MslEncoderFormat getFormat(final String name) {
return formatsByName.get(name);
}
/**
* @param identifier the encoder format identifier.
* @return the encoder format identified by the specified identifier or
* {@code null} if there is none.
*/
public static MslEncoderFormat getFormat(final byte identifier) {
return formatsById.get(Byte.valueOf(identifier));
}
/**
* @return all known encoder formats.
*/
public static Collection<MslEncoderFormat> values() {
return formatsByName.values();
}
/**
* @return the format identifier.
*/
public String name() {
return name;
}
/**
* @return the byte stream identifier.
*/
public byte identifier() {
return identifier;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return name();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return name.hashCode() ^ Byte.valueOf(identifier).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 MslEncoderFormat)) return false;
final MslEncoderFormat that = (MslEncoderFormat)obj;
return this.name.equals(that.name) && this.identifier == that.identifier;
}
/** Name. */
private final String name;
/** Byte stream identifier. */
private final byte identifier;
}
| 1,740 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslEncoderUtils.java
|
/**
* Copyright (c) 2012-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.io;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* MSL encoder utility functions.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslEncoderUtils {
/** Encoding charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/** Base64 characters. */
private static final char CHAR_PLUS = '+';
private static final char CHAR_MINUS = '-';
private static final char CHAR_SLASH = '/';
private static final char CHAR_UNDERSCORE = '_';
private static final char CHAR_EQUALS = '=';
/**
* URL-safe Base64 encode data as UTF-8 without padding characters.
*
* @param s the value to Base64 encode.
* @return the Base64 encoded data.
*/
public static String b64urlEncode(final String s) {
final byte[] data = s.getBytes(UTF_8);
return MslEncoderUtils.b64urlEncode(data);
}
/**
* URL-safe Base64 encode data without padding characters.
*
* @param data the value to Base64 encode.
* @return the Base64 encoded data.
*/
public static String b64urlEncode(final byte[] data) {
// Perform a standard Base64 encode.
final String padded = Base64.encode(data);
// Replace standard characters with URL-safe characters.
final String modified = padded.replace(CHAR_PLUS, CHAR_MINUS).replace(CHAR_SLASH, CHAR_UNDERSCORE);
// Remove padding.
final int padIndex = modified.indexOf(CHAR_EQUALS);
return (padIndex != -1) ? modified.substring(0, padIndex) : modified;
}
/**
* URL-safe Base64 decode data that has no padding characters.
*
* @param data the Base64 encoded data.
* @return the decoded data or {@code null} if there is an error decoding.
*/
public static byte[] b64urlDecode(final String data) {
// Replace URL-safe characters with standard characters.
final String modified = data.replace(CHAR_MINUS, CHAR_PLUS).replace(CHAR_UNDERSCORE, CHAR_SLASH);
// Pad if necessary, then decode.
try {
final int toPad = 4 - (modified.length() % 4);
if (toPad == 0 || toPad == 4)
return Base64.decode(modified);
final StringBuilder padded = new StringBuilder(modified);
for (int i = 0; i < toPad; ++i)
padded.append(CHAR_EQUALS);
return Base64.decode(padded.toString());
} catch (final IllegalArgumentException e) {
return null;
}
}
/**
* Create a MSL array from a collection of objects that are either one of
* the accepted types: <code>Boolean</code>, <code>Byte[]</code>,
* <code>MslArray</code>, <code>MslObject</code>, <code>Number</code>,
* <code>String</code>, <code>null</code>, or turn any
* <code>MslEncodable</code> into a <code>MslObject</code>.
*
* @param ctx MSL context.
* @param format MSL encoder format.
* @param c a collection of MSL encoding-compatible objects.
* @return the constructed MSL array.
* @throws MslEncoderException if a <code>MslEncodable</code> cannot be
* encoded properly or an unsupported object is encountered.
*/
public static MslArray createArray(final MslContext ctx, final MslEncoderFormat format, final Collection<?> c) throws MslEncoderException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslArray array = encoder.createArray();
for (final Object o : c) {
if (o instanceof byte[] ||
o instanceof Boolean ||
o instanceof MslArray ||
o instanceof MslObject ||
o instanceof Number ||
o instanceof String ||
o instanceof Map ||
o instanceof Collection ||
o instanceof Object[] ||
o instanceof Enum ||
o == null)
{
array.put(-1, o);
} else if (o instanceof MslEncodable) {
final MslEncodable me = (MslEncodable)o;
final byte[] encode = me.toMslEncoding(encoder, format);
final MslObject mo = encoder.parseObject(encode);
array.put(-1, mo);
} else {
throw new MslEncoderException("Class " + o.getClass().getName() + " is not MSL encoding-compatible.");
}
}
return array;
}
/**
* Performs a deep comparison of two MSL objects for equivalence. MSL
* objects are equivalent if they have the same name/value pairs. Also, two
* MSL object references are considered equal if both are null.
*
* @param mo1 first MSL object. May be null.
* @param mo2 second MSL object. May be null.
* @return true if the MSL objects are equivalent.
* @throws MslEncoderException if there is an error parsing the data.
*/
public static boolean equalObjects(final MslObject mo1, final MslObject mo2) throws MslEncoderException {
// Equal if both null or the same object.
if (mo1 == mo2)
return true;
// Not equal if only one of them is null.
if (mo1 == null || mo2 == null)
return false;
// Check the children names. If there are no names, the MSL object is
// empty.
final Set<String> names1 = mo1.getKeys();
final Set<String> names2 = mo2.getKeys();
// Continue if the same object.
if (names1 != names2) {
// Not equal if only one of them is null or of different length.
if (names1 == null || names2 == null || names1.size() != names2.size())
return false;
// Not equal if the sets are not equal.
if (!names1.equals(names2))
return false;
}
// Bail on the first child element whose values are not equal.
for (final String name : names1) {
final Object o1 = mo1.opt(name);
final Object o2 = mo2.opt(name);
// Equal if both null or the same object.
if (o1 == o2) continue;
// Not equal if only one of them is null.
if (o1 == null || o2 == null)
return false;
// byte[] may be represented differently, so we have to compare by
// accessing directly. This isn't perfect but works for now.
if (o1 instanceof byte[] || o2 instanceof byte[]) {
final byte[] b1 = mo1.getBytes(name);
final byte[] b2 = mo2.getBytes(name);
if (!Arrays.equals(b1, b2))
return false;
} else if (o1 instanceof MslObject && o2 instanceof MslObject) {
if (!MslEncoderUtils.equalObjects((MslObject)o1, (MslObject)o2))
return false;
} else if (o1 instanceof MslArray && o2 instanceof MslArray) {
if (!MslEncoderUtils.equalArrays((MslArray)o1, (MslArray)o2))
return false;
} else {
if (o1.getClass() != o2.getClass())
return false;
if (!o1.equals(o2))
return false;
}
}
// All name/value pairs are equal.
return true;
}
/**
* Computes the hash code of a MSL object in a manner that is consistent
* with MSL object equality.
*
* @param mo MSL object. May be {@code null}.
* @return the hash code.
*/
public static int hashObject(final MslObject mo) {
if (mo == null) return -1;
int hashcode = 0;
final Set<String> names = mo.getKeys();
for (final String name : names) {
final int valuehash;
// byte[] may be represented differently, so try accessing directly
// first.
final byte[] b = mo.optBytes(name, null);
if (b != null) {
valuehash = Arrays.hashCode(b);
}
// Otherwise process normally.
else {
final Object o = mo.opt(name);
if (o instanceof MslObject) {
valuehash = hashObject((MslObject)o);
} else if (o instanceof MslArray) {
valuehash = hashArray((MslArray)o);
} else if (o != null) {
valuehash = o.hashCode();
} else {
valuehash = 1;
}
}
// Modify the hash code. The name/value association matters.
hashcode ^= (name.hashCode() + valuehash);
}
return hashcode;
}
/**
* Performs a deep comparison of two MSL arrays for equality. Two MSL
* arrays are considered equal if both arrays contain the same number of
* elements, and all corresponding pairs of elements in the two arrays are
* equal. In other words, two MSL arrays are equal if they contain the
* same elements in the same order. Also, two MSL array references are
* considered equal if both are null.
*
* @param ma1 first MSL array. May be null.
* @param ma2 second MSL array. May be null.
* @return true if the MSL arrays are equal.
* @throws MslEncoderException if there is an error parsing the data.
*/
public static boolean equalArrays(final MslArray ma1, final MslArray ma2) throws MslEncoderException {
// Equal if both null or the same object.
if (ma1 == ma2)
return true;
// Not equal if only one of them is null or of different length.
if (ma1 == null || ma2 == null || ma1.size() != ma2.size())
return false;
// Bail on the first elements whose values are not equal.
for (int i = 0; i < ma1.size(); ++i) {
final Object o1 = ma1.opt(i);
final Object o2 = ma2.opt(i);
// Equal if both null or the same object.
if (o1 == o2) continue;
// Not equal if only one of them is null.
if (o1 == null || o2 == null)
return false;
// byte[] may be represented differently, so we have to compare by
// accessing directly. This isn't perfect but works for now.
if (o1 instanceof byte[] || o2 instanceof byte[]) {
final byte[] b1 = ma1.getBytes(i);
final byte[] b2 = ma2.getBytes(i);
if (!Arrays.equals(b1, b2))
return false;
} else if (o1 instanceof MslObject && o2 instanceof MslObject) {
if (!MslEncoderUtils.equalObjects((MslObject)o1, (MslObject)o2))
return false;
} else if (o1 instanceof MslArray && o2 instanceof MslArray) {
if (!MslEncoderUtils.equalArrays((MslArray)o1, (MslArray)o2))
return false;
} else {
if (o1.getClass() != o2.getClass())
return false;
if (!o1.equals(o2))
return false;
}
}
// All values are equal.
return true;
}
/**
* Computes the hash code of a MSL array in a manner that is consistent
* with MSL array equality.
*
* @param ma MSL array. May be {@code null}.
* @return the hash code.
*/
public static int hashArray(final MslArray ma) {
if (ma == null) return -1;
int hashcode = 0;
for (int i = 0; i < ma.size(); ++i) {
// byte[] may be represented differently, so try accessing directly
// first.
final byte[] b = ma.optBytes(i, null);
if (b != null) {
hashcode = 37 * hashcode + Arrays.hashCode(b);
continue;
}
// Otherwise process normally.
final Object o = ma.opt(i);
if (o instanceof MslObject) {
hashcode = 37 * hashcode + hashObject((MslObject)o);
} else if (o instanceof MslArray) {
hashcode = 37 * hashcode + hashArray((MslArray)o);
} else if (o != null) {
hashcode = 37 * hashcode + o.hashCode();
} else {
hashcode = 37 * hashcode + 1;
}
}
return hashcode;
}
/**
* Performs a shallow comparison of two MSL arrays for set equality. Two
* MSL arrays are considered set-equal if both arrays contain the same
* number of elements and all elements found in one array are also found in
* the other. In other words, two MSL arrays are set-equal if they contain
* the same elements in the any order. Also, two MSL array references are
* considered set-equal if both are null.
*
* @param ma1 first MSL array. May be {@code null}.
* @param ma2 second MSL array. May be {@code null}.
* @return true if the MSL arrays are set-equal.
* @throws MslEncoderException if there is an error parsing the data.
*/
public static boolean equalSets(final MslArray ma1, final MslArray ma2) throws MslEncoderException {
// Equal if both null or the same object.
if (ma1 == ma2)
return true;
// Not equal if only one of them is null or of different length.
if (ma1 == null || ma2 == null || ma1.size() != ma2.size())
return false;
// Compare as sets.
final Set<Object> s1 = new HashSet<Object>();
final Set<Object> s2 = new HashSet<Object>();
for (int i = 0; i < ma1.size(); ++i) {
s1.add(ma1.opt(i));
s2.add(ma2.opt(i));
}
return s1.equals(s2);
}
/**
* Merge two MSL objects into a single MSL object. If the same key is
* found in both objects, the second object's value is used. The values are
* copied by reference so this is a shallow copy.
*
* @param mo1 first MSL object. May be null.
* @param mo2 second MSL object. May be null.
* @return the merged MSL object or null if both arguments are null.
* @throws MslEncoderException if a value in one of the arguments is
* invalid—this should not happen.
*/
public static MslObject merge(final MslObject mo1, final MslObject mo2) throws MslEncoderException {
// Return null if both objects are null.
if (mo1 == null && mo2 == null)
return null;
// Make a copy of the first object, or create an empty object.
final MslObject mo = (mo1 != null)
? new MslObject(mo1.getMap())
: new MslObject();
// If the second object is null, we're done and just return the copy.
if (mo2 == null)
return mo;
// Copy the contents of the second object into the final object.
for (final String key : mo2.getKeys())
mo.put(key, mo2.get(key));
return mo;
}
}
| 1,741 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/DefaultMslEncoderFactory.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.io;
import java.io.InputStream;
import java.util.Set;
/**
* <p>Default {@link MslEncoderFactory} implementation that supports the
* following encoder formats:
* <ul>
* <li>JSON: backed by {@code org.json}.</li>
* </ul>
* </p>
*
* @author Wesley Miaw <[email protected]>
*/
public class DefaultMslEncoderFactory extends MslEncoderFactory {
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncoderFactory#getPreferredFormat(java.util.Set)
*/
public MslEncoderFormat getPreferredFormat(final Set<MslEncoderFormat> formats) {
// We don't know about any other formats right now.
return MslEncoderFormat.JSON;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncoderFactory#generateTokenizer(java.io.InputStream, com.netflix.msl.io.MslEncoderFormat)
*/
protected MslTokenizer generateTokenizer(final InputStream source, final MslEncoderFormat format) throws MslEncoderException {
// JSON.
if (MslEncoderFormat.JSON.equals(format))
return new JsonMslTokenizer(this, source);
// Unsupported encoder format.
throw new MslEncoderException("Unsupported encoder format: " + format + ".");
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncoderFactory#parseObject(byte[])
*/
public MslObject parseObject(final byte[] encoding) throws MslEncoderException {
// Identify the encoder format.
final MslEncoderFormat format = parseFormat(encoding);
// JSON.
if (MslEncoderFormat.JSON.equals(format))
return new JsonMslObject(this, encoding);
// Unsupported encoder format.
throw new MslEncoderException("Unsupported encoder format: " + format + ".");
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncoderFactory#encodeObject(com.netflix.msl.io.MslObject, com.netflix.msl.io.MslEncoderFormat)
*/
public byte[] encodeObject(final MslObject object, final MslEncoderFormat format) throws MslEncoderException {
// JSON.
if (MslEncoderFormat.JSON.equals(format))
return JsonMslObject.getEncoded(this, object);
// Unsupported encoder format.
throw new MslEncoderException("Unsupported encoder format: " + format + ".");
}
}
| 1,742 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/UnsynchronizedBufferedInputStream.java
|
/**
* Copyright (c) 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.io;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* <p>A {@code UnsynchronizedBufferedInputStream} adds support for the
* {@code mark()} and {@code reset()} functions.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class UnsynchronizedBufferedInputStream extends FilterInputStream {
/**
* Buffer of data read since the last call to mark(). Null if
* mark() has not been called or if the read limit has been
* exceeded.
*/
protected byte buf[] = null;
/** Number of valid bytes in the buffer. */
protected int bufcount;
/** Current buffer read position. */
protected int bufpos;
/**
* Creates a new <code>UnsynchronizedBufferedInputStream</code> without any
* mark position set.
*
* @param in the backing input stream.
*/
public UnsynchronizedBufferedInputStream(final InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
if (in == null)
throw new IOException("Stream is closed");
// If we have any data in the buffer, read it first.
if (bufpos < bufcount)
return buf[bufpos++];
// Otherwise read from the backing stream...
final int c = in.read();
if (c == -1) return -1;
// If we are buffering data...
if (buf != null) {
// Store the data if there is space.
if (bufcount < buf.length) {
buf[bufcount++] = (byte)c;
bufpos++;
}
// Otherwise we have exceeded the read limit. Stop buffering and
// invalidate the mark.
else {
buf = null;
bufcount = 0;
bufpos = 0;
}
}
// Return the read data.
return c;
}
@Override
public int read(final byte b[], final int off, final int len) throws IOException {
if (in == null)
throw new IOException("Stream is closed");
// Copy in any buffered data.
final int copied;
if (bufcount > bufpos) {
copied = Math.min(bufcount - bufpos, len);
System.arraycopy(buf, bufpos, b, off, copied);
bufpos += copied;
} else {
copied = 0;
}
// Read any remaining data requested.
final int remaining = len - copied;
final int numread = in.read(b, off + copied, remaining);
// If we were unable to read, return the number of bytes copied or -1
// to indicate end-of-stream if we also didn't copy any bytes.
if (numread == -1)
return (copied > 0) ? copied : -1;
// If we are buffering data...
if (buf != null) {
// Store the data if there is space.
if (bufcount + numread <= buf.length) {
System.arraycopy(b, copied, buf, bufpos, numread);
bufcount += numread;
bufpos += numread;
}
// Otherwise we have exceeded the read limit. Stop buffering and
// invalidate the mark.
else {
buf = null;
bufcount = 0;
bufpos = 0;
}
}
// Return number of bytes read.
return copied + numread;
}
@Override
public long skip(final long n) throws IOException {
if (in == null)
throw new IOException("Stream is closed");
// If we have enough buffered characters, skip over them.
final long buffered = bufcount - bufpos;
if (buffered >= n) {
bufpos += n;
return n;
}
// Otherwise skip over the buffered characters and read the rest.
bufpos += buffered;
long remaining = n - buffered;
while (remaining > 0) {
final byte[] buf = new byte[(int)remaining];
final int read = read(buf, 0, buf.length);
if (read == -1) break;
remaining -= read;
}
// Return the number of characters skipped.
return n - remaining;
}
@Override
public int available() throws IOException {
if (in == null)
throw new IOException("Stream is closed");
final int available = in.available();
return (bufcount + available < 0) ? Integer.MAX_VALUE : bufcount + available;
}
@Override
public void mark(final int readlimit) {
// Create the new buffer of the requested size.
final byte[] newbuf = new byte[readlimit];
// Copy any unread data that is currently buffered into the new buffer.
final int tocopy = (buf != null) ? bufcount - bufpos : 0;
if (tocopy > 0)
System.arraycopy(buf, bufpos, newbuf, 0, tocopy);
// Set the buffer.
buf = newbuf;
bufpos = 0;
bufcount = tocopy;
}
@Override
public void reset() throws IOException {
if (in == null)
throw new IOException("Stream is closed");
bufpos = 0;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void close() throws IOException {
if (in != null) {
in.close();
in = null;
}
}
}
| 1,743 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/JavaUrl.java
|
/**
* Copyright (c) 2012-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.io;
import java.io.BufferedInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* An implementation of the {@link Url} interface based on the built-in Java
* {@link URL} class.
*/
public class JavaUrl implements Url {
/**
* <p>A delayed input stream does not open the real input stream until one
* of its methods is called. This class may be useful in situations where
* the connection will not permit use of its output stream after the input
* stream is requested.</p>
*
* <p>The input stream itself will be a {@link BufferedInputStream} which
* will read ahead for improved performance, and support the
* {@link #mark(int)}, {@link #reset()}, and {@link #skip(long)}
* methods. This is necessary to facilitate stream reuse across multiple
* MSL messages.</p>
*/
public static class DelayedInputStream extends FilterInputStream {
/**
* Create a new delayed input stream that will not attempt to
* construct the input stream from the URL connection until it is
* actually needed (i.e. read from).
*
* @param conn backing URL connection.
*/
public DelayedInputStream(final URLConnection conn) {
super(null);
this.conn = conn;
}
/**
* <p>If the connection input stream has not already been opened, open
* it and wrap it inside a {@link BufferedInputStream}, then assign it
* to the parent member variable {@link FilterInputStream#in}.</p>
*
* <p>If mark was called and delayed, also mark the input stream.</p>
*
* @throws IOException any exception thrown by
* {@link URLConnection#getInputStream()}.
*/
private void openOnce() throws IOException {
// Return immediately if already open.
if (in != null) return;
// Open and wrap the input stream.
final InputStream source = conn.getInputStream();
in = new BufferedInputStream(source);
// If mark had been called earlier, mark the input stream now.
if (readlimit != -1)
in.mark(readlimit);
}
@Override
public int available() throws IOException {
openOnce();
return super.available();
}
@Override
public void close() throws IOException {
openOnce();
super.close();
}
@Override
public synchronized void mark(final int readlimit) {
// Mark the BufferedInputStream if it is already open.
if (in != null)
super.mark(readlimit);
// Otherwise remember that mark was called so it can be called on
// the BufferedInputStream once opened.
else
this.readlimit = readlimit;
}
@Override
public boolean markSupported() {
// BufferedInputStream supports mark.
return true;
}
@Override
public int read() throws IOException {
openOnce();
return super.read();
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
openOnce();
return super.read(b, off, len);
}
@Override
public int read(final byte[] b) throws IOException {
openOnce();
return super.read(b);
}
@Override
public synchronized void reset() throws IOException {
openOnce();
super.reset();
}
@Override
public long skip(final long n) throws IOException {
openOnce();
return super.skip(n);
}
/** Connection providing the input stream. */
private final URLConnection conn;
/** Mark read limit. -1 if no mark is set. */
private int readlimit = -1;
}
/**
* An implementation of the {@link Connection} interface backed by the
* built-in Java {@link URLConnection} class.
*/
private static class JavaConnection implements Connection {
/**
* Create a new Java connection with the backing URL connection.
*
* @param conn the backing URL connection.
*/
public JavaConnection(final URLConnection conn) {
this.conn = conn;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.Url.Connection#getInputStream()
*/
@Override
public InputStream getInputStream() throws IOException {
// Asking for the URL connection's input stream prevents further
// writing to the output stream, so return a delayed input stream.
return new DelayedInputStream(conn);
}
/* (non-Javadoc)
* @see com.netflix.msl.io.Url.Connection#getOutputStream()
*/
@Override
public OutputStream getOutputStream() throws IOException {
return conn.getOutputStream();
}
/** URL connection. */
private final URLConnection conn;
}
/**
* @param url the target location.
*/
public JavaUrl(final URL url) {
this.url = url;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.Url#setTimeout(int)
*/
@Override
public void setTimeout(final int timeout) {
this.timeout = timeout;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.Url#openConnection()
*/
@Override
public Connection openConnection() throws IOException {
final URLConnection connection = url.openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
return new JavaConnection(connection);
}
/** URL. */
private final URL url;
/** Connection timeout. */
private int timeout = 0;
}
| 1,744 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/LZWOutputStream.java
|
/**
* Copyright (c) 2013-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.io;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* <p>This class implements a stream filter for writing compressed data in the
* LZW format.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class LZWOutputStream extends OutputStream {
/** Maximum number of codes to buffer before flushing. */
private static final int MAX_BUFFER_SIZE = 100;
/** A byte array for use as map keys. */
private static class Key {
/**
* Create a new key with the following byte array value. This does not
* make a copy of the byte array.
*
* @param bytes the byte array to serve as the key value.
*/
public Key(final byte[] bytes) {
this.bytes = bytes;
this.hashCode = Arrays.hashCode(bytes);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof Key)) return false;
return Arrays.equals(bytes, ((Key)o).bytes);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return hashCode;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return Arrays.toString(bytes);
}
/** The byte array value. */
private final byte[] bytes;
/** The hash code value. */
private final int hashCode;
}
/** A code is a numeric value represented by a specific number of bits. */
private static class Code {
/**
* Create a new code with the specified value and bit length.
*
* @param value the value.
* @param bits the number of bits used to encode the value.
*/
public Code(int value, int bits) {
this.value = value;
this.bits = bits;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return Integer.toHexString(value) + " (" + bits + "b)";
}
/** Numeric value. */
public final int value;
/** Bit length. */
public final int bits;
}
/** Maximum number of values represented by a byte. */
private static final int BYTE_RANGE = 256;
/** The initial dictionary. */
private static final Map<Key,Integer> INITIAL_DICTIONARY = new HashMap<Key,Integer>(BYTE_RANGE);
static {
for (int i = 0; i < BYTE_RANGE; ++i) {
final byte[] keybytes = { (byte)i };
final Key key = new Key(keybytes);
INITIAL_DICTIONARY.put(key, i);
}
}
/**
* Creates a new output stream.
*
* @param out the output stream.
*/
public LZWOutputStream(final OutputStream out) {
this.out = out;
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
/* (non-Javadoc)
* @see java.io.OutputStream#close()
*/
@Override
public void close() throws IOException {
if (!closed) {
finish();
out.close();
closed = true;
}
}
/**
* Finishes writing compressed data to the output stream without closing
* the underlying stream. Use this method when applying multiple filters in
* succession to the same output stream.
*
* @throws IOException if an I/O error has occurred.
*/
public void finish() throws IOException {
if (!finish) {
finish = true;
// If there are any symbols left we have to emit those codes now.
if (symbols.size() > 0) {
final byte[] keybytes = symbols.toByteArray();
final Key key = new Key(keybytes);
final Integer value = dictionary.get(key);
buffer.add(new Code(value, bits));
flush();
}
}
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(int)
*/
@Override
public void write(int b) throws IOException {
final byte[] buf = new byte[1];
buf[0] = (byte)(b & 0xff);
write(buf, 0, 1);
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(byte[], int, int)
*/
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (closed)
throw new IOException("Output stream is closed.");
if (off < 0)
throw new IndexOutOfBoundsException("Offset cannot be negative.");
if (len < 0)
throw new IndexOutOfBoundsException("Length cannot be negative.");
if (off + len > b.length)
throw new IndexOutOfBoundsException("Offset plus length cannot be greater than the array length.");
for (int i = off; i < off + len; ++i) {
// Add a byte to the input.
final byte c = b[i];
symbols.write(c);
// Check if the input is in the dictionary.
final byte[] keybytes = symbols.toByteArray();
final Key key = new Key(keybytes);
final Integer value = dictionary.get(key);
// If the input is not in the dictionary, then...
if (value == null) {
// emit the previous input's code...
final byte[] prevkeybytes = Arrays.copyOf(keybytes, keybytes.length - 1);
final Key prevkey = new Key(prevkeybytes);
final Integer prevvalue = dictionary.get(prevkey);
buffer.add(new Code(prevvalue, bits));
// and add the new input to the dictionary.
//
// The bit width increases from p to p + 1 when the new code is
// the first code requiring p + 1 bits.
final int newvalue = dictionary.size();
if (newvalue >> bits != 0)
++bits;
dictionary.put(key, newvalue);
// Remove the emitted symbol from the current input.
symbols.reset();
symbols.write(c);
// If the buffer is too big, flush to avoid blowing the heap.
if (buffer.size() > MAX_BUFFER_SIZE)
flush();
}
}
}
/* (non-Javadoc)
* @see java.io.OutputStream#flush()
*/
public void flush() throws IOException {
// Do nothing if the code buffer is empty.
if (buffer.isEmpty()) return;
// Use MSB-First packing order.
//
// Collect codes until aligned on a byte boundary.
int codebits = 0;
final LinkedList<Code> codes = new LinkedList<Code>();
while (buffer.size() > 0) {
final Code c = buffer.remove();
codes.add(c);
codebits += c.bits;
// If aligned on a byte boundary output the collected codes and
// remove them from the codes buffer.
if (codebits % 8 == 0) {
out.write(codesToBytes(codes));
codes.clear();
codebits = 0;
}
}
// If the stream is closed then output the remaining codes.
if (finish)
out.write(codesToBytes(codes));
// Otherwise stick them back onto the code buffer for next time.
else
buffer.addAll(codes);
}
/**
* Convert an ordered list of codes (which may or may not be byte-aligned)
* into their MSB-first byte representation.
*
* @param codes an ordered list of codes.
* @return the MSB-first byte representation of the codes.
*/
private static byte[] codesToBytes(final LinkedList<Code> codes) {
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
byte b = 0;
int available = Byte.SIZE;
while (codes.size() > 0) {
// Write the current code bits MSB-first.
final Code code = codes.remove();
int bits = code.bits;
while (bits > 0) {
// If the code has more bits than available, shift right to get
// the most significant bits. This finishes off the current
// byte.
if (bits > available) {
int msbits = code.value;
msbits >>>= bits - available;
b |= (msbits & 0xff);
// The current byte is finished so write it out.
bytes.write(b);
// We've written 'available' bits of the current code. The
// next byte is completely available so reset the values.
bits -= available;
available = Byte.SIZE;
b = 0;
}
// If the code has less then or equal bits available, shift
// left to pack against the previous bits.
else if (bits <= available) {
// First shift left to erase the most significant bits then
// shift right to start at the correct offset.
int msbits = code.value;
msbits <<= available - bits;
msbits &= 0xff;
msbits >>>= Byte.SIZE - available;
b |= (msbits & 0xff);
// We've written 'bits' bits into the current byte. There
// are no more bits to write for the current code.
available -= bits;
bits = 0;
// If this finished the current byte then write it and
// reset the values.
if (available == 0) {
bytes.write(b);
available = Byte.SIZE;
b = 0;
}
}
}
}
// If the number of bits available in the current byte is less than the
// size of a byte then the current byte still needs to be written.
if (available < Byte.SIZE)
bytes.write(b);
return bytes.toByteArray();
}
/** Output stream. */
private final OutputStream out;
/** The dictionary of codes keyed off bytes. */
private final Map<Key,Integer> dictionary = new HashMap<Key,Integer>(INITIAL_DICTIONARY);
/** Working symbols. */
private final ByteArrayOutputStream symbols = new ByteArrayOutputStream();
/** Current bit length. */
private int bits = Byte.SIZE;
/** Buffered codes pending write. */
private final LinkedList<Code> buffer = new LinkedList<Code>();
/** Finish called. */
private boolean finish = false;
/** Stream closed. */
private boolean closed = false;
}
| 1,745 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/JsonMslTokenizer.java
|
/**
* Copyright (c) 2015-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.io;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslInternalException;
/**
* <p>Create a new {@link MslTokenizer} that parses JSON-encoded MSL
* messages.</p>
*
* <p>This implementation is backed by {@code org.json}.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class JsonMslTokenizer extends MslTokenizer {
/**
* <p>Create a new JSON MSL tokenzier that will read data off the provided
* input stream.</p>
*
* @param encoder MSL encoder factory.
* @param source JSON input stream.
*/
public JsonMslTokenizer(final MslEncoderFactory encoder, final InputStream source) {
this.encoder = encoder;
// We cannot use the standard {@code InputStreamReader} to support
// UTF-8 decoding because it makes use of {@code StreamDecoder} which
// will read {@code StreamDecoder.DEFAULT_BYTE_BUFFER_SIZE} bytes by
// default, and enforces a minimum of
// {@code StreamDecoder.MIN_BYTE_BUFFER_SIZE}. This will consume extra
// bytes and prevent the input stream from being used for future MSL
// messages.
//
// {@code JSONTokener} will consume one character at a time, but will
// default to a {@code BufferedReader} with the default buffer size if
// an {@code InputStream} or {@code Reader} is provided that does not
// support mark, which will also consume extra bytes and prevent reuse
// of the input stream.
//
// Ensure none of that occurs and that only the minimum number of bytes
// are consumed by explicitly using the {@code ThriftyUtf8Reader} which
// reads characters one at a time and also supports mark.
//
// Make sure we're trying to parse UTF-8 data.
if (StandardCharsets.UTF_8 != MslConstants.DEFAULT_CHARSET)
throw new MslInternalException("Charset " + MslConstants.DEFAULT_CHARSET + " unsupported.");
final Reader reader = new ThriftyUtf8Reader(source);
this.tokenizer = new JSONTokener(reader);
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslTokenizer#next(int)
*/
@Override
protected MslObject next(final int timeout) throws MslEncoderException {
try {
if (!tokenizer.more())
return null;
final Object o = tokenizer.nextValue();
if (o instanceof JSONObject)
return new JsonMslObject(encoder, (JSONObject)o);
throw new MslEncoderException("JSON value is not a JSON object.");
} catch (final JSONException e) {
throw new MslEncoderException("JSON syntax error.", e);
}
}
/** MSL encoder factory. */
private final MslEncoderFactory encoder;
/** JSON tokenizer. */
private final JSONTokener tokenizer;
}
| 1,746 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslArray.java
|
/**
* Copyright (c) 2015-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.io;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* <p>A {@code MslArray} is an ordered sequence of values.</p>
*
* <p>The values can be any of these types: <code>Boolean</code>,
* <code>Byte[]</code> <code>MslArray</code>, <code>MslObject</code>,
* <code>Number</code>, or <code>String</code>. <code>Enum</code> is also
* accepted and will be converted to a <code>String</code> using its
* {@code name()} method.</p>
*
* <p>The generic <code>get()</code> and <code>opt()</code> methods return an
* object, which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and type
* coercion for you. The opt methods differ from the get methods in that they
* do not throw. Instead, they return a specified value, such as null.</p>
*
* <p>The <code>put</code> methods add or replace values in an object.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MslArray {
/**
* Create a new empty {@code MslArray}.
*/
public MslArray() {
}
/**
* Create a new {@code MslArray} from the given object array.
*
* @param array the array of values. May be {@code null}.
* @throws IllegalArgumentException if one of the values is of an
* unsupported type.
*/
public MslArray(final Object[] array) {
if (array != null) {
for (final Object o : array)
put(-1, o);
}
}
/**
* Create a new {@code MslArray} from the given collection.
*
* @param collection the collection of values. May be {@code null}.
* @throws IllegalArgumentException if one of the values is of an
* unsupported type.
*/
public MslArray(final Collection<?> collection) {
if (collection != null) {
for (final Object o : collection)
put(-1, o);
}
}
/** Object list. */
private final List<Object> list = new ArrayList<Object>();
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
@SuppressWarnings("unchecked")
public Object get(final int index) throws MslEncoderException {
if (index < 0 || index >= list.size())
throw new ArrayIndexOutOfBoundsException("MslArray[" + index + "] is negative or exceeds array length.");
final Object o = list.get(index);
if (o == null)
throw new MslEncoderException("MslArray[" + index + "] is null.");
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
return o;
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public boolean getBoolean(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof Boolean)
return (Boolean)o;
throw new MslEncoderException("MslArray[" + index + "] is not a boolean.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public byte[] getBytes(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof byte[])
return (byte[])o;
throw new MslEncoderException("MslArray[" + index + "] is not binary data.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public double getDouble(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof Number)
return ((Number)o).doubleValue();
throw new MslEncoderException("MslArray[" + index + "] is not a number.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public int getInt(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof Number)
return ((Number)o).intValue();
throw new MslEncoderException("MslArray[" + index + "] is not a number.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
@SuppressWarnings("unchecked")
public MslArray getMslArray(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof MslArray)
return (MslArray)o;
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
throw new MslEncoderException("MslArray[" + index + "] is not a MslArray.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @param encoder the MSL encoder factory.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public MslObject getMslObject(final int index, final MslEncoderFactory encoder) throws MslEncoderException {
final Object o = get(index);
if (o instanceof MslObject)
return (MslObject)o;
/* FIXME: How should we handle MslEncodable?
if (o instanceof MslEncodable)
return ((MslEncodable)o).toMslObject(encoder);
*/
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof byte[]) {
try {
return encoder.parseObject((byte[])o);
} catch (final MslEncoderException e) {
throw new MslEncoderException("MslObject[" + index + "] is not a MslObject.", e);
}
}
throw new MslEncoderException("MslArray[" + index + "] is not a MslObject.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public long getLong(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof Number)
return ((Number)o).longValue();
throw new MslEncoderException("MslArray[" + index + "] is not a number.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public String getString(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof String)
return (String)o;
throw new MslEncoderException("MslArray[" + index + "] is not a string.");
}
/**
* Return true if the value at the index is {@code null}.
*
* @param index the index.
* @return true if the value is null.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public boolean isNull(final int index) {
if (index < 0 || index >= list.size())
throw new ArrayIndexOutOfBoundsException("MslArray[" + index + "] is negative or exceeds array length.");
return list.get(index) == null;
}
/**
* Return the number of elements in the array, including {@code null}
* values.
*
* @return the array size.
*/
public int size() {
return list.size();
}
/**
* Return the value at the index, which may be {@code null}. {@code null}
* will also be returned if the value is an unsupported type.
*
* @param index the index.
* @return the value. May be {@code null}.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
@SuppressWarnings("unchecked")
public Object opt(final int index) {
if (index < 0 || index >= list.size())
throw new ArrayIndexOutOfBoundsException("MslArray[" + index + "] is negative or exceeds array length.");
final Object o = list.get(index);
try {
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
} catch (final IllegalArgumentException e) {
return null;
}
return o;
}
/**
* Return the value at the index or {@code false} if the value is not of
* the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public boolean optBoolean(final int index) {
return optBoolean(index, false);
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public boolean optBoolean(final int index, final boolean defaultValue) {
final Object o = opt(index);
if (o instanceof Boolean)
return (Boolean)o;
return defaultValue;
}
/**
* Return the value at the index or an empty byte array if the value is not
* of the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public byte[] optBytes(final int index) {
return optBytes(index, new byte[0]);
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public byte[] optBytes(final int index, final byte[] defaultValue) {
final Object o = opt(index);
if (o instanceof byte[])
return (byte[])o;
return defaultValue;
}
/**
* Return the value at the index or {@code NaN} if the value is not of
* the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public double optDouble(final int index) {
return optDouble(index, Double.NaN);
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public double optDouble(final int index, final double defaultValue) {
final Object o = opt(index);
if (o instanceof Number)
return ((Number)o).doubleValue();
return defaultValue;
}
/**
* Return the value at the index or zero if the value is not of
* the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public int optInt(final int index) {
return optInt(index, 0);
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public int optInt(final int index, final int defaultValue) {
final Object o = opt(index);
if (o instanceof Number)
return ((Number)o).intValue();
return defaultValue;
}
/**
* Return the {@code MslArray} at the index or {@code null} if the value
* is not of the correct type.
*
* @param index the index.
* @return the {@code MslArray} or {@code null}.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
@SuppressWarnings("unchecked")
public MslArray optMslArray(final int index) {
final Object o = opt(index);
if (o instanceof MslArray)
return (MslArray)o;
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
return null;
}
/**
* Return the {@code MslObject} at the index or {@code null} if the value
* is not of the correct type.
*
* @param index the index.
* @param encoder the MSL encoder factory.
* @return the {@code MslObject} or {@code null}.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public MslObject optMslObject(final int index, final MslEncoderFactory encoder) {
final Object o = opt(index);
if (o instanceof MslObject)
return (MslObject)o;
/* FIXME: How should we handle MslEncodable?
if (o instanceof MslEncodable) {
try {
return ((MslEncodable)o).toMslObject(encoder);
} catch (final MslEncoderException e) {
// Drop through.
}
}
*/
try {
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
} catch (final IllegalArgumentException e) {
return null;
}
if (o instanceof byte[]) {
try {
return encoder.parseObject((byte[])o);
} catch (final MslEncoderException e) {
return null;
}
}
return null;
}
/**
* Return the value at the index or zero if the value is not of
* the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public long optLong(final int index) {
return optLong(index, 0);
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public long optLong(final int index, final long defaultValue) {
final Object o = opt(index);
if (o instanceof Number)
return ((Number)o).longValue();
return defaultValue;
}
/**
* Return the value at the index or the empty string if the value is not
* of the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public String optString(final int index) {
return optString(index, "");
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public String optString(final int index, final String defaultValue) {
final Object o = opt(index);
if (o instanceof String)
return (String)o;
return defaultValue;
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
* @throws IllegalArgumentException if the value is of an unsupported type.
*/
@SuppressWarnings("unchecked")
public MslArray put(final int index, final Object value) {
if (index < -1)
throw new ArrayIndexOutOfBoundsException("MslArray[" + index + "] is negative.");
// Convert appropriate values to MSL objects or MSL arrays.
final Object element;
if (value instanceof Boolean ||
value instanceof byte[] ||
value instanceof Number ||
value instanceof MslObject ||
value instanceof MslArray ||
value instanceof String ||
value instanceof MslEncodable)
{
element = value;
}
else if (value instanceof Map) {
element = new MslObject((Map<?,?>)value);
} else if (value instanceof Collection) {
element = new MslArray((Collection<Object>)value);
} else if (value instanceof Object[]) {
element = new MslArray((Object[])value);
} else if (value instanceof Enum) {
element = ((Enum<?>)value).name();
} else if (value == null) {
element = null;
} else {
throw new IllegalArgumentException("Value [" + value.getClass() + "] is an unsupported type.");
}
// Fill with null elements as necessary.
for (int i = list.size(); i < index; ++i)
list.add(null);
// Append if requested.
if (index == -1 || index == list.size()) {
list.add(element);
return this;
}
// Otherwise replace.
list.set(index, element);
return this;
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putBoolean(final int index, final Boolean value) {
return put(index, value);
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putBytes(final int index, final byte[] value) {
return put(index, value);
}
/**
* Put or replace a value in the {@code MslArray} at the index. The
* collection of elements will be transformed into a {@code MslArray}. If
* the index exceeds the length, null elements will be added as necessary.
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
* @throws IllegalArgumentException if the value contains an unsupported
* type.
*/
public MslArray putCollection(final int index, final Collection<Object> value) {
return put(index, value);
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putDouble(final int index, final Double value) {
return put(index, value);
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putInt(final int index, final Integer value) {
return put(index, value);
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putLong(final int index, final Long value) {
return put(index, value);
}
/**
* Put or replace a value in the {@code MslArray} at the index. The map of
* strings onto objects will be transformed into a {@code MslObject}. If
* the index exceeds the length, null elements will be added as necessary.
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
* @throws IllegalArgumentException if one of the values is an unsupported
* type.
*/
public MslArray putMap(final int index, final Map<String,Object> value) {
return put(index, new MslObject(value));
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putString(final int index, final String value) {
return put(index, value);
}
/**
* Remove an element at the index. This decreases the length by one.
*
* @param index the index. -1 for the end of the array.
* @return the removed value. May be {@code null}.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public Object remove(final int index) {
if (index < -1 || index >= list.size())
throw new ArrayIndexOutOfBoundsException("MslArray[" + index + "] is negative or exceeds array length.");
final int i = (index == -1) ? list.size() - 1 : index;
final Object value = opt(i);
list.remove(i);
return value;
}
/**
* Return an unmodifiable collection of the {@code MslArray} contents.
*
* @return the unmodifiable collection of {@code MslArray} contents.
*/
public Collection<Object> getCollection() {
return Collections.unmodifiableList(list);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (!(obj instanceof MslArray)) return false;
final MslArray that = (MslArray)obj;
try {
return MslEncoderUtils.equalArrays(this, that);
} catch (final MslEncoderException e) {
return false;
}
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return MslEncoderUtils.hashArray(this);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// This is based on the org.json {@code JSONArray.write()} code.
final StringBuilder sb = new StringBuilder();
boolean commanate = false;
final int length = list.size();
sb.append('[');
if (length == 1) {
sb.append(MslEncoderFactory.stringify(this.list.get(0)));
} else if (length != 0) {
for (int i = 0; i < length; i += 1) {
if (commanate) {
sb.append(',');
}
sb.append(MslEncoderFactory.stringify(list.get(i)));
commanate = true;
}
}
sb.append(']');
return sb.toString();
}
}
| 1,747 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/userauth/UserAuthenticationScheme.java
|
/**
* Copyright (c) 2012-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.userauth;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* <p>User authentication schemes.</p>
*
* <p>The scheme name is used to uniquely identify user authentication
* schemes.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class UserAuthenticationScheme {
/** Map of names onto schemes. */
private static Map<String,UserAuthenticationScheme> schemes = new HashMap<String,UserAuthenticationScheme>();
/** Email/password. */
public static final UserAuthenticationScheme EMAIL_PASSWORD = new UserAuthenticationScheme("EMAIL_PASSWORD");
/** User ID token. */
public static final UserAuthenticationScheme USER_ID_TOKEN = new UserAuthenticationScheme("USER_ID_TOKEN");
/**
* Define a user authentication scheme with the specified name.
*
* @param name the user authentication scheme name.
*/
protected UserAuthenticationScheme(final String name) {
this.name = name;
// Add this scheme to the map.
synchronized (schemes) {
schemes.put(name, this);
}
}
/**
* @param name the entity authentication scheme name.
* @return the scheme identified by the specified name or {@code null} if
* there is none.
*/
public static UserAuthenticationScheme getScheme(final String name) {
return schemes.get(name);
}
/**
* @return all known user authentication schemes.
*/
public static Collection<UserAuthenticationScheme> values() {
return schemes.values();
}
/**
* @return the scheme identifier.
*/
public String name() {
return name;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
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 UserAuthenticationScheme)) return false;
final UserAuthenticationScheme that = (UserAuthenticationScheme)obj;
return this.name.equals(that.name);
}
/** Scheme name. */
private final String name;
}
| 1,748 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/userauth/EmailPasswordAuthenticationFactory.java
|
/**
* Copyright (c) 2012-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.userauth;
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.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* Email/password-based user authentication factory.
*
* @author Wesley Miaw <[email protected]>
*/
public class EmailPasswordAuthenticationFactory extends UserAuthenticationFactory {
/**
* Construct a new email/password-based user authentication factory.
*
* @param store email/password store.
* @param authutils authentication utilities.
*/
public EmailPasswordAuthenticationFactory(final EmailPasswordStore store, final AuthenticationUtils authutils) {
super(UserAuthenticationScheme.EMAIL_PASSWORD);
this.store = store;
this.authutils = authutils;
}
/* (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 EmailPasswordAuthenticationData(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 EmailPasswordAuthenticationData))
throw new MslInternalException("Incorrect authentication data type " + data.getClass().getName() + ".");
final EmailPasswordAuthenticationData epad = (EmailPasswordAuthenticationData)data;
// Verify the scheme is permitted.
if(!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslUserAuthException(MslError.USERAUTH_ENTITY_INCORRECT_DATA, "Authentication scheme " + this.getScheme() + " not permitted for entity " + identity + ".").setUserAuthenticationData(data);
// Extract and check email and password values.
final String epadEmail = epad.getEmail();
final String epadPassword = epad.getPassword();
if (epadEmail == null || epadPassword == null)
throw new MslUserAuthException(MslError.EMAILPASSWORD_BLANK).setUserAuthenticationData(epad);
final String email = epadEmail.trim();
final String password = epadPassword.trim();
if (email.isEmpty() || password.isEmpty())
throw new MslUserAuthException(MslError.EMAILPASSWORD_BLANK).setUserAuthenticationData(epad);
// Authenticate the user.
final MslUser user = store.isUser(email, password);
if (user == null)
throw new MslUserAuthException(MslError.EMAILPASSWORD_INCORRECT).setUserAuthenticationData(epad);
// Verify the scheme is still permitted.
if (!authutils.isSchemePermitted(identity, user, this.getScheme()))
throw new MslUserAuthException(MslError.USERAUTH_ENTITYUSER_INCORRECT_DATA, "Authentication scheme " + this.getScheme() + " not permitted for entity " + identity + ".").setUserAuthenticationData(epad);
// 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).setUserAuthenticationData(epad);
}
// Return the user.
return user;
}
/** Email/password store. */
private final EmailPasswordStore store;
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 1,749 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/userauth/EmailPasswordAuthenticationData.java
|
/**
* Copyright (c) 2012-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.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;
/**
* <p>Email/password-based user authentication data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "email", "password" ],
* "email" : "string",
* "password" : "string"
* }} where:
* <ul>
* <li>{@code email} is the user email address</li>
* <li>{@code password} is the user password</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class EmailPasswordAuthenticationData extends UserAuthenticationData {
/** Key email. */
private static final String KEY_EMAIL = "email";
/** Key password. */
private static final String KEY_PASSWORD = "password";
/**
* Construct a new email/password authentication data instance from the
* specified email and password.
*
* @param email the email address.
* @param password the password.
*/
public EmailPasswordAuthenticationData(final String email, final String password) {
super(UserAuthenticationScheme.EMAIL_PASSWORD);
this.email = email;
this.password = password;
}
/**
* Construct a new email/password authentication data instance from the
* provided MSL object.
*
* @param emailPasswordAuthMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
*/
public EmailPasswordAuthenticationData(final MslObject emailPasswordAuthMo) throws MslEncodingException {
super(UserAuthenticationScheme.EMAIL_PASSWORD);
try {
email = emailPasswordAuthMo.getString(KEY_EMAIL);
password = emailPasswordAuthMo.getString(KEY_PASSWORD);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "email/password authdata " + emailPasswordAuthMo, e);
}
}
/**
* @return the email address.
*/
public String getEmail() {
return email;
}
/**
* @return the password.
*/
public String getPassword() {
return password;
}
@Override
public MslObject getAuthData(final MslEncoderFactory encoder, final MslEncoderFormat format) {
final MslObject mo = encoder.createObject();
mo.put(KEY_EMAIL, email);
mo.put(KEY_PASSWORD, password);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.userauth.UserAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof EmailPasswordAuthenticationData)) return false;
final EmailPasswordAuthenticationData that = (EmailPasswordAuthenticationData)obj;
return super.equals(obj) && email.equals(that.email) && password.equals(that.password);
}
/* (non-Javadoc)
* @see com.netflix.msl.userauth.UserAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ email.hashCode() ^ password.hashCode();
}
/** Email. */
private final String email;
/** Password. */
private final String password;
}
| 1,750 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/userauth/UserIdTokenAuthenticationData.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.userauth;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslUserAuthException;
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.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.util.MslContext;
/**
* <p>User ID token-based user authentication data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "mastertoken", "useridtoken" ],
* "mastertoken" : mastertoken,
* "useridtoken" : useridtoken,
* }} where:
* <ul>
* <li>{@code mastertoken} is the master token</li>
* <li>{@code useridtoken} is the user ID token</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class UserIdTokenAuthenticationData extends UserAuthenticationData {
/** Key master token. */
private static final String KEY_MASTER_TOKEN = "mastertoken";
/** Key user ID token. */
private static final String KEY_USER_ID_TOKEN = "useridtoken";
/**
* Construct a new user ID token authentication data instance from the
* provided master token and user ID token.
*
* @param masterToken the master token.
* @param userIdToken the user ID token.
*/
public UserIdTokenAuthenticationData(final MasterToken masterToken, final UserIdToken userIdToken) {
super(UserAuthenticationScheme.USER_ID_TOKEN);
if (!userIdToken.isBoundTo(masterToken))
throw new MslInternalException("User ID token must be bound to master token.");
this.masterToken = masterToken;
this.userIdToken = userIdToken;
}
/**
* Construct a new user ID token authentication data instance from the
* provided MSL object.
*
* @param ctx MSl context.
* @param userIdTokenAuthMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslUserAuthException if the token data is invalid or the user ID
* token is not bound to the master token.
*/
public UserIdTokenAuthenticationData(final MslContext ctx, final MslObject userIdTokenAuthMo) throws MslEncodingException, MslUserAuthException {
super(UserAuthenticationScheme.USER_ID_TOKEN);
// Extract master token and user ID token representations.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject masterTokenMo, userIdTokenMo;
try {
masterTokenMo = userIdTokenAuthMo.getMslObject(KEY_MASTER_TOKEN, encoder);
userIdTokenMo = userIdTokenAuthMo.getMslObject(KEY_USER_ID_TOKEN, encoder);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "user ID token authdata " + userIdTokenAuthMo, e);
}
// Convert any MslExceptions into MslUserAuthException because we don't
// want to trigger entity or user re-authentication incorrectly.
try {
masterToken = new MasterToken(ctx, masterTokenMo);
} catch (final MslException e) {
throw new MslUserAuthException(MslError.USERAUTH_MASTERTOKEN_INVALID, "user ID token authdata " + userIdTokenAuthMo, e);
}
try {
userIdToken = new UserIdToken(ctx, userIdTokenMo, masterToken);
} catch (final MslException e) {
throw new MslUserAuthException(MslError.USERAUTH_USERIDTOKEN_INVALID, "user ID token authdata " + userIdTokenAuthMo, e);
}
}
/**
* @return the master token.
*/
public MasterToken getMasterToken() {
return masterToken;
}
/**
* @return the user ID token.
*/
public UserIdToken getUserIdToken() {
return userIdToken;
}
/* (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 authdata = encoder.createObject();
authdata.put(KEY_MASTER_TOKEN, masterToken);
authdata.put(KEY_USER_ID_TOKEN, userIdToken);
return encoder.parseObject(encoder.encodeObject(authdata, format));
}
/* (non-Javadoc)
* @see com.netflix.msl.userauth.UserAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof UserIdTokenAuthenticationData)) return false;
final UserIdTokenAuthenticationData that = (UserIdTokenAuthenticationData)obj;
return super.equals(obj) && masterToken.equals(that.masterToken) && userIdToken.equals(that.userIdToken);
}
/* (non-Javadoc)
* @see com.netflix.msl.userauth.UserAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ masterToken.hashCode() ^ userIdToken.hashCode();
}
/** Master token. */
private final MasterToken masterToken;
/** User ID token. */
private final UserIdToken userIdToken;
}
| 1,751 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/userauth/UserAuthenticationFactory.java
|
/**
* Copyright (c) 2012-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.userauth;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.MslUserIdTokenException;
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.util.MslContext;
/**
* A user authentication factory creates authentication data instances and
* performs authentication for a specific user authentication scheme.
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class UserAuthenticationFactory {
/**
* Create a new user authentication factory for the specified scheme.
*
* @param scheme the user authentication scheme.
*/
protected UserAuthenticationFactory(final UserAuthenticationScheme scheme) {
this.scheme = scheme;
}
/**
* @return the user authentication scheme this factory is for.
*/
public UserAuthenticationScheme getScheme() {
return scheme;
}
/**
* <p>Construct a new user authentication data instance from the provided
* MSL object.</p>
*
* <p>A master token may be required for certain user authentication
* schemes.</p>
*
* @param ctx MSL context.
* @param masterToken the entity master token. May be {@code null}.
* @param userAuthMo the MSL object.
* @return the user authentication data.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslUserAuthException if there is an error creating the user
* authentication data.
* @throws MslCryptoException if there is an error with the user
* authentication data cryptography.
*/
public abstract UserAuthenticationData createData(final MslContext ctx, final MasterToken masterToken, final MslObject userAuthMo) throws MslEncodingException, MslUserAuthException, MslCryptoException;
/**
* <p>Authenticate the user using the provided authentication data.</p>
*
* <p>If a user ID token is provided then also validate the authenticated
* user against the provided user ID token. This is typically a check to
* ensure the user identities are equal but not always. The returned user
* must be the user identified by the user ID token.</p>
*
* @param ctx MSL context.
* @param identity the entity identity.
* @param data user authentication data.
* @param userIdToken user ID token. May be {@code null}.
* @return the MSL user.
* @throws MslUserAuthException if there is an error authenticating the
* user or if the user authentication data and user ID token
* identities do not match.
* @throws MslUserIdTokenException if there is a problem with the user ID
* token.
*/
public abstract MslUser authenticate(final MslContext ctx, final String identity, final UserAuthenticationData data, final UserIdToken userIdToken) throws MslUserAuthException, MslUserIdTokenException;
/** The factory's user authentication scheme. */
private final UserAuthenticationScheme scheme;
}
| 1,752 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/userauth/UserAuthenticationData.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 com.netflix.msl.userauth;
import java.util.HashMap;
import java.util.Map;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.io.MslEncodable;
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.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* <p>The user authentication data provides proof of user identity.</p>
*
* <p>Specific user authentication mechanisms should define their own user
* authentication data types.</p>
*
* <p>User authentication data is represented as
* {@code
* userauthdata = {
* "#mandatory" : [ "scheme"., "authdata" ],
* "scheme" : "string",
* "authdata" : object
* }} where
* <ul>
* <li>{@code scheme} is the user authentication scheme</li>
* <li>{@code authdata} is the scheme-specific authentication data</li>
* </ul></p>
*/
public abstract class UserAuthenticationData implements MslEncodable {
/** Key user authentication scheme. */
private static final String KEY_SCHEME = "scheme";
/** Key user authentication data. */
private static final String KEY_AUTHDATA = "authdata";
/**
* Create a new user authentication data object with the specified user
* authentication scheme.
*
* @param scheme the user authentication scheme.
*/
protected UserAuthenticationData(final UserAuthenticationScheme scheme) {
this.scheme = scheme;
}
/**
* <p>Construct a new user authentication data instance of the correct type
* from the provided MSL object.</p>
*
* <p>A master token may be required for certain user authentication
* schemes.</p>
*
* @param ctx MSL context.
* @param masterToken the master token associated with the user
* authentication data. May be {@code null}.
* @param userAuthMo the MSL object.
* @return the user authentication data concrete instance.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslUserAuthException if there is an error instantiating the user
* authentication data.
* @throws MslCryptoException if there is an error with the entity
* authentication data cryptography.
*/
public static UserAuthenticationData create(final MslContext ctx, final MasterToken masterToken, final MslObject userAuthMo) throws MslUserAuthException, MslEncodingException, MslCryptoException {
try {
// Pull the scheme.
final String schemeName = userAuthMo.getString(KEY_SCHEME);
final UserAuthenticationScheme scheme = ctx.getUserAuthenticationScheme(schemeName);
if (scheme == null)
throw new MslUserAuthException(MslError.UNIDENTIFIED_USERAUTH_SCHEME, schemeName);
// Construct an instance of the concrete subclass.
final UserAuthenticationFactory factory = ctx.getUserAuthenticationFactory(scheme);
if (factory == null)
throw new MslUserAuthException(MslError.USERAUTH_FACTORY_NOT_FOUND, scheme.name());
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
return factory.createData(ctx, masterToken, userAuthMo.getMslObject(KEY_AUTHDATA, encoder));
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "userauthdata " + userAuthMo, e);
}
}
/**
* @return the user authentication scheme.
*/
public UserAuthenticationScheme getScheme() {
return scheme;
}
/**
* Returns the scheme-specific user authentication data. This method is
* expected to succeed unless there is an internal error.
*
* @param encoder the encoder factory.
* @param format the encoder format.
* @return the authentication data MSL object.
* @throws MslEncoderException if there was an error constructing the
* MSL object.
*/
public abstract MslObject getAuthData(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException;
/** User authentication scheme. */
private final UserAuthenticationScheme scheme;
/** Cached encodings. */
private final Map<MslEncoderFormat,byte[]> encodings = new HashMap<MslEncoderFormat,byte[]>();
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
// Return any cached encoding.
if (encodings.containsKey(format))
return encodings.get(format);
// Encode the user authentication data.
final MslObject mo = encoder.createObject();
mo.put(KEY_SCHEME, scheme.name());
mo.put(KEY_AUTHDATA, getAuthData(encoder, format));
final byte[] encoding = encoder.encodeObject(mo, format);
// Cache and return the encoding.
encodings.put(format, encoding);
return encoding;
}
/* (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 UserAuthenticationData)) return false;
final UserAuthenticationData that = (UserAuthenticationData)obj;
return scheme.equals(that.scheme);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return scheme.hashCode();
}
}
| 1,753 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/userauth/EmailPasswordStore.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.userauth;
import com.netflix.msl.tokens.MslUser;
/**
* An email/password store contains user credentials.
*
* @author Wesley Miaw <[email protected]>
*/
public interface EmailPasswordStore {
/**
* Return the user if the email/password combination is valid.
*
* @param email email address.
* @param password password.
* @return the MSL user or null if there is no such user.
*/
public MslUser isUser(final String email, final String password);
}
| 1,754 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/userauth/UserIdTokenAuthenticationFactory.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.userauth;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
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.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* User ID token-based user authentication factory.
*
* @author Wesley Miaw <[email protected]>
*/
public class UserIdTokenAuthenticationFactory extends UserAuthenticationFactory {
/**
* Construct a new user ID token-based user authentication factory.
*
* @param authutils authentication utilities.
*/
public UserIdTokenAuthenticationFactory(final AuthenticationUtils authutils) {
super(UserAuthenticationScheme.USER_ID_TOKEN);
this.authutils = authutils;
}
/* (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, MslUserAuthException {
return new UserIdTokenAuthenticationData(ctx, 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 UserIdTokenAuthenticationData))
throw new MslInternalException("Incorrect authentication data type " + data.getClass().getName() + ".");
final UserIdTokenAuthenticationData uitad = (UserIdTokenAuthenticationData)data;
// Verify the scheme is permitted.
if(!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslUserAuthException(MslError.USERAUTH_ENTITY_INCORRECT_DATA, "Authentication scheme " + this.getScheme() + " not permitted for entity " + identity + ".").setUserAuthenticationData(data);
// Extract and check master token.
final MasterToken uitadMasterToken = uitad.getMasterToken();
final String uitadIdentity = uitadMasterToken.getIdentity();
if (uitadIdentity == null)
throw new MslUserAuthException(MslError.USERAUTH_MASTERTOKEN_NOT_DECRYPTED).setUserAuthenticationData(uitad);
if (!identity.equals(uitadIdentity))
throw new MslUserAuthException(MslError.USERAUTH_ENTITY_MISMATCH, "entity identity " + identity + "; uad identity " + uitadIdentity).setUserAuthenticationData(uitad);
// Authenticate the user.
final UserIdToken uitadUserIdToken = uitad.getUserIdToken();
final MslUser user = uitadUserIdToken.getUser();
if (user == null)
throw new MslUserAuthException(MslError.USERAUTH_USERIDTOKEN_NOT_DECRYPTED).setUserAuthenticationData(uitad);
// Verify the scheme is still permitted.
if (!authutils.isSchemePermitted(identity, user, this.getScheme()))
throw new MslUserAuthException(MslError.USERAUTH_ENTITYUSER_INCORRECT_DATA, "Authentication scheme " + this.getScheme() + " not permitted for entity " + identity + ".").setUserAuthenticationData(data);
// Verify token has not been revoked.
final MslError revokeMslError;
try {
revokeMslError = ctx.getTokenFactory().isUserIdTokenRevoked(ctx, uitadMasterToken, uitadUserIdToken);
} catch (final MslException e) {
throw new MslUserAuthException(MslError.USERAUTH_USERIDTOKEN_REVOKE_CHECK_ERROR, "Error while checking user ID token for revocation.", e).setUserAuthenticationData(uitad);
}
if (revokeMslError != null)
throw new MslUserAuthException(revokeMslError, "User ID token used to authenticate was revoked.").setUserAuthenticationData(uitad);
// 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).setUserAuthenticationData(uitad);
}
// Return the user.
return user;
}
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 1,755 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/tokens/MasterToken.java
|
/**
* Copyright (c) 2012-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.tokens;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslConstants.EncryptionAlgo;
import com.netflix.msl.MslConstants.SignatureAlgo;
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.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.io.MslEncodable;
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.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>The master token provides proof of remote entity identity. A MSL-specific
* crypto context is used to encrypt the master token data and generate the
* master token verification data. The remote entity cannot decrypt the master
* token data or generate the master token verification data.</p>
*
* <p>The master token session keys will be used for MSL message encryption and
* integrity protection. The use of these session keys implies the MSL message
* identity as specified in the master token.</p>
*
* <p>Master tokens also contain a sequence number identifying the issue number
* of the token. This is a monotonically increasing number that is incremented
* by one each time a master token is renewed.</p>
*
* <p>When in possession of multiple master tokens, the token with the highest
* sequence number should be considered the newest token. Since the sequence
* number space is signed 53-bit numbers, if a sequence number is smaller by
* more than 45-bits (e.g. the new sequence number is <= 128 and the old
* sequence number is 2^53), it is considered the newest token.</p>
*
* <p>The renewal window indicates the time after which the master token will
* be renewed if requested by the entity. The expiration is the time after
* which the master token will be renewed no matter what.</p>
*
* <p>Master tokens also contain a serial number against which all other tokens
* are bound. Changing the serial number when the master token is renewed
* invalidates all of those tokens.</p>
*
* <p>The issuer identity identifies the issuer of this master token, which may
* be useful to services that accept the master token.</p>
*
* <p>While there can be multiple versions of a master token, this class should
* encapsulate support for all of those versions.</p>
*
* <p>Master tokens are represented as
* {@code
* mastertoken = {
* "#mandatory" : [ "tokendata", "signature" ],
* "tokendata" : "binary",
* "signature" : "binary"
* }} where:
* <ul>
* <li>{@code tokendata} is the master token data (mastertokendata)</li>
* <li>{@code signature} is the verification data of the master token data</li>
* </ul></p>
*
* <p>The token data is represented as
* {@code
* mastertokendata = {
* "#mandatory" : [ "renewalwindow", "expiration", "sequencenumber", "serialnumber", "sessiondata" ],
* "renewalwindow" : "int64(0,-)",
* "expiration" : "int64(0,-)",
* "sequencenumber" : "int64(0,2^53^)",
* "serialnumber" : "int64(0,2^53^)",
* "sessiondata" : "binary"
* }} where:
* <ul>
* <li>{@code renewalwindow} is when the renewal window opens in seconds since the epoch</li>
* <li>{@code expiration} is the expiration timestamp in seconds since the epoch</li>
* <li>{@code sequencenumber} is the master token sequence number</li>
* <li>{@code serialnumber} is the master token serial number</li>
* <li>{@code sessiondata} is the encrypted session data (sessiondata)</li>
* </ul></p>
*
* <p>The decrypted session data is represented as
* {@code
* sessiondata = {
* "#mandatory" : [ "identity", "encryptionkey" ],
* "#conditions" : [ "hmackey" or "signaturekey" ],
* "issuerdata" : object,
* "identity" : "string",
* "encryptionkey" : "binary",
* "encryptionkeyalgorithm" : "string",
* "hmackey" : "binary",
* "signaturekey" : "binary",
* "signaturekeyalgorithm" : "string",
* }}
* where:
* <ul>
* <li>{@code issuerdata} is the master token issuer data</li>
* <li>{@code identity} is the identifier of the remote entity</li>
* <li>{@code encryptionkey} is the encryption session key</li>
* <li>{@code encryptionkeyalgorithm} is the JCA encryption algorithm name (default: AES/CBC/PKCS5Padding)</li>
* <li>{@code hmackey} is the HMAC session key</li>
* <li>{@code signaturekey} is the signature session key</li>
* <li>{@code signaturekeyalgorithm} is the JCA signature algorithm name (default: HmacSHA256)</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MasterToken implements MslEncodable {
/** Milliseconds per second. */
private static final long MILLISECONDS_PER_SECOND = 1000;
/** Key token data. */
private static final String KEY_TOKENDATA = "tokendata";
/** Key signature. */
private static final String KEY_SIGNATURE = "signature";
// tokendata
/** Key renewal window timestamp. */
private static final String KEY_RENEWAL_WINDOW = "renewalwindow";
/** Key expiration timestamp. */
private static final String KEY_EXPIRATION = "expiration";
/** Key sequence number. */
private static final String KEY_SEQUENCE_NUMBER = "sequencenumber";
/** Key serial number. */
private static final String KEY_SERIAL_NUMBER = "serialnumber";
/** Key session data. */
private static final String KEY_SESSIONDATA = "sessiondata";
// sessiondata
/** Key issuer data. */
private static final String KEY_ISSUER_DATA = "issuerdata";
/** Key identity. */
private static final String KEY_IDENTITY = "identity";
/** Key symmetric encryption key. */
private static final String KEY_ENCRYPTION_KEY = "encryptionkey";
/** Key encryption algorithm. */
private static final String KEY_ENCRYPTION_ALGORITHM = "encryptionalgorithm";
/** Key symmetric HMAC key. */
private static final String KEY_HMAC_KEY = "hmackey";
/** Key signature key. */
private static final String KEY_SIGNATURE_KEY = "signaturekey";
/** Key signature algorithm. */
private static final String KEY_SIGNATURE_ALGORITHM = "signaturealgorithm";
/**
* Create a new master token with the specified expiration, identity,
* serial number, and encryption and signature keys.
*
* @param ctx MSL context.
* @param renewalWindow the renewal window.
* @param expiration the expiration.
* @param sequenceNumber the master token sequence number.
* @param serialNumber the master token serial number.
* @param issuerData the issuer data. May be null.
* @param identity the singular identity this master token represents.
* @param encryptionKey the session encryption key.
* @param signatureKey the session signature key.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data or the crypto algorithms are not recognized.
*/
public MasterToken(final MslContext ctx, final Date renewalWindow, final Date expiration, final long sequenceNumber, final long serialNumber, final MslObject issuerData, final String identity, final SecretKey encryptionKey, final SecretKey signatureKey) throws MslEncodingException, MslCryptoException {
// The expiration must appear after the renewal window.
if (expiration.before(renewalWindow))
throw new MslInternalException("Cannot construct a master token that expires before its renewal window opens.");
// The sequence number and serial number must be within range.
if (sequenceNumber < 0 || sequenceNumber > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Sequence number " + sequenceNumber + " is outside the valid range.");
if (serialNumber < 0 || serialNumber > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Serial number " + serialNumber + " is outside the valid range.");
this.ctx = ctx;
this.renewalWindow = renewalWindow.getTime() / MILLISECONDS_PER_SECOND;
this.expiration = expiration.getTime() / MILLISECONDS_PER_SECOND;
this.sequenceNumber = sequenceNumber;
this.serialNumber = serialNumber;
this.issuerdata = issuerData;
this.identity = identity;
this.encryptionKey = encryptionKey;
this.signatureKey = signatureKey;
// Encode session keys and algorithm names.
final byte[] encryptionKeyBytes = this.encryptionKey.getEncoded();
final byte[] signatureKeyBytes = this.signatureKey.getEncoded();
final EncryptionAlgo encryptionAlgo;
final SignatureAlgo signatureAlgo;
try {
encryptionAlgo = EncryptionAlgo.fromString(this.encryptionKey.getAlgorithm());
signatureAlgo = SignatureAlgo.fromString(this.signatureKey.getAlgorithm());
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_ALGORITHM, "encryption algorithm: " + this.encryptionKey.getAlgorithm() + "; signature algorithm: " + this.signatureKey.getAlgorithm(), e);
}
// Create session data.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
this.sessiondata = encoder.createObject();
if (this.issuerdata != null)
this.sessiondata.put(KEY_ISSUER_DATA, this.issuerdata);
this.sessiondata.put(KEY_IDENTITY, this.identity);
this.sessiondata.put(KEY_ENCRYPTION_KEY, encryptionKeyBytes);
this.sessiondata.put(KEY_ENCRYPTION_ALGORITHM, encryptionAlgo);
this.sessiondata.put(KEY_HMAC_KEY, signatureKeyBytes);
this.sessiondata.put(KEY_SIGNATURE_KEY, signatureKeyBytes);
this.sessiondata.put(KEY_SIGNATURE_ALGORITHM, signatureAlgo);
this.tokendataBytes = null;
this.signatureBytes = null;
this.verified = true;
}
/**
* Create a new master token from the provided MSL object.
*
* @param ctx MSL context.
* @param masterTokenMo master token MSL object.
* @throws MslEncodingException if there is an error parsing the object,
* the token data is missing or invalid, the signature is missing
* or invalid, or the session data is missing or invalid.
* @throws MslCryptoException if there is an error verifying the token data
* or extracting the session keys.
* @throws MslException if the expiration timestamp occurs before the
* renewal window, or the sequence number is out of range, or the
* serial number is out of range.
*/
public MasterToken(final MslContext ctx, final MslObject masterTokenMo) throws MslEncodingException, MslCryptoException, MslException {
this.ctx = ctx;
// Grab the crypto context.
final ICryptoContext cryptoContext = ctx.getMslCryptoContext();
// Verify the encoding.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
try {
tokendataBytes = masterTokenMo.getBytes(KEY_TOKENDATA);
if (tokendataBytes.length == 0)
throw new MslEncodingException(MslError.MASTERTOKEN_TOKENDATA_MISSING, "mastertoken " + masterTokenMo);
signatureBytes = masterTokenMo.getBytes(KEY_SIGNATURE);
verified = cryptoContext.verify(tokendataBytes, signatureBytes, encoder);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "mastertoken " + masterTokenMo, e);
}
// Pull the token data.
final byte[] plaintext;
try {
final MslObject tokendata = encoder.parseObject(tokendataBytes);
renewalWindow = tokendata.getLong(KEY_RENEWAL_WINDOW);
expiration = tokendata.getLong(KEY_EXPIRATION);
if (expiration < renewalWindow)
throw new MslException(MslError.MASTERTOKEN_EXPIRES_BEFORE_RENEWAL, "mastertokendata " + tokendata);
sequenceNumber = tokendata.getLong(KEY_SEQUENCE_NUMBER);
if (sequenceNumber < 0 || sequenceNumber > MslConstants.MAX_LONG_VALUE)
throw new MslException(MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_RANGE, "mastertokendata " + tokendata);
serialNumber = tokendata.getLong(KEY_SERIAL_NUMBER);
if (serialNumber < 0 || serialNumber > MslConstants.MAX_LONG_VALUE)
throw new MslException(MslError.MASTERTOKEN_SERIAL_NUMBER_OUT_OF_RANGE, "mastertokendata " + tokendata);
final byte[] ciphertext = tokendata.getBytes(KEY_SESSIONDATA);
if (ciphertext.length == 0)
throw new MslEncodingException(MslError.MASTERTOKEN_SESSIONDATA_MISSING, "mastertokendata " + tokendata);
plaintext = (this.verified) ? cryptoContext.decrypt(ciphertext, encoder) : null;
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MASTERTOKEN_TOKENDATA_PARSE_ERROR, "mastertokendata " + Base64.encode(tokendataBytes), e);
}
// Pull the session data.
if (plaintext != null) {
final byte[] rawEncryptionKey, rawSignatureKey;
final String encryptionAlgo, signatureAlgo;
try {
sessiondata = encoder.parseObject(plaintext);
issuerdata = (sessiondata.has(KEY_ISSUER_DATA)) ? sessiondata.getMslObject(KEY_ISSUER_DATA, encoder) : null;
identity = sessiondata.getString(KEY_IDENTITY);
rawEncryptionKey = sessiondata.getBytes(KEY_ENCRYPTION_KEY);
encryptionAlgo = sessiondata.optString(KEY_ENCRYPTION_ALGORITHM, JcaAlgorithm.AES);
rawSignatureKey = (sessiondata.has(KEY_SIGNATURE_KEY))
? sessiondata.getBytes(KEY_SIGNATURE_KEY)
: sessiondata.getBytes(KEY_HMAC_KEY);
signatureAlgo = sessiondata.optString(KEY_SIGNATURE_ALGORITHM, JcaAlgorithm.HMAC_SHA256);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MASTERTOKEN_SESSIONDATA_PARSE_ERROR, "sessiondata " + Base64.encode(plaintext), e);
}
// Decode algorithm names.
final String jcaEncryptionAlgo, jcaSignatureAlgo;
try {
jcaEncryptionAlgo = EncryptionAlgo.fromString(encryptionAlgo).toString();
jcaSignatureAlgo = SignatureAlgo.fromString(signatureAlgo).toString();
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_ALGORITHM, "encryption algorithm: " + encryptionAlgo + "; signature algorithm" + signatureAlgo, e);
}
// Reconstruct keys.
try {
encryptionKey = new SecretKeySpec(rawEncryptionKey, jcaEncryptionAlgo);
signatureKey = new SecretKeySpec(rawSignatureKey, jcaSignatureAlgo);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.MASTERTOKEN_KEY_CREATION_ERROR, e);
}
} else {
sessiondata = null;
issuerdata = null;
identity = null;
encryptionKey = null;
signatureKey = null;
}
}
/**
* @return true if the decrypted content is available. (Implies verified.)
*/
public boolean isDecrypted() {
return sessiondata != null;
}
/**
* @return true if the token has been verified.
*/
public boolean isVerified() {
return verified;
}
/**
* @return the start of the renewal window.
*/
public Date getRenewalWindow() {
return new Date(renewalWindow * MILLISECONDS_PER_SECOND);
}
/**
* <p>Returns true if the master token renewal window has been entered.</p>
*
* <ul>
* <li>If a time is provided the renewal window value will be compared
* against the provided time.</li>
* <li>If the master token was issued by the local entity the renewal
* window value will be compared against the local entity time. We assume
* its clock at the time of issuance is in sync with the clock now.</li>
* <li>Otherwise the master token is considered renewable under the
* assumption that the local time is not synchronized with the master token
* issuing entity time.</li>
* </ul>
*
* @param now the time to compare against. May be {@code null}.
* @return true if the renewal window has been entered.
*/
public boolean isRenewable(final Date now) {
if (now != null)
return renewalWindow * MILLISECONDS_PER_SECOND <= now.getTime();
if (isVerified())
return renewalWindow * MILLISECONDS_PER_SECOND <= ctx.getTime();
return true;
}
/**
* @return the expiration.
*/
public Date getExpiration() {
return new Date(expiration * MILLISECONDS_PER_SECOND);
}
/**
* <p>Returns true if the master token is expired.</p>
*
* <ul>
* <li>If a time is provided the expiration value will be compared against
* the provided time.</li>
* <li>If the master token was issued by the local entity the expiration
* value will be compared against the local entity time. We assume
* its clock at the time of issuance is in sync with the clock now.</li>
* <li>Otherwise the master token is considered not expired under the
* assumption that the local time is not synchronized with the token-
* issuing entity time.</li>
* </ul>
*
* @param now the time to compare against.
* @return true if expired.
*/
public boolean isExpired(final Date now) {
if (now != null)
return expiration * MILLISECONDS_PER_SECOND <= now.getTime();
if (isVerified())
return expiration * MILLISECONDS_PER_SECOND <= ctx.getTime();
return false;
}
/**
* @return the sequence number.
*/
public long getSequenceNumber() {
return sequenceNumber;
}
/**
* @return the serial number.
*/
public long getSerialNumber() {
return serialNumber;
}
/**
* <p>A master token is considered newer if its sequence number is greater
* than another master token. If both the sequence numbers are equal, then
* the master token with the later expiration date is considered newer.</p>
*
* <p>Serial numbers are not taken into consideration when comparing which
* master token is newer because serial numbers will change when new master
* tokens are created as opposed to renewed. The caller of this function
* should already be comparing master tokens that can be used
* interchangeably (i.e. for the same MSL network).</p>
*
* @param that the master token to compare with.
* @return true if this master token is newer than the provided one.
*/
public boolean isNewerThan(final MasterToken that) {
// If the sequence numbers are equal then compare the expiration dates.
if (this.sequenceNumber == that.sequenceNumber)
return this.expiration > that.expiration;
// If this sequence number is bigger than that sequence number, make
// sure that sequence number is not less than the cutoff.
if (this.sequenceNumber > that.sequenceNumber) {
final long cutoff = this.sequenceNumber - MslConstants.MAX_LONG_VALUE + 127;
return that.sequenceNumber >= cutoff;
}
// If this sequence number is smaller than that sequence number, make
// sure this sequence number is less than the cutoff.
final long cutoff = that.sequenceNumber - MslConstants.MAX_LONG_VALUE + 127;
return this.sequenceNumber < cutoff;
}
/**
* Returns the issuer data.
*
* @return the master token issuer data or null if there is none or it is
* unknown (session data could not be decrypted).
*/
public MslObject getIssuerData() {
return issuerdata;
}
/**
* Returns the identifier of the authenticated peer.
*
* @return the Netflix peer identity or null if unknown (session data could
* not be decrypted).
*/
public String getIdentity() {
return identity;
}
/**
* @return the encryption key or null if unknown (session data could not be
* decrypted).
*/
public SecretKey getEncryptionKey() {
return encryptionKey;
}
/**
* @return the signature key or null if unknown (session data could not be
* decrypted).
*/
public SecretKey getSignatureKey() {
return signatureKey;
}
/** MSL context. */
private final MslContext ctx;
/** Master token renewal window in seconds since the epoch. */
private final long renewalWindow;
/** Master token expiration in seconds since the epoch. */
private final long expiration;
/** Sequence number. */
private final long sequenceNumber;
/** Serial number. */
private final long serialNumber;
/** Session data. */
private final MslObject sessiondata;
/** Issuer data. */
private final MslObject issuerdata;
/** Entity identity. */
private final String identity;
/** Encryption key. */
private final SecretKey encryptionKey;
/** Signature key. */
private final SecretKey signatureKey;
/** Token data bytes. */
private final byte[] tokendataBytes;
/** Signature bytes. */
private final byte[] signatureBytes;
/** Token is verified. */
private final boolean verified;
/** Cached encodings. */
private final Map<MslEncoderFormat,byte[]> encodings = new HashMap<MslEncoderFormat,byte[]>();
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
// Return any cached encoding.
if (encodings.containsKey(format))
return encodings.get(format);
// If we parsed this token (i.e. did not create it from scratch) then
// we should not re-encrypt or re-sign as there is no guarantee out MSL
// crypto context is capable of encrypting and signing with the same
// keys, even if it is capable of decrypting and verifying.
final byte[] data, signature;
if (tokendataBytes != null || signatureBytes != null) {
data = tokendataBytes;
signature = signatureBytes;
}
//
// Otherwise create the token data and signature.
else {
// Grab the MSL token crypto context.
final ICryptoContext cryptoContext;
try {
cryptoContext = ctx.getMslCryptoContext();
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error creating the MSL crypto context.", e);
}
// Encrypt the session data.
final byte[] plaintext = encoder.encodeObject(sessiondata, format);
final byte[] ciphertext;
try {
ciphertext = cryptoContext.encrypt(plaintext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error encrypting the session data.", e);
}
// Construct the token data.
final MslObject tokendata = encoder.createObject();
tokendata.put(KEY_RENEWAL_WINDOW, renewalWindow);
tokendata.put(KEY_EXPIRATION, expiration);
tokendata.put(KEY_SEQUENCE_NUMBER, sequenceNumber);
tokendata.put(KEY_SERIAL_NUMBER, serialNumber);
tokendata.put(KEY_SESSIONDATA, ciphertext);
// Sign the token data.
data = encoder.encodeObject(tokendata, format);
try {
signature = cryptoContext.sign(data, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error signing the token data.", e);
}
}
// Encode the token.
final MslObject token = encoder.createObject();
token.put(KEY_TOKENDATA, data);
token.put(KEY_SIGNATURE, signature);
final byte[] encoding = encoder.encodeObject(token, format);
// Cache and return the encoding.
encodings.put(format, encoding);
return encoding;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject tokendata = encoder.createObject();
tokendata.put(KEY_RENEWAL_WINDOW, renewalWindow);
tokendata.put(KEY_EXPIRATION, expiration);
tokendata.put(KEY_SEQUENCE_NUMBER, sequenceNumber);
tokendata.put(KEY_SERIAL_NUMBER, serialNumber);
tokendata.put(KEY_SESSIONDATA, "(redacted)");
final MslObject token = encoder.createObject();
token.put(KEY_TOKENDATA, tokendata);
token.put(KEY_SIGNATURE, (signatureBytes != null) ? signatureBytes : "(null)");
return token.toString();
}
/**
* <p>Returns true if the other object is a master token with the same
* serial number, sequence number, and expiration. The expiration is
* considered in the event the issuer renews a master token but is unable
* or unwilling to increment the sequence number.</p>
*
* @param obj the reference object with which to compare.
* @return true if the other object is a master token with the same
* serial number, sequence number, and expiration.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj instanceof MasterToken) {
final MasterToken that = (MasterToken)obj;
return this.serialNumber == that.serialNumber &&
this.sequenceNumber == that.sequenceNumber &&
this.expiration == that.expiration;
}
return false;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return (String.valueOf(serialNumber) + ":" + String.valueOf(sequenceNumber) + ":" + String.valueOf(expiration)).hashCode();
}
}
| 1,756 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/tokens/UserIdToken.java
|
/**
* Copyright (c) 2012-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.tokens;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
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.crypto.ICryptoContext;
import com.netflix.msl.io.MslEncodable;
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.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>A user ID token provides proof of user identity. While there can be
* multiple versions of a user ID token, this class should encapsulate support
* for all of those versions.</p>
*
* <p>User ID tokens are bound to a specific master token by the master token's
* serial number.</p>
*
* <p>The renewal window indicates the time after which the user ID token will
* be renewed if requested by the entity. The expiration is the time after
* which the user ID token will be renewed no matter what.</p>
*
* <p>User ID tokens are represented as
* {@code
* useridtoken = {
* "#mandatory" : [ "tokendata", "signature" ],
* "tokendata" : "binary",
* "signature" : "binary"
* }} where:
* <ul>
* <li>{@code tokendata} is the user ID token data (usertokendata)</li>
* <li>{@code signature} is the verification data of the user ID token data</li>
* </ul>
*
* <p>The token data is represented as
* {@code
* usertokendata = {
* "#mandatory" : [ "renewalwindow", "expiration", "mtserialnumber", "serialnumber", "userdata" ],
* "renewalwindow" : "int64(0,-)",
* "expiration" : "int64(0,-)",
* "mtserialnumber" : "int64(0,2^53^)",
* "serialnumber" : "int64(0,2^53^)",
* "userdata" : "binary"
* }} where:
* <ul>
* <li>{@code renewalwindow} is when the renewal window opens in seconds since the epoch</li>
* <li>{@code expiration} is the expiration timestamp in seconds since the epoch</li>
* <li>{@code mtserialnumber} is the master token serial number</li>
* <li>{@code serialnumber} is the user ID token serial number</li>
* <li>{@code userdata} is the encrypted user data (userdata)</li>
* </ul></p>
*
* <p>The decrypted user data is represented as
* {@code
* userdata = {
* "#mandatory" : [ "identity" ],
* "issuerdata" : object,
* "identity" : "string"
* }}
* where:
* <ul>
* <li>{@code issuerdata} is the user ID token issuer data</li>
* <li>{@code identity} is the encoded user identity data</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class UserIdToken implements MslEncodable {
/** Milliseconds per second. */
private static final long MILLISECONDS_PER_SECOND = 1000;
/** Key token data. */
private static final String KEY_TOKENDATA = "tokendata";
/** Key signature. */
private static final String KEY_SIGNATURE = "signature";
// tokendata
/** Key renewal window timestamp. */
private static final String KEY_RENEWAL_WINDOW = "renewalwindow";
/** Key expiration timestamp. */
private static final String KEY_EXPIRATION = "expiration";
/** Key master token serial number. */
private static final String KEY_MASTER_TOKEN_SERIAL_NUMBER = "mtserialnumber";
/** Key user ID token serial number. */
private static final String KEY_SERIAL_NUMBER = "serialnumber";
/** Key token user data. */
private static final String KEY_USERDATA = "userdata";
// userdata
/** Key issuer data. */
private static final String KEY_ISSUER_DATA = "issuerdata";
/** Key identity. */
private static final String KEY_IDENTITY = "identity";
/**
* Create a new user ID token with the specified user.
*
* @param ctx MSL context.
* @param renewalWindow the renewal window.
* @param expiration the expiration.
* @param masterToken the master token.
* @param serialNumber the user ID token serial number.
* @param issuerData the issuer data. May be null.
* @param user the MSL user.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
*/
public UserIdToken(final MslContext ctx, final Date renewalWindow, final Date expiration, final MasterToken masterToken, final long serialNumber, final MslObject issuerData, final MslUser user) throws MslEncodingException, MslCryptoException {
// The expiration must appear after the renewal window.
if (expiration.before(renewalWindow))
throw new MslInternalException("Cannot construct a user ID token that expires before its renewal window opens.");
// A master token must be provided.
if (masterToken == null)
throw new MslInternalException("Cannot construct a user ID token without a master token.");
// The serial number must be within range.
if (serialNumber < 0 || serialNumber > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Serial number " + serialNumber + " is outside the valid range.");
this.ctx = ctx;
this.renewalWindow = renewalWindow.getTime() / MILLISECONDS_PER_SECOND;
this.expiration = expiration.getTime() / MILLISECONDS_PER_SECOND;
this.mtSerialNumber = masterToken.getSerialNumber();
this.serialNumber = serialNumber;
this.issuerdata = issuerData;
this.user = user;
// Construct the user data.
final MslEncoderFactory encoder = this.ctx.getMslEncoderFactory();
this.userdata = encoder.createObject();
if (this.issuerdata != null)
this.userdata.put(KEY_ISSUER_DATA, this.issuerdata);
this.userdata.put(KEY_IDENTITY, user.getEncoded());
this.tokendataBytes = null;
this.signatureBytes = null;
this.verified = true;
}
/**
* Create a new user ID token from the provided MSL object. The associated
* master token must be provided to verify the user ID token.
*
* @param ctx MSL context.
* @param userIdTokenMo user ID token MSL object.
* @param masterToken the master token.
* @throws MslEncodingException if there is an error parsing the data, the
* token data is missing or invalid, or the signature is invalid.
* @throws MslCryptoException if there is an error verifying the token
* data.
* @throws MslException if the user ID token master token serial number
* does not match the master token serial number, or the expiration
* timestamp occurs before the renewal window, or the user data is
* missing or invalid, or the user ID token master token serial
* number is out of range, or the user ID token serial number is
* out of range.
*/
public UserIdToken(final MslContext ctx, final MslObject userIdTokenMo, final MasterToken masterToken) throws MslEncodingException, MslCryptoException, MslException {
this.ctx = ctx;
// Grab the crypto context and encoder.
final ICryptoContext cryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
// Verify the encoding.
try {
tokendataBytes = userIdTokenMo.getBytes(KEY_TOKENDATA);
if (tokendataBytes.length == 0)
throw new MslEncodingException(MslError.USERIDTOKEN_TOKENDATA_MISSING, "useridtoken " + userIdTokenMo).setMasterToken(masterToken);
signatureBytes = userIdTokenMo.getBytes(KEY_SIGNATURE);
verified = cryptoContext.verify(tokendataBytes, signatureBytes, encoder);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "useridtoken " + userIdTokenMo, e).setMasterToken(masterToken);
}
// Pull the token data.
final byte[] plaintext;
try {
final MslObject tokendata = encoder.parseObject(tokendataBytes);
renewalWindow = tokendata.getLong(KEY_RENEWAL_WINDOW);
expiration = tokendata.getLong(KEY_EXPIRATION);
if (expiration < renewalWindow)
throw new MslException(MslError.USERIDTOKEN_EXPIRES_BEFORE_RENEWAL, "usertokendata " + tokendata).setMasterToken(masterToken);
mtSerialNumber = tokendata.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 " + tokendata).setMasterToken(masterToken);
serialNumber = tokendata.getLong(KEY_SERIAL_NUMBER);
if (serialNumber < 0 || serialNumber > MslConstants.MAX_LONG_VALUE)
throw new MslException(MslError.USERIDTOKEN_SERIAL_NUMBER_OUT_OF_RANGE, "usertokendata " + tokendata).setMasterToken(masterToken);
final byte[] ciphertext = tokendata.getBytes(KEY_USERDATA);
if (ciphertext.length == 0)
throw new MslException(MslError.USERIDTOKEN_USERDATA_MISSING).setMasterToken(masterToken);
plaintext = (verified) ? cryptoContext.decrypt(ciphertext, encoder) : null;
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.USERIDTOKEN_TOKENDATA_PARSE_ERROR, "usertokendata " + Base64.encode(tokendataBytes), e).setMasterToken(masterToken);
} catch (final MslCryptoException e) {
e.setMasterToken(masterToken);
throw e;
}
// Pull the user data.
if (plaintext != null) {
try {
userdata = encoder.parseObject(plaintext);
issuerdata = (userdata.has(KEY_ISSUER_DATA)) ? userdata.getMslObject(KEY_ISSUER_DATA, encoder) : null;
final String identity = userdata.getString(KEY_IDENTITY);
if (identity == null || identity.length() == 0)
throw new MslException(MslError.USERIDTOKEN_IDENTITY_INVALID, "userdata " + userdata).setMasterToken(masterToken);
final TokenFactory factory = ctx.getTokenFactory();
user = factory.createUser(ctx, identity);
if (user == null)
throw new MslInternalException("TokenFactory.createUser() returned null in violation of the interface contract.");
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.USERIDTOKEN_USERDATA_PARSE_ERROR, "userdata " + Base64.encode(plaintext), e).setMasterToken(masterToken);
}
} else {
userdata = null;
issuerdata = null;
user = null;
}
// Verify serial numbers.
if (masterToken == null || this.mtSerialNumber != masterToken.getSerialNumber())
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit mtserialnumber " + this.mtSerialNumber + "; mt " + masterToken).setMasterToken(masterToken);
}
/**
* @return true if the decrypted content is available. (Implies verified.)
*/
public boolean isDecrypted() {
return user != null;
}
/**
* @return true if the token has been verified.
*/
public boolean isVerified() {
return verified;
}
/**
* @return the start of the renewal window.
*/
public Date getRenewalWindow() {
return new Date(renewalWindow * MILLISECONDS_PER_SECOND);
}
/**
* <p>Returns true if the user ID token renewal window has been entered.</p>
*
* <ul>
* <li>If a time is provided the renewal window value will be compared
* against the provided time.</li>
* <li>If the user ID token was issued by the local entity the renewal
* window value will be compared against the local entity time. We assume
* its clock at the time of issuance is in sync with the clock now.</li>
* <li>Otherwise the user ID token is considered renewable under the
* assumption that the local time is not synchronized with the master token
* issuing entity time.</li>
* </ul>
*
* @param now the time to compare against. May be {@code null}.
* @return true if the renewal window has been entered.
*/
public boolean isRenewable(final Date now) {
if (now != null)
return renewalWindow * MILLISECONDS_PER_SECOND <= now.getTime();
if (isVerified())
return renewalWindow * MILLISECONDS_PER_SECOND <= ctx.getTime();
return true;
}
/**
* @return the expiration.
*/
public Date getExpiration() {
return new Date(expiration * MILLISECONDS_PER_SECOND);
}
/**
* <p>Returns true if the user ID token is expired.</p>
*
* <ul>
* <li>If a time is provided the expiration value will be compared against
* the provided time.</li>
* <li>If the user ID token was issued by the local entity the expiration
* value will be compared against the local entity time. We assume
* its clock at the time of issuance is in sync with the clock now.</li>
* <li>Otherwise the user ID token is considered not expired under the
* assumption that the local time is not synchronized with the token-
* issuing entity time.</li>
* </ul>
*
* @param now the time to compare against.
* @return true if expired.
*/
public boolean isExpired(final Date now) {
if (now != null)
return expiration * MILLISECONDS_PER_SECOND <= now.getTime();
if (isVerified())
return expiration * MILLISECONDS_PER_SECOND <= ctx.getTime();
return false;
}
/**
* @return the user ID token issuer data or null if there is none or it is
* unknown (user data could not be decrypted).
*/
public MslObject getIssuerData() {
return issuerdata;
}
/**
* @return the MSL user, or null if unknown (user data could not be
* decrypted).
*/
public MslUser getUser() {
return user;
}
/**
* @return the user ID token serial number.
*/
public long getSerialNumber() {
return serialNumber;
}
/**
* Return the serial number of the master token this user ID token is bound
* to.
*
* @return the master token serial number.
*/
public long getMasterTokenSerialNumber() {
return mtSerialNumber;
}
/**
* @param masterToken master token. May be null.
* @return true if this token is bound to the provided master token.
*/
public boolean isBoundTo(final MasterToken masterToken) {
return masterToken != null && masterToken.getSerialNumber() == mtSerialNumber;
}
/** MSL context. */
private final MslContext ctx;
/** User ID token renewal window in seconds since the epoch. */
private final long renewalWindow;
/** User ID token expiration in seconds since the epoch. */
private final long expiration;
/** Master token serial number. */
private final long mtSerialNumber;
/** Serial number. */
private final long serialNumber;
/** User data. */
private final MslObject userdata;
/** Issuer data. */
private final MslObject issuerdata;
/** MSL user. */
private final MslUser user;
/** Token data bytes. */
private final byte[] tokendataBytes;
/** Signature bytes. */
private final byte[] signatureBytes;
/** Token is verified. */
private final boolean verified;
/** Cached encodings. */
private final Map<MslEncoderFormat,byte[]> encodings = new HashMap<MslEncoderFormat,byte[]>();
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
// Return any cached encoding.
if (encodings.containsKey(format))
return encodings.get(format);
// If we parsed this token (i.e. did not create it from scratch) then
// we should not re-encrypt or re-sign as there is no guarantee out MSL
// crypto context is capable of encrypting and signing with the same
// keys, even if it is capable of decrypting and verifying.
final byte[] data, signature;
if (tokendataBytes != null || signatureBytes != null) {
data = tokendataBytes;
signature = signatureBytes;
}
//
// Otherwise create the token data and signature.
else {
// Grab the MSL token crypto context.
final ICryptoContext cryptoContext;
try {
cryptoContext = ctx.getMslCryptoContext();
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error creating the MSL crypto context.", e);
}
// Encrypt the user data.
final byte[] plaintext = encoder.encodeObject(userdata, format);
final byte[] ciphertext;
try {
ciphertext = cryptoContext.encrypt(plaintext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error encrypting the user data.", e);
}
// Construct the token data.
final MslObject tokendata = encoder.createObject();
tokendata.put(KEY_RENEWAL_WINDOW, this.renewalWindow);
tokendata.put(KEY_EXPIRATION, this.expiration);
tokendata.put(KEY_MASTER_TOKEN_SERIAL_NUMBER, this.mtSerialNumber);
tokendata.put(KEY_SERIAL_NUMBER, this.serialNumber);
tokendata.put(KEY_USERDATA, ciphertext);
// Sign the token data.
data = encoder.encodeObject(tokendata, format);
try {
signature = cryptoContext.sign(data, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error signing the token data.", e);
}
}
// Encode the token.
final MslObject token = encoder.createObject();
token.put(KEY_TOKENDATA, data);
token.put(KEY_SIGNATURE, signature);
final byte[] encoding = encoder.encodeObject(token, format);
// Cache and return the encoding.
encodings.put(format, encoding);
return encoding;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject tokendataMo = encoder.createObject();
tokendataMo.put(KEY_RENEWAL_WINDOW, renewalWindow);
tokendataMo.put(KEY_EXPIRATION, expiration);
tokendataMo.put(KEY_MASTER_TOKEN_SERIAL_NUMBER, mtSerialNumber);
tokendataMo.put(KEY_SERIAL_NUMBER, serialNumber);
tokendataMo.put(KEY_USERDATA, "(redacted)");
final MslObject mslObj = encoder.createObject();
mslObj.put(KEY_TOKENDATA, tokendataMo);
mslObj.put(KEY_SIGNATURE, (signatureBytes != null) ? signatureBytes : "(null)");
return mslObj.toString();
}
/**
* <p>Returns true if the other object is a user ID token with the same
* serial number bound to the same master token.</p>
*
* <p>This function is designed for use with sets and maps to guarantee
* uniqueness of individual user ID tokens.</p>
*
* @param obj the reference object with which to compare.
* @return true if the other object is a user ID token with the same serial
* number bound to the same master token.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj instanceof UserIdToken) {
final UserIdToken that = (UserIdToken)obj;
return this.serialNumber == that.serialNumber &&
this.mtSerialNumber == that.mtSerialNumber;
}
return false;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return (String.valueOf(serialNumber) + ":" + String.valueOf(mtSerialNumber)).hashCode();
}
}
| 1,757 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/tokens/TokenFactory.java
|
/**
* Copyright (c) 2012-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.tokens;
import javax.crypto.SecretKey;
import com.netflix.msl.MslConstants.ResponseCode;
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.MslUserIdTokenException;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.MslContext;
/**
* The token factory creates and renews master tokens and user ID tokens.
*
* @author Wesley Miaw <[email protected]>
*/
public interface TokenFactory {
/**
* <p>Return false if the master token has been revoked.</p>
*
* <p>A master token may be revoked at any time after creation and before
* renewal for various reasons, including but not limited to entity
* revocation or knowledge that a master token or its session keys has been
* compromised. The entity will be forced to re-authenticate if its master
* token is rejected.</p>
*
* <p>This method is slightly different than
* {@link #isMasterTokenRenewable(MslContext, MasterToken)} because it
* will be called for every received message and should not check the
* renewability of the master token.</p>
*
* <p>This method should return the exact {@link MslError} identifying the
* reason the master token has been revoked. The response code associated
* with the error will be honored.</p>
*
* @param ctx MSL context.
* @param masterToken the master token to check.
* @return {@code null} if the master token has not been revoked. Otherwise
* return a MSL error.
* @throws MslMasterTokenException if the master token is not trusted.
* @throws MslException if there is an error performing the revocation
* check.
*/
public MslError isMasterTokenRevoked(final MslContext ctx, final MasterToken masterToken) throws MslMasterTokenException, MslException;
/**
* <p>Return true if the non-replayable ID is larger by no more than 65536
* than the largest non-replayable ID accepted so far for the provided
* master token.</p>
*
* <p>Non-replayable IDs should be tracked by the master token entity
* identity and serial number. Before accepting any non-replayable IDs the
* largest value accepted so far shall be considered zero. The maximum non-
* replayable ID is equal to
* {@link com.netflix.msl.MslConstants#MAX_LONG_VALUE} which the IDs wrap
* around to zero. The wrap around must be considered when comparing the
* non-replayable ID to the largest non-replayable ID accepted so far.</p>
*
* <p>It is also permitted to accept non-replayable IDs less than the
* largest non-replayable ID accepted so far if those non-replayable IDs
* have not been seen. The set of smaller non-replayable IDs accepted
* should be limited in size based on a reasonable expectation for the the
* number of concurrent non-replayable messages the entity may create.</p>
*
* <p>This method should return the exact {@link MslError} identifying the
* reason the non-replayable ID was rejected. The response code associated
* with the error will be honored. If the master token entity cannot be
* expected to recover if the message is sent with a new non-replayable ID
* then the response code {@link ResponseCode#ENTITYDATA_REAUTH} should be
* used.</p>
*
* @param ctx MSL context.
* @param masterToken the master token.
* @param nonReplayableId non-replayable ID.
* @return {@code null} if the non-replayable ID has been accepted.
* Otherwise return a MSL error.
* @throws MslMasterTokenException if the master token is not trusted.
* @throws MslException if there is an error comparing or updating the non-
* replayable ID associated with this master token.
* @see #createMasterToken(MslContext, EntityAuthenticationData, SecretKey, SecretKey, MslObject)
* @see MslError#MESSAGE_REPLAYED
* @see MslError#MESSAGE_REPLAYED_UNRECOVERABLE
*/
public MslError acceptNonReplayableId(final MslContext ctx, final MasterToken masterToken, final long nonReplayableId) throws MslMasterTokenException, MslException;
/**
* <p>Create a new master token with the specified identity and session
* keys.</p>
*
* <p>Creating a new master token implies all previous master tokens issued
* to the specified entity are no longer valid and therefore all state data
* for the non-replayable IDs associated with the entity identity may be
* discarded.</p>
*
* @param ctx MSL context.
* @param entityAuthData the entity authentication data.
* @param encryptionKey the session encryption key.
* @param hmacKey the session HMAC key.
* @param issuerData optional master token issuer data that should be
* included in the master token. May be {@code null}.
* @return the new master token.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslException if there is an error creating the master token.
* @see #acceptNonReplayableId(MslContext, MasterToken, long)
*/
public MasterToken createMasterToken(final MslContext ctx, final EntityAuthenticationData entityAuthData, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException, MslException;
/**
* <p>Check if the master token would be renewed by a call to
* {@link #renewMasterToken(MslContext, MasterToken, SecretKey, SecretKey, MslObject)}.</p>
*
* <p>This method should return the exact {@link MslError} identifying the
* reason the master token will not be renewed.</p>
*
* @param ctx MSL context.
* @param masterToken the master token to check.
* @return {@code null} if the master token would be renewed. Otherwise
* return a MSL error.
* @throws MslMasterTokenException if the master token is not trusted.
* @throws MslException if there is an error checking the master token
* renewability.
* @see #renewMasterToken(MslContext, MasterToken, SecretKey, SecretKey, MslObject)
*/
public MslError isMasterTokenRenewable(final MslContext ctx, final MasterToken masterToken) throws MslMasterTokenException, MslException;
/**
* <p>Renew a master token assigning it the new session keys.</p>
*
* <p>This method should also perform any additional entity checks such as
* if the entity has been revoked.</p>
*
* @param ctx MSL context.
* @param masterToken the master token to renew.
* @param encryptionKey the session encryption key.
* @param hmacKey the session HMAC key.
* @param issuerData optional master token issuer data that should be
* merged into or overwrite any existing issuer data. May be
* {@code null}.
* @return the new master token.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslMasterTokenException if the master token is not trusted or
* the factory does not wish to renew it.
* @throws MslException if there is an error renewing the master token.
* @see #isMasterTokenRenewable(MslContext, MasterToken)
*/
public MasterToken renewMasterToken(final MslContext ctx, final MasterToken masterToken, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException, MslMasterTokenException, MslException;
/**
* <p>Return false if the user ID token has been revoked.</p>
*
* <p>A user ID token may be revoked at any time after creation and before
* renewal for various reasons, including but not limited to user deletion.
* The user will be forced to re-authenticate if its user ID token is
* rejected.</p>
*
* <p>This method should return the exact {@link MslError} identifying the
* reason the user ID token has been revoked.</p>
*
* @param ctx MSL context.
* @param masterToken the associated master token.
* @param userIdToken the user ID token to check.
* @return {@code null} if the user ID token has not been revoked.
* Otherwise return a MSL error.
* @throws MslMasterTokenException if the master token is not trusted.
* @throws MslUserIdTokenException if the user ID token is not trusted.
* @throws MslException if there is an error performing the revocation
* check.
*/
public MslError isUserIdTokenRevoked(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken) throws MslMasterTokenException, MslUserIdTokenException, MslException;
/**
* Create a new user ID token bound to the provided master token.
*
* @param ctx MSL context.
* @param user MSL user.
* @param masterToken the master token to bind the user token against.
* @return the new user ID token.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslMasterTokenException if the master token is not trusted.
* @throws MslException if there is an error creating the user ID token.
*/
public UserIdToken createUserIdToken(final MslContext ctx, final MslUser user, final MasterToken masterToken) throws MslEncodingException, MslCryptoException, MslMasterTokenException, MslException;
/**
* <p>Renew a user ID token and bind it to the provided master token.</p>
*
* <p>This method should also perform any additional user checks such as if
* the user no longer exists or must re-login.</p>
*
* @param ctx MSL context.
* @param userIdToken the user ID token to renew.
* @param masterToken the master token to bind the user token against.
* @return the new user ID token.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslUserIdTokenException if the user ID token is not decrypted or
* the factory does not wish to renew it.
* @throws MslMasterTokenException if the master token is not trusted.
* @throws MslException if there is an error renewing the user ID token.
*/
public UserIdToken renewUserIdToken(final MslContext ctx, final UserIdToken userIdToken, final MasterToken masterToken) throws MslEncodingException, MslCryptoException, MslUserIdTokenException, MslMasterTokenException, MslException;
/**
* <p>Create a new MSL user instance from the serialized user data.</p>
*
* <p>This method is called when reconstructing a user ID token. Thrown
* {@link MslException}s should keep that in mind when deciding upon the
* {@link MslError} to reference.</p>
*
* @param ctx MSL context.
* @param userdata serialized user data.
* @return the MSL user.
* @throws MslEncodingException if there is an error parsing the user data.
* @throws MslException if there is an error creating the MSL user.
*/
public MslUser createUser(final MslContext ctx, final String userdata) throws MslEncodingException, MslException;
}
| 1,758 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/tokens/ServiceToken.java
|
/**
* Copyright (c) 2012-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.tokens;
import java.util.HashMap;
import java.util.Map;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
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.crypto.ICryptoContext;
import com.netflix.msl.io.MslEncodable;
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.util.Base64;
import com.netflix.msl.util.MslCompression;
import com.netflix.msl.util.MslContext;
/**
* <p>Service tokens are service-defined tokens carried as part of any MSL
* message. These tokens should be used to carry service state.</p>
*
* <p>Service tokens are optionally bound to a specific master token and user
* ID token by their serial numbers.</p>
*
* <p>Service tokens are either verified or encrypted. Verified tokens carry
* their data in the clear but are accompanied by a signature allowing the
* issuer to ensure the data has not been tampered with. Encrypted tokens
* encrypt their data as well as contain a signature.</p>
*
* <p>Service tokens should use application- or service-specific crypto
* contexts and not the crypto context associated with the entity credentials
* or master token.</p>
*
* <p>Service tokens are represented as
* {@code
* servicetoken = {
* "#mandatory" : [ "tokendata", "signature" ],
* "tokendata" : "binary",
* "signature" : "binary"
* }} where:
* <ul>
* <li>{@code tokendata} is the service token data (servicetokendata)</li>
* <li>{@code signature} is the verification data of the service token data</li>
* </ul></p>
*
* <p>The token data is represented as
* {@code
* servicetokendata = {
* "#mandatory" : [ "name", "mtserialnumber", "uitserialnumber", "encrypted", "servicedata" ],
* "name" : "string",
* "mtserialnumber" : "int64(0,2^53^)",
* "uitserialnumber" : "int64(0,2^53^)",
* "encrypted" : "boolean",
* "compressionalgo" : "enum(GZIP|LZW)",
* "servicedata" : "binary"
* }} where:
* <ul>
* <li>{@code name} is the token name</li>
* <li>{@code mtserialnumber} is the master token serial number or -1 if unbound</li>
* <li>{@code utserialnumber} is the user ID token serial number or -1 if unbound</li>
* <li>{@code encrypted} indicates if the service data is encrypted or not</li>
* <li>{@code compressionalgo} indicates the algorithm used to compress the data</li>
* <li>{@code servicedata} is the optionally encrypted service data</li>
* </ul></p>
*
* <p>Service token names should follow a reverse fully-qualified domain
* hierarchy. e.g. {@literal com.netflix.service.tokenname}.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class ServiceToken implements MslEncodable {
/** Key token data. */
private static final String KEY_TOKENDATA = "tokendata";
/** Key signature. */
private static final String KEY_SIGNATURE = "signature";
// tokendata
/** Key token name. */
private static final String KEY_NAME = "name";
/** Key master token serial number. */
private static final String KEY_MASTER_TOKEN_SERIAL_NUMBER = "mtserialnumber";
/** Key user ID token serial number. */
private static final String KEY_USER_ID_TOKEN_SERIAL_NUMBER = "uitserialnumber";
/** Key encrypted. */
private static final String KEY_ENCRYPTED = "encrypted";
/** Key compression algorithm. */
private static final String KEY_COMPRESSION_ALGORITHM = "compressionalgo";
/** Key service data. */
private static final String KEY_SERVICEDATA = "servicedata";
/**
* <p>Select the appropriate crypto context for the service token
* represented by the provided MSL object.</p>
*
* <p>If the service token name exists as a key in the map of crypto
* contexts, the mapped crypto context will be returned. Otherwise the
* default crypto context mapped from the empty string key will be
* returned. If no explicit or default crypto context exists null will be
* returned.</p>
*
* @param encoder the MSL encoder factory.
* @param serviceTokenMo the MSL object.
* @param cryptoContexts the map of service token names onto crypto
* contexts used to decrypt and verify service tokens.
* @return the correct crypto context for the service token or null.
* @throws MslEncodingException if there is a problem parsing the data.
*/
private static ICryptoContext selectCryptoContext(final MslEncoderFactory encoder, final MslObject serviceTokenMo, final Map<String,ICryptoContext> cryptoContexts) throws MslEncodingException {
try {
final byte[] tokendata = serviceTokenMo.getBytes(KEY_TOKENDATA);
if (tokendata.length == 0)
throw new MslEncodingException(MslError.SERVICETOKEN_TOKENDATA_MISSING, "servicetoken " + serviceTokenMo);
final MslObject tokenDataMo = encoder.parseObject(tokendata);
final String name = tokenDataMo.getString(KEY_NAME);
if (cryptoContexts.containsKey(name))
return cryptoContexts.get(name);
return cryptoContexts.get("");
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "servicetoken " + serviceTokenMo, e);
}
}
/**
* <p>Construct a new service token with the specified name and data. If a
* master token is provided, the service token is bound to the master
* token's serial number. If a user ID token is provided, the service token
* is bound to the user ID token's serial number.</p>
*
* <p>For encrypted tokens, the token data is encrypted using the provided
* crypto context. For verified tokens, the token data is signed using the
* provided crypto context.</p>
*
* @param ctx the MSL context.
* @param name the service token name--must be unique.
* @param data the service token data (unencrypted).
* @param masterToken the master token. May be null.
* @param userIdToken the user ID token. May be null.
* @param encrypted true if the token should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @param cryptoContext the crypto context.
* @throws MslException if there is an error compressing the data.
*/
public ServiceToken(final MslContext ctx, final String name, final byte[] data, final MasterToken masterToken, final UserIdToken userIdToken, final boolean encrypted, final CompressionAlgorithm compressionAlgo, final ICryptoContext cryptoContext) throws MslException {
this.ctx = ctx;
// If both master token and user ID token are provided the user ID
// token must be bound to the master token.
if (masterToken != null && userIdToken != null && !userIdToken.isBoundTo(masterToken))
throw new MslInternalException("Cannot construct a service token bound to a master token and user ID token where the user ID token is not bound to the same master token.");
// The crypto context may not be null.
if (cryptoContext == null)
throw new NullPointerException("Crypto context may not be null.");
// Set token properties.
this.name = name;
this.mtSerialNumber = (masterToken != null) ? masterToken.getSerialNumber() : -1;
this.uitSerialNumber = (userIdToken != null) ? userIdToken.getSerialNumber() : -1;
this.servicedata = data;
this.encrypted = encrypted;
// Optionally compress the service data.
if (compressionAlgo != null) {
final byte[] compressed = MslCompression.compress(compressionAlgo, data);
// Only use compression if the compressed data is smaller than the
// uncompressed data.
if (compressed != null && compressed.length < data.length) {
this.compressionAlgo = compressionAlgo;
this.compressedServicedata = compressed;
} else {
this.compressionAlgo = null;
this.compressedServicedata = data;
}
} else {
this.compressionAlgo = null;
this.compressedServicedata = data;
}
// Save the crypto context.
this.cryptoContext = cryptoContext;
this.tokendataBytes = null;
this.signatureBytes = null;
this.verified = true;
}
/**
* <p>Construct a new service token from the provided MSL object and
* attempt to decrypt and verify the signature of the service token using
* the appropriate crypto context. If the data cannot be decrypted or the
* signature cannot be verified, the token will still be created.</p>
*
* <p>If the service token name exists as a key in the map of crypto
* contexts, the mapped crypto context will be used. Otherwise the default
* crypto context mapped from the empty string key will be used.</p>
*
* <p>If a matching crypto context is found, the token data will be
* decrypted and its signature verified.</p>
*
* <p>If the service token is bound to a master token or user ID token it
* will be verified against the provided master token or user ID tokens
* which must not be null.</p>
*
* @param ctx the MSL context.
* @param serviceTokenMo the MSL object.
* @param masterToken the master token. May be null.
* @param userIdToken the user ID token. May be null.
* @param cryptoContexts a map of service token names onto crypto contexts.
* @throws MslEncodingException if there is a problem parsing the data.
* @throws MslCryptoException if there is an error decrypting or verifying
* the token data.
* @throws MslException if the service token is bound to a master token or
* user ID token and the provided tokens are null or the serial
* numbers do not match, or if bound to a user ID token but not to
* a master token, or if the service data is missing, or if the
* compression algorithm is not known or there is an error
* uncompressing the data.
*/
public ServiceToken(final MslContext ctx, final MslObject serviceTokenMo, final MasterToken masterToken, final UserIdToken userIdToken, final Map<String,ICryptoContext> cryptoContexts) throws MslEncodingException, MslCryptoException, MslException {
this(ctx, serviceTokenMo, masterToken, userIdToken, selectCryptoContext(ctx.getMslEncoderFactory(), serviceTokenMo, cryptoContexts));
}
/**
* <p>Construct a new service token from the provided MSL object.</p>
*
* <p>If a crypto context is provided, the token data will be decrypted and
* its signature verified. If the data cannot be decrypted or the signature
* cannot be verified, the token will still be created.</p>
*
* <p>If the service token is bound to a master token or user ID token it
* will be verified against the provided master token or user ID tokens
* which must not be null.</p>
*
* @param ctx the MSL context.
* @param serviceTokenMo the MSL object.
* @param masterToken the master token. May be null.
* @param userIdToken the user ID token. May be null.
* @param cryptoContext the crypto context. May be null.
* @throws MslCryptoException if there is a problem decrypting or verifying
* the token data.
* @throws MslEncodingException if there is a problem parsing the data, the
* token data is missing or invalid, or the signature is invalid.
* @throws MslException if the service token is bound to a master token or
* user ID token and the provided tokens are null or the serial
* numbers do not match, or if bound to a user ID token but not to
* a master token, or if the service data is missing, or if the
* service token master token serial number is out of range, or if
* the service token user ID token serial number is out of range,
* or if the compression algorithm is not known or there is an
* error uncompressing the data.
*/
public ServiceToken(final MslContext ctx, final MslObject serviceTokenMo, final MasterToken masterToken, final UserIdToken userIdToken, final ICryptoContext cryptoContext) throws MslCryptoException, MslEncodingException, MslException {
this.ctx = ctx;
this.cryptoContext = cryptoContext;
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
// Verify the data representation.
try {
tokendataBytes = serviceTokenMo.getBytes(KEY_TOKENDATA);
if (tokendataBytes.length == 0)
throw new MslEncodingException(MslError.SERVICETOKEN_TOKENDATA_MISSING, "servicetoken " + serviceTokenMo).setMasterToken(masterToken).setUserIdToken(userIdToken);
signatureBytes = serviceTokenMo.getBytes(KEY_SIGNATURE);
verified = (cryptoContext != null) ? cryptoContext.verify(tokendataBytes, signatureBytes, encoder) : false;
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "servicetoken " + serviceTokenMo, e).setMasterToken(masterToken).setUserIdToken(userIdToken);
} catch (final MslCryptoException e) {
e.setMasterToken(masterToken);
throw e;
}
// Pull the token data.
try {
final MslObject tokendata = encoder.parseObject(tokendataBytes);
name = tokendata.getString(KEY_NAME);
if (tokendata.has(KEY_MASTER_TOKEN_SERIAL_NUMBER)) {
mtSerialNumber = tokendata.getLong(KEY_MASTER_TOKEN_SERIAL_NUMBER);
if (mtSerialNumber < 0 || mtSerialNumber > MslConstants.MAX_LONG_VALUE)
throw new MslException(MslError.SERVICETOKEN_MASTERTOKEN_SERIAL_NUMBER_OUT_OF_RANGE, "servicetokendata " + tokendata).setMasterToken(masterToken).setUserIdToken(userIdToken);
} else {
mtSerialNumber = -1;
}
if (tokendata.has(KEY_USER_ID_TOKEN_SERIAL_NUMBER)) {
uitSerialNumber = tokendata.getLong(KEY_USER_ID_TOKEN_SERIAL_NUMBER);
if (uitSerialNumber < 0 || uitSerialNumber > MslConstants.MAX_LONG_VALUE)
throw new MslException(MslError.SERVICETOKEN_USERIDTOKEN_SERIAL_NUMBER_OUT_OF_RANGE, "servicetokendata " + tokendata).setMasterToken(masterToken).setUserIdToken(userIdToken);
} else {
uitSerialNumber = -1;
}
// There has to be a master token serial number if there is a
// user ID token serial number.
encrypted = tokendata.getBoolean(KEY_ENCRYPTED);
if (tokendata.has(KEY_COMPRESSION_ALGORITHM)) {
final String algoName = tokendata.getString(KEY_COMPRESSION_ALGORITHM);
try {
compressionAlgo = CompressionAlgorithm.valueOf(algoName);
} catch (final IllegalArgumentException e) {
throw new MslException(MslError.UNIDENTIFIED_COMPRESSION, algoName, e);
}
} else {
compressionAlgo = null;
}
// If encrypted, and we were able to verify the data then we better
// be able to decrypt it. (An exception is thrown if decryption
// fails.)
final byte[] data = tokendata.getBytes(KEY_SERVICEDATA);
if (verified) {
final byte[] ciphertext = data;
compressedServicedata = (encrypted && ciphertext.length > 0)
? cryptoContext.decrypt(ciphertext, encoder)
: ciphertext;
servicedata = (compressionAlgo != null)
? MslCompression.uncompress(compressionAlgo, compressedServicedata)
: compressedServicedata;
} else {
compressedServicedata = data;
servicedata = (data.length == 0) ? new byte[0] : null;
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "servicetokendata " + Base64.encode(tokendataBytes), e).setMasterToken(masterToken).setUserIdToken(userIdToken);
} catch (final MslCryptoException e) {
e.setMasterToken(masterToken);
e.setUserIdToken(userIdToken);
throw e;
}
// Verify serial numbers.
if (mtSerialNumber != -1 && (masterToken == null || mtSerialNumber != masterToken.getSerialNumber()))
throw new MslException(MslError.SERVICETOKEN_MASTERTOKEN_MISMATCH, "st mtserialnumber " + mtSerialNumber + "; mt " + masterToken).setMasterToken(masterToken).setUserIdToken(userIdToken);
if (uitSerialNumber != -1 && (userIdToken == null || uitSerialNumber != userIdToken.getSerialNumber()))
throw new MslException(MslError.SERVICETOKEN_USERIDTOKEN_MISMATCH, "st uitserialnumber " + uitSerialNumber + "; uit " + userIdToken).setMasterToken(masterToken).setUserIdToken(userIdToken);
}
/**
* @return true if the content is encrypted.
*/
public boolean isEncrypted() {
return encrypted;
}
/**
* @return true if the decrypted content is available. (Implies verified.)
*/
public boolean isDecrypted() {
return servicedata != null;
}
/**
* @return true if the token has been verified.
*/
public boolean isVerified() {
return verified;
}
/**
* @return the application token name.
*/
public String getName() {
return name;
}
/**
* @return true if this token has been marked for deletion.
* @see #getData()
*/
public boolean isDeleted() {
return servicedata != null && servicedata.length == 0;
}
/**
* @return the compression algorithm. May be {@code null} if not
* compressed.
*/
public CompressionAlgorithm getCompressionAlgo() {
return compressionAlgo;
}
/**
* Returns the service data if the token data was not encrypted or we were
* able to decrypt it.
*
* Zero-length data indicates this token should be deleted.
*
* @return the service data or null if we don't have it.
* @see #isDeleted()
*/
public byte[] getData() {
return servicedata;
}
/**
* Returns the serial number of the master token this service token is
* bound to.
*
* @return the master token serial number or -1 if unbound.
*/
public long getMasterTokenSerialNumber() {
return mtSerialNumber;
}
/**
* @return true if this token is bound to a master token.
*/
public boolean isMasterTokenBound() {
return mtSerialNumber != -1;
}
/**
* @param masterToken master token. May be null.
* @return true if this token is bound to the provided master token.
*/
public boolean isBoundTo(final MasterToken masterToken) {
return masterToken != null && masterToken.getSerialNumber() == mtSerialNumber;
}
/**
* Returns the serial number of the user ID token this service token is
* bound to.
*
* @return the user ID token serial number or -1 if unbound.
*/
public long getUserIdTokenSerialNumber() {
return uitSerialNumber;
}
/**
* Returns true if this token is bound to a user ID token. This implies the
* token is bound to a master token as well.
*
* @return true if this token is bound to a user ID token.
*/
public boolean isUserIdTokenBound() {
return uitSerialNumber != -1;
}
/**
* @param userIdToken user ID token. May be null.
* @return true if this token is bound to the provided user ID token.
*/
public boolean isBoundTo(final UserIdToken userIdToken) {
return userIdToken != null && userIdToken.getSerialNumber() == uitSerialNumber;
}
/**
* @return true if this token is not bound to a master token or user ID
* token.
*/
public boolean isUnbound() {
return mtSerialNumber == -1 && uitSerialNumber == -1;
}
/** MSL context. */
private final MslContext ctx;
/** Service token crypto context. */
private final ICryptoContext cryptoContext;
/** The service token name. */
private final String name;
/** The service token master token serial number. */
private final long mtSerialNumber;
/** The service token user ID token serial number. */
private final long uitSerialNumber;
/** Service token data is encrypted. */
private final boolean encrypted;
/** Compression algorithm. */
private final CompressionAlgorithm compressionAlgo;
/** The service token data. */
private final byte[] servicedata;
/** The compressed service token data. */
private final byte[] compressedServicedata;
/** Token data bytes. */
private final byte[] tokendataBytes;
/** Signature bytes. */
private final byte[] signatureBytes;
/** Token is verified. */
private final boolean verified;
/** Cached encodings. */
private final Map<MslEncoderFormat,byte[]> encodings = new HashMap<MslEncoderFormat,byte[]>();
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
// Return any cached encoding.
if (encodings.containsKey(format))
return encodings.get(format);
// If we parsed this token (i.e. did not create it from scratch) then
// we should not re-encrypt or re-sign as there is no guarantee out MSL
// crypto context is capable of encrypting and signing with the same
// keys, even if it is capable of decrypting and verifying.
final byte[] data, signature;
if (tokendataBytes != null || signatureBytes != null) {
data = tokendataBytes;
signature = signatureBytes;
}
//
// Otherwise create the token data and signature.
else {
// Encrypt the service data if the length is > 0. Otherwise encode
// as empty data to indicate this token should be deleted.
final byte[] ciphertext;
try {
ciphertext = (encrypted && compressedServicedata.length > 0)
? cryptoContext.encrypt(compressedServicedata, encoder, format)
: compressedServicedata;
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error encrypting the service data.", e);
}
// Construct the token data.
final MslObject tokendata = encoder.createObject();
tokendata.put(KEY_NAME, this.name);
if (this.mtSerialNumber != -1) tokendata.put(KEY_MASTER_TOKEN_SERIAL_NUMBER, this.mtSerialNumber);
if (this.uitSerialNumber != -1) tokendata.put(KEY_USER_ID_TOKEN_SERIAL_NUMBER, this.uitSerialNumber);
tokendata.put(KEY_ENCRYPTED, this.encrypted);
if (this.compressionAlgo != null) tokendata.put(KEY_COMPRESSION_ALGORITHM, this.compressionAlgo.name());
tokendata.put(KEY_SERVICEDATA, ciphertext);
// Sign the token data.
data = encoder.encodeObject(tokendata, format);
try {
signature = cryptoContext.sign(data, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error signing the token data.", e);
}
}
// Encode the token.
final MslObject token = encoder.createObject();
token.put(KEY_TOKENDATA, data);
token.put(KEY_SIGNATURE, signature);
final byte[] encoding = encoder.encodeObject(token, format);
// Cache and return the encoding.
encodings.put(format, encoding);
return encoding;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject tokendata = encoder.createObject();
tokendata.put(KEY_NAME, name);
tokendata.put(KEY_MASTER_TOKEN_SERIAL_NUMBER, mtSerialNumber);
tokendata.put(KEY_USER_ID_TOKEN_SERIAL_NUMBER, uitSerialNumber);
tokendata.put(KEY_SERVICEDATA, "(redacted)");
final MslObject token = encoder.createObject();
token.put(KEY_TOKENDATA, tokendata);
token.put(KEY_SIGNATURE, (signatureBytes != null) ? signatureBytes : "(null)");
return token.toString();
}
/**
* <p>Returns true if the other object is a service token with the same
* name and bound to the same tokens.</p>
*
* <p>This function is designed for use with sets and maps to guarantee
* uniqueness of individual service tokens.</p>
*
* @param obj the reference object with which to compare.
* @return true if the other object is a service token with the same name
* and bound to the same tokens.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj instanceof ServiceToken) {
final ServiceToken that = (ServiceToken)obj;
return this.name.equals(that.name) &&
this.mtSerialNumber == that.mtSerialNumber &&
this.uitSerialNumber == that.uitSerialNumber;
}
return false;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return (this.name + ":" + String.valueOf(mtSerialNumber) + ":" + String.valueOf(uitSerialNumber)).hashCode();
}
}
| 1,759 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/tokens/ClientTokenFactory.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.tokens;
import javax.crypto.SecretKey;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.MslContext;
/**
* This class should be used by trusted network clients for the token factory.
* Since trusted network clients do not issue tokens the mamority of these
* methods either return under the assumption everything should be accepted or
* trusted, or throw exceptions if the operation should never occur.
*
* @author Wesley Miaw <[email protected]>
*/
public class ClientTokenFactory 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) {
throw new MslInternalException("Creating master tokens is unsupported by the token factory.");
}
/* (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) {
throw new MslInternalException("Renewing master tokens is unsupported by the token factory.");
}
/* (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) {
throw new MslInternalException("Creating user ID tokens is unsupported by the token factory.");
}
/* (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) {
throw new MslInternalException("Renewing master tokens is unsupported by the token factory.");
}
/* (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) {
throw new MslInternalException("Creating users is unsupported by the token factory.");
}
}
| 1,760 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/tokens/MslUser.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.tokens;
/**
* <p>A MSL user. The {@link #equals(Object)} and {@link #hashCode()} methods
* must be implemented.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public interface MslUser {
/**
* <p>Returns a serialized data encoding of the MSL user. This is the value
* that will be used by the MSL stack during transport and to reconstruct
* the MSL user instance.</p>
*
* @return the MSL user encoding.
*/
public String getEncoded();
/**
* <p>Compares this object against the provided object. This method must
* return true if the provided object is a {@code MslUser} referencing the
* same MSL user.</p>
*
* @param obj the object with which to compare.
* @return {@code true} if the object is a {@code MslUser} that references
* the same MSL user.
* @see #hashCode()
*/
@Override
public boolean equals(final Object obj);
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode();
}
| 1,761 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/X509Store.java
|
/**
* Copyright (c) 1997-2013 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.entityauth;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.x500.X500Principal;
import com.netflix.msl.util.Base64;
/**
* <p>An X.509 certificate store.</p>
*
* <p>This class provides a clearing house of X.509 certificate validation. It
* contains individual trusted certificates, trusted certificate chains, and
* may support CRLs in the future. It provides X.509 certificate signature
* verification, certificate chaining, validity (time) checks, and trust store
* management functionality.</p>
*/
public class X509Store {
/**
* <p>Return the issuing certificate for the provided certificate. The
* certificate will only be returned if the provided certificate signature
* is verified by the issuing certificate.</p>
*
* @param cert the certificate.
* @return the issuing certificate or {@code null} if not found.
*/
private X509Certificate getIssuer(final X509Certificate cert) {
final X500Principal issuerDn = cert.getIssuerX500Principal();
final List<X509Certificate> issuers = store.get(issuerDn);
if (issuers == null)
return null;
for (final X509Certificate issuer : issuers) {
try {
cert.verify(issuer.getPublicKey());
return issuer;
} catch (final Exception e) {
// Ignore failures.
}
}
return null;
}
/**
* <p>Returns the chain of issuer certificates for the provided
* certificate.</p>
*
* <p>The first certificate in the chain will be self-signed and will be
* ordered with the root certificate in the first position.</p>
*
* @param cert the certificate.
* @return the ordered chain of issuer certificates.
* @throws CertificateException if an issuer certificate cannot be found.
*/
private List<X509Certificate> getIssuerChain(final X509Certificate cert) throws CertificateException {
final List<X509Certificate> chain = new ArrayList<X509Certificate>();
X509Certificate current = cert;
do {
final X509Certificate issuer = getIssuer(current);
if (issuer == null)
throw new CertificateException("No issuer found for certificate: " + Base64.encode(current.getEncoded()));
chain.add(0, issuer);
current = issuer;
} while (!isSelfSigned(current));
return chain;
}
/**
* <p>Return true if the certificate is self-signed.</p>
*
* @param cert the certificate.
* @return true if the certificate is self-signed.
*/
private static boolean isSelfSigned(final X509Certificate cert) {
final X500Principal subject = cert.getSubjectX500Principal();
final X500Principal issuer = cert.getIssuerX500Principal();
return subject.equals(issuer);
}
/**
* @param cert the certificate.
* @return true if the certificate is verified by a trusted certificate.
*/
private boolean isVerified(final X509Certificate cert) {
final X509Certificate issuer = getIssuer(cert);
return (issuer != null);
}
/**
* <p>Verifies that the provided certificate is allowed to be a CA
* certificate based on the issuer chain's path lengths.</p>
*
* @param cert the certificate.
* @return true if the certificate distance from its issuers is acceptable.
* @throws CertificateException if an issuer certificate cannot be found.
*/
private boolean isPermittedByIssuer(final X509Certificate cert) throws CertificateException {
// Get the issuer chain. It should never be empty.
final List<X509Certificate> issuerChain = getIssuerChain(cert);
if (issuerChain.isEmpty())
return false;
// If at any point in the chain we see a path length set, we use "lazy"
// chain enforcement: the path length field is optional for all
// subordinate CA certificates as long the path length has not been
// exceeded and any path lengths of subordinate certificates are equal
// to or less than the expected path length.
int expectedPathLength = -1;
for (final X509Certificate issuer : issuerChain) {
final int nextPathLength = issuer.getBasicConstraints();
// There is no path length in this issuing certificate...
if (nextPathLength == -1) {
// If there is no path length from a superior certificate then
// fail.
if (expectedPathLength == -1)
return false;
// Otherwise decrement the current path length.
--expectedPathLength;
}
// Otherwise if this is our first path length then start using it.
else if (expectedPathLength == -1) {
expectedPathLength = nextPathLength;
}
// Otherwise if this certificate's path length is too large then
// fail.
else if (nextPathLength > expectedPathLength) {
return false;
}
// Otherwise the new path length is acceptable.
else {
expectedPathLength = nextPathLength;
}
// Make sure the path length is not zero.
if (expectedPathLength == 0)
return false;
}
// Make sure this certificate's path length is equal to or less than
// the expected path length.
final int next = cert.getBasicConstraints();
if (next != -1 && next > expectedPathLength)
return false;
// Success.
return true;
}
/**
* <p>Add one or more trusted certificates (in DER format, binary or Base64-
* encoded) to this X509Store.</p>
*
* <p>This method calls {@link #addTrusted(X509Certificate)} on each
* certificate found. If an exception is thrown, any certificates
* parsed prior to the error will still be in the trust store.</p>
*
* @param input the input stream.
* @throws IOException if there is an error reading the input stream.
* @throws CertificateExpiredException if the certificate is expired.
* @throws CertificateNotYetValidException if the certificate is not yet
* valid.
* @throws CertificateException if a certificate is not a CA certificate, a
* certificate is not self-signed and not trusted by an existing
* trusted certificate, a certificate is not permitted as a
* subordinate certificate, a certificate is malformed, or there is
* no X.509 certificate factory.
* @throws SignatureException if the certificate signature cannot be or
* fails to verify for any reason including a malformed certificate.
* @throws NoSuchAlgorithmException if the signature algorithm is
* unsupported.
* @throws InvalidKeyException if a certificate public key is invalid.
* @throws NoSuchProviderException if there is no X.509 certificate
* provider.
*/
public void addTrusted(final InputStream input) throws CertificateExpiredException, CertificateNotYetValidException, CertificateException, IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, NoSuchProviderException {
final BufferedInputStream bis = new BufferedInputStream(input);
final CertificateFactory factory = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
final X509Certificate cert = (X509Certificate)factory.generateCertificate(bis);
addTrusted(cert);
}
}
/**
* <p>Add a chain of trusted certificates to this X509Store.</p>
*
* <p>The first certificate in the chain must be self-signed, and all
* certificates must be CA certificates. The list must be ordered with the
* root certificate in the first position and the leaf certificate in the
* last position.</p>
*
* @param chain the ordered chain of certificates.
* @throws NoSuchAlgorithmException if the signature algorithm is
* unsupported.
* @throws InvalidKeyException if an certificate's public key is invalid.
* @throws NoSuchProviderException if there is no signature provider.
* @throws SignatureException if a certificate signature verification fails.
* @throws CertificateExpiredException if the certificate is expired.
* @throws CertificateNotYetValidException if the certificate is not yet
* valid.
* @throws CertificateException if a certificate is malformed or the first
* certificate is not a self-signed certificate.
*/
public void addTrusted(final List<X509Certificate> chain) throws CertificateExpiredException, CertificateNotYetValidException, CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
// Do nothing if the chain is null or empty.
if (chain == null || chain.isEmpty())
return;
// Verify that the root certificate is self-signed and add it.
X509Certificate issuer = chain.get(0);
if(!isSelfSigned(issuer))
throw new CertificateException("First certificate is not self-signed: " + Base64.encode(issuer.getEncoded()));
addTrusted(issuer);
// Add subordinate certificates.
for (int i = 1; i < chain.size(); ++i) {
final X509Certificate cert = chain.get(i);
cert.verify(issuer.getPublicKey());
addTrusted(cert);
issuer = cert;
}
}
/**
* <p>Add a trusted certificate (in DER format, binary or Base64-encoded)
* to this X509Store.</p>
*
* <p>This method verifies the certificate. That has the effect of
* requiring the CA root certificate to be added before any subordinate
* CA certificates.</p>
*
* <p>To add a certificate chain, use {@link #addTrusted(List)} instead.</p>
*
* @param cert the X.509 certificate to add.
* @throws CertificateExpiredException if the certificate is expired.
* @throws CertificateNotYetValidException if the certificate is not yet
* valid.
* @throws CertificateException if the certificate is not a CA certificate,
* the certificate is not self-signed and not trusted by an
* existing trusted certificate, or the certificate is not
* permitted as a subordinate certificate, or the certificate is
* malformed.
* @throws SignatureException if the certificate signature cannot be or
* fails to verify for any reason including a malformed certificate.
* @throws NoSuchAlgorithmException if the signature algorithm is
* unsupported.
* @throws InvalidKeyException if a certificate public key is invalid.
* @throws NoSuchProviderException if there is no X.509 certificate
* provider.
*/
public void addTrusted(final X509Certificate cert) throws CertificateExpiredException, CertificateNotYetValidException, CertificateException, SignatureException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
// Verify the certificate not-yet-valid and expiration dates.
cert.checkValidity();
// Verify this is a CA certificate.
final int pathlen = cert.getBasicConstraints();
if (pathlen < 0)
throw new CertificateException("Certificate is not a CA certificate: " + Base64.encode(cert.getEncoded()));
// Verify the certificate signature.
if (isSelfSigned(cert)) {
cert.verify(cert.getPublicKey());
} else {
if (!isVerified(cert))
throw new CertificateException("Certificate is not self-signed and not trusted by any known CA certificate: " + Base64.encode(cert.getEncoded()));
// Subordinate certificates must have their path length validated.
if (!isPermittedByIssuer(cert))
throw new CertificateException("Certificate appears too far from its issuing CA certificate: " + Base64.encode(cert.getEncoded()));
}
// Add the certificate.
final X500Principal subjectName = cert.getSubjectX500Principal();
if (!store.containsKey(subjectName))
store.put(subjectName, new ArrayList<X509Certificate>());
final List<X509Certificate> certs = store.get(subjectName);
if (!certs.contains(cert))
certs.add(cert);
}
/**
* <p>Add a trusted certificate (in DER format, binary or Base64-encoded)
* and its corresponding private key to this X509Store.</p>
*
* <p>This method verifies the certificate. That has the effect of
* requiring the CA root certificate to be added before any subordinate
* CA certificates.</p>
*
* <p>To add a certificate chain, use {@link #addTrusted(List)} instead.</p>
*
* @param cert the X.509 certificate to add.
* @param privkey matching private key to add.
* @throws CertificateExpiredException if the certificate is expired.
* @throws CertificateNotYetValidException if the certificate is not yet
* valid.
* @throws CertificateException if the certificate is not a CA certificate,
* the certificate is not self-signed and not trusted by an
* existing trusted certificate, or the certificate is not
* permitted as a subordinate certificate, or the certificate is
* malformed.
* @throws SignatureException if the certificate signature cannot be or
* fails to verify for any reason including a malformed certificate.
* @throws NoSuchAlgorithmException if the signature algorithm is
* unsupported.
* @throws InvalidKeyException if a certificate public key is invalid.
* @throws NoSuchProviderException if there is no X.509 certificate
* provider.
* @see #getPrivateKey(X509Certificate)
*/
public void addTrusted(final X509Certificate cert, final PrivateKey privkey) throws CertificateExpiredException, CertificateNotYetValidException, CertificateException, SignatureException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
// Add the certificate.
addTrusted(cert);
// Add the private key.
final X500Principal subjectName = cert.getSubjectX500Principal();
privateKeys.put(subjectName, privkey);
}
/**
* <p>Return true if the provided certificate is valid and accepted by a
* trusted certificate in this store.</p>
*
* @param cert the certificate.
* @return true if the certificate is accepted.
* @throws CertificateExpiredException if the certificate is expired.
* @throws CertificateNotYetValidException if the certificate is not yet
* valid.
*/
public boolean isAccepted(final X509Certificate cert) throws CertificateExpiredException, CertificateNotYetValidException {
cert.checkValidity();
return isVerified(cert);
}
/**
* <p>Return the private key associated with the provided certificate.</p>
*
* @param cert the certificate.
* @return the private key or null if not found.
* @see #addTrusted(X509Certificate, PrivateKey)
*/
public PrivateKey getPrivateKey(final X509Certificate cert) {
final X500Principal subjectName = cert.getSubjectX500Principal();
return privateKeys.get(subjectName);
}
/** Map of certificate subject names onto X.509 certificates. */
private final Map</*SubjectName*/X500Principal, List<X509Certificate>> store = new HashMap<X500Principal, List<X509Certificate>>();
/** Map of certificate subject names onto private keys. */
private final Map</*SubjectName*/X500Principal, PrivateKey> privateKeys = new HashMap<X500Principal, PrivateKey>();
}
| 1,762 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/UnauthenticatedAuthenticationData.java
|
/**
* Copyright (c) 2012-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.entityauth;
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;
/**
* <p>Unauthenticated entity authentication data. This form of authentication
* is used by entities that cannot provide any form of entity
* authentication.</p>
*
* <p>Unauthenticated entity authentication data is represented as
* {@code
* unauthenticatedauthdata = {
* "#mandatory" : [ "identity" ],
* "identity" : "string"
* }} where:
* <ul>
* <li>{@code identity} is the entity identity</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class UnauthenticatedAuthenticationData extends EntityAuthenticationData {
/** Key entity identity. */
private static final String KEY_IDENTITY = "identity";
/**
* Construct a new unauthenticated entity authentication data instance from
* the specified entity identity.
*
* @param identity the entity identity.
*/
public UnauthenticatedAuthenticationData(final String identity) {
super(EntityAuthenticationScheme.NONE);
this.identity = identity;
}
/**
* Construct a new unauthenticated entity authentication data instance from
* the provided MSL object.
*
* @param unauthenticatedAuthMo the authentication data MSL object.
* @throws MslEncodingException if there is an error parsing the MSL data.
*/
UnauthenticatedAuthenticationData(final MslObject unauthenticatedAuthMo) throws MslEncodingException {
super(EntityAuthenticationScheme.NONE);
try {
identity = unauthenticatedAuthMo.getString(KEY_IDENTITY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "unauthenticated authdata " + unauthenticatedAuthMo, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#getIdentity()
*/
@Override
public String getIdentity() {
return identity;
}
/* (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) {
final MslObject mo = encoder.createObject();
mo.put(KEY_IDENTITY, identity);
return mo;
}
/** Entity identity. */
private final String identity;
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof UnauthenticatedAuthenticationData)) return false;
final UnauthenticatedAuthenticationData that = (UnauthenticatedAuthenticationData)obj;
return super.equals(obj) && this.identity.equals(that.identity);
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ identity.hashCode();
}
}
| 1,763 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/ProvisionedAuthenticationData.java
|
/**
* Copyright (c) 2016-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.entityauth;
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>Provisioned entity authentication data. This form of authentication is
* used by entities that cannot provide any form of entity authentication and
* also want to delegate the generation or assignment of their identity to the
* remote entity.</p>
*
* <p>Provisioned entity authentication data is represented as
* {@code
* provisionedauthdata = {
* }}</p>
*
* <p>Until the entity identity has been provisioned, the entity identity will
* be equal to the empty string.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class ProvisionedAuthenticationData extends EntityAuthenticationData {
/**
* Construct a new provisioned entity authentication data instance.
*/
public ProvisionedAuthenticationData() {
super(EntityAuthenticationScheme.PROVISIONED);
}
/**
* Construct a new provisioned entity authentication data instance from the
* provided JSON object.
*
* @param provisionedAuthMo the authentication data JSON object.
*/
public ProvisionedAuthenticationData(final MslObject provisionedAuthMo) {
super(EntityAuthenticationScheme.PROVISIONED);
}
/**
* <p>Sets the entity identity.</p>
*
* @param identity the entity identity.
*/
void setIdentity(final String identity) {
this.identity = identity;
}
/**
* <p>Return the entity identity. Prior to provisioning, this function will
* return the empty string. After an identity has been provisioned, this
* function will return the provisioned identity.</p>
*
* @see #setIdentity(String)
*/
@Override
public String getIdentity() {
return identity;
}
@Override
public MslObject getAuthData(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
return encoder.createObject();
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof ProvisionedAuthenticationData)) return false;
return super.equals(obj);
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode();
}
/** Entity identity. */
private String identity = "";
}
| 1,764 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/UnauthenticatedAuthenticationFactory.java
|
/**
* Copyright (c) 2012-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.entityauth;
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.crypto.NullCryptoContext;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>Unauthenticated entity authentication factory.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class UnauthenticatedAuthenticationFactory extends EntityAuthenticationFactory {
/**
* Construct a new unauthenticated authentication factory instance.
*
* @param authutils authentication utilities.
*/
public UnauthenticatedAuthenticationFactory(final AuthenticationUtils authutils) {
super(EntityAuthenticationScheme.NONE);
this.authutils = authutils;
}
/* (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 {
return new UnauthenticatedAuthenticationData(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 UnauthenticatedAuthenticationData))
throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + ".");
final UnauthenticatedAuthenticationData uad = (UnauthenticatedAuthenticationData)authdata;
// Check for revocation.
final String identity = uad.getIdentity();
if (authutils.isEntityRevoked(identity))
throw new MslEntityAuthException(MslError.ENTITY_REVOKED, "none " + identity).setEntityAuthenticationData(uad);
// Verify the scheme is permitted.
if (!authutils.isSchemePermitted(identity, getScheme()))
throw new MslEntityAuthException(MslError.INCORRECT_ENTITYAUTH_DATA, "Authentication Scheme for Device Type Not Supported " + identity + ":" + getScheme()).setEntityAuthenticationData(uad);
// Return the crypto context.
return new NullCryptoContext();
}
/** Authentication utilities. */
final AuthenticationUtils authutils;
}
| 1,765 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/ProvisionedAuthenticationFactory.java
|
/**
* Copyright (c) 2016-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.entityauth;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.NullCryptoContext;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.MslContext;
/**
* <p>Provisioned entity authentication factory.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class ProvisionedAuthenticationFactory extends EntityAuthenticationFactory {
/**
* An identity provisioning service returns unique entity identities.
*/
public interface IdentityProvisioningService {
/**
* @return the next unique entity identity.
*/
public String nextIdentity();
}
/**
* Construct a new provisioned authentication factory instance.
*
* @param service the identity provisioning service to use.
*/
public ProvisionedAuthenticationFactory(final IdentityProvisioningService service) {
super(EntityAuthenticationScheme.PROVISIONED);
this.service = service;
}
/* (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) {
return new ProvisionedAuthenticationData(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 MslCryptoException, MslEntityAuthException {
// Make sure we have the right kind of entity authentication data.
if (!(authdata instanceof ProvisionedAuthenticationData))
throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + ".");
final ProvisionedAuthenticationData pad = (ProvisionedAuthenticationData)authdata;
// Provision an entity identity.
final String identity = service.nextIdentity();
pad.setIdentity(identity);
// Return the crypto context.
return new NullCryptoContext();
}
/** Identity provisioning service. */
final IdentityProvisioningService service;
}
| 1,766 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/RsaAuthenticationData.java
|
/**
* Copyright (c) 2012-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.entityauth;
import com.netflix.msl.MslCryptoException;
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;
/**
* <p>RSA asymmetric keys entity authentication data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "identity", "pubkeyid" ],
* "identity" : "string",
* "pubkeyid" : "string"
* }} where:
* <ul>
* <li>{@code identity} is the entity identity</li>
* <li>{@code pubkeyid} is the identity of the RSA public key associated with this identity</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class RsaAuthenticationData extends EntityAuthenticationData {
/** Key entity identity. */
private static final String KEY_IDENTITY = "identity";
/** Key public key ID. */
private static final String KEY_PUBKEY_ID = "pubkeyid";
/**
* Construct a new public key authentication data instance from the
* specified entity identity and public key ID.
*
* @param identity the entity identity.
* @param pubkeyid the public key ID.
*/
public RsaAuthenticationData(final String identity, final String pubkeyid) {
super(EntityAuthenticationScheme.RSA);
this.identity = identity;
this.pubkeyid = pubkeyid;
}
/**
* Construct a new RSA asymmetric keys authentication data instance from
* the provided MSL object.
*
* @param rsaAuthMo the authentication data MSL object.
* @throws MslEncodingException if there is an error parsing the MSL data.
*/
public RsaAuthenticationData(final MslObject rsaAuthMo) throws MslCryptoException, MslEncodingException {
super(EntityAuthenticationScheme.RSA);
try {
// Extract RSA authentication data.
identity = rsaAuthMo.getString(KEY_IDENTITY);
pubkeyid = rsaAuthMo.getString(KEY_PUBKEY_ID);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "RSA authdata " + rsaAuthMo, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#getIdentity()
*/
@Override
public String getIdentity() {
return identity;
}
/**
* @return the public key ID.
*/
public String getPublicKeyId() {
return pubkeyid;
}
/* (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) {
final MslObject mo = encoder.createObject();
mo.put(KEY_IDENTITY, identity);
mo.put(KEY_PUBKEY_ID, pubkeyid);
return mo;
}
/** Entity identity. */
private final String identity;
/** Public key ID. */
private final String pubkeyid;
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof RsaAuthenticationData)) return false;
final RsaAuthenticationData that = (RsaAuthenticationData)obj;
return super.equals(obj) && this.identity.equals(that.identity) && this.pubkeyid.equals(that.pubkeyid);
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ (identity + "|" + pubkeyid).hashCode();
}
}
| 1,767 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/EntityAuthenticationData.java
|
/**
* Copyright (c) 2012-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.entityauth;
import java.util.HashMap;
import java.util.Map;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.io.MslEncodable;
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.util.MslContext;
/**
* <p>The entity authentication data provides proof of entity identity.</p>
*
* <p>Specific entity authentication mechanisms should define their own entity
* authentication data types.</p>
*
* <p>Entity authentication data is represented as
* {@code
* entityauthdata = {
* "#mandatory" : [ "scheme", "authdata" ],
* "scheme" : "string",
* "authdata" : object
* }} where:
* <ul>
* <li>{@code scheme} is the entity authentication scheme</li>
* <li>{@code authdata} is the scheme-specific entity authentication data</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class EntityAuthenticationData implements MslEncodable {
/** Key entity authentication scheme. */
private static final String KEY_SCHEME = "scheme";
/** Key entity authentication data. */
private static final String KEY_AUTHDATA = "authdata";
/**
* Create a new entity authentication data object with the specified entity
* authentication scheme.
*
* @param scheme the entity authentication scheme.
*/
protected EntityAuthenticationData(final EntityAuthenticationScheme scheme) {
this.scheme = scheme;
}
/**
* Construct a new entity authentication data instance of the correct type
* from the provided MSL object.
*
* @param ctx MSL context.
* @param entityAuthMo the MSL object.
* @return the entity authentication data concrete instance.
* @throws MslEntityAuthException if unable to create the entity
* authentication data.
* @throws MslEncodingException if there is an error parsing the entity
* authentication data.
* @throws MslCryptoException if there is an error creating the entity
* authentication data crypto.
*/
public static EntityAuthenticationData create(final MslContext ctx, final MslObject entityAuthMo) throws MslEntityAuthException, MslEncodingException, MslCryptoException {
try {
// Identify the concrete subclass from the authentication scheme.
final String schemeName = entityAuthMo.getString(KEY_SCHEME);
final EntityAuthenticationScheme scheme = ctx.getEntityAuthenticationScheme(schemeName);
if (scheme == null)
throw new MslEntityAuthException(MslError.UNIDENTIFIED_ENTITYAUTH_SCHEME, schemeName);
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject authdata = entityAuthMo.getMslObject(KEY_AUTHDATA, encoder);
// Construct an instance of the concrete subclass.
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(scheme);
if (factory == null)
throw new MslEntityAuthException(MslError.ENTITYAUTH_FACTORY_NOT_FOUND, scheme.name());
return factory.createData(ctx, authdata);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "entityauthdata " + entityAuthMo, e);
}
}
/**
* @return the entity authentication scheme.
*/
public EntityAuthenticationScheme getScheme() {
return scheme;
}
/**
* @return the entity identity. May be {@code null} if unknown.
* @throws MslCryptoException if there is a crypto error accessing the
* entity identity.
*/
public abstract String getIdentity() throws MslCryptoException;
/**
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the authentication data MSL representation.
* @throws MslEncoderException if there was an error constructing the
* MSL object.
*/
public abstract MslObject getAuthData(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException;
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public final byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
// Return any cached encoding.
if (encodings.containsKey(format))
return encodings.get(format);
// Encode the entity authentication data.
final MslObject mo = encoder.createObject();
mo.put(KEY_SCHEME, scheme.name());
mo.put(KEY_AUTHDATA, getAuthData(encoder, format));
final byte[] encoding = encoder.encodeObject(mo, format);
// Cache and return the encoding.
encodings.put(format, encoding);
return encoding;
}
/* (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 EntityAuthenticationData)) return false;
final EntityAuthenticationData that = (EntityAuthenticationData)obj;
return this.scheme.equals(that.scheme);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return scheme.hashCode();
}
/** Entity authentication scheme. */
private final EntityAuthenticationScheme scheme;
/** Cached encodings. */
private final Map<MslEncoderFormat,byte[]> encodings = new HashMap<MslEncoderFormat,byte[]>();
}
| 1,768 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/EccStore.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.entityauth;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Set;
/**
* An ECC public key store contains trusted ECC public and private keys.
*/
public interface EccStore {
/**
* @return the known key pair identities.
*/
public Set<String> getIdentities();
/**
* Return the public key of the identified ECC key pair.
*
* @param identity ECC key pair identity.
* @return the public key of the identified key pair or null if not found.
*/
public PublicKey getPublicKey(final String identity);
/**
* Return the private key of the identified ECC key pair.
*
* @param identity ECC key pair identity.
* @return the private key of the identified key pair or null if not found.
*/
public PrivateKey getPrivateKey(final String identity);
}
| 1,769 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/EccAuthenticationData.java
|
/**
* Copyright (c) 2016-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.entityauth;
import com.netflix.msl.MslCryptoException;
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;
/**
* <p>ECC asymmetric keys entity authentication data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "identity", "pubkeyid" ],
* "identity" : "string",
* "pubkeyid" : "string"
* }} where:
* <ul>
* <li>{@code identity} is the entity identity</li>
* <li>{@code pubkeyid} is the identity of the ECC public key associated with this identity</li>
* </ul></p>
*/
public class EccAuthenticationData extends EntityAuthenticationData {
/** Key entity identity. */
private static final String KEY_IDENTITY = "identity";
/** Key public key ID. */
private static final String KEY_PUBKEY_ID = "pubkeyid";
/**
* Construct a new public key authentication data instance from the
* specified entity identity and public key ID.
*
* @param identity the entity identity.
* @param pubkeyid the public key ID.
*/
public EccAuthenticationData(final String identity, final String pubkeyid) {
super(EntityAuthenticationScheme.ECC);
this.identity = identity;
this.pubkeyid = pubkeyid;
}
/**
* Construct a new ECC asymmetric keys authentication data instance from
* the provided MSL object.
*
* @param eccAuthMo the authentication data MSL object.
* @throws MslEncodingException if there is an error parsing the data.
*/
EccAuthenticationData(final MslObject eccAuthMo) throws MslCryptoException, MslEncodingException {
super(EntityAuthenticationScheme.ECC);
try {
// Extract ECC authentication data.
identity = eccAuthMo.getString(KEY_IDENTITY);
pubkeyid = eccAuthMo.getString(KEY_PUBKEY_ID);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "ECC authdata " + eccAuthMo, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#getIdentity()
*/
@Override
public String getIdentity() {
return identity;
}
/**
* @return the public key ID.
*/
public String getPublicKeyId() {
return pubkeyid;
}
/* (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_IDENTITY, identity);
mo.put(KEY_PUBKEY_ID, pubkeyid);
return mo;
}
/** Entity identity. */
private final String identity;
/** Public key ID. */
private final String pubkeyid;
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof EccAuthenticationData)) return false;
final EccAuthenticationData that = (EccAuthenticationData)obj;
return super.equals(obj) && this.identity.equals(that.identity) && this.pubkeyid.equals(that.pubkeyid);
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ (identity + "|" + pubkeyid).hashCode();
}
}
| 1,770 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/PresharedAuthenticationFactory.java
|
/**
* Copyright (c) 2012-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.entityauth;
import com.netflix.msl.MslCryptoException;
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.crypto.SymmetricCryptoContext;
import com.netflix.msl.entityauth.KeySetStore.KeySet;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* Preshared keys entity authentication factory.
*
* @author Wesley Miaw <[email protected]>
*/
public class PresharedAuthenticationFactory extends EntityAuthenticationFactory {
/**
* Construct a new preshared keys authentication factory instance.
*
* @param store preshared key store.
* @param authutils authentication utilities.
*/
public PresharedAuthenticationFactory(final KeySetStore store, final AuthenticationUtils authutils) {
super(EntityAuthenticationScheme.PSK);
this.store = store;
this.authutils = authutils;
}
/* (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 {
return new PresharedAuthenticationData(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 MslCryptoException, 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;
// Check for revocation.
final String identity = pad.getIdentity();
if (authutils.isEntityRevoked(identity))
throw new MslEntityAuthException(MslError.ENTITY_REVOKED, "psk " + identity).setEntityAuthenticationData(pad);
// Verify the scheme is permitted.
if (!authutils.isSchemePermitted(identity, getScheme()))
throw new MslEntityAuthException(MslError.INCORRECT_ENTITYAUTH_DATA, "Authentication Scheme for Device Type Not Supported " + identity + ":" + getScheme()).setEntityAuthenticationData(pad);
// Load key set.
final KeySet keys = store.getKeys(identity);
if (keys == null)
throw new MslEntityAuthException(MslError.ENTITY_NOT_FOUND, "psk " + identity).setEntityAuthenticationData(pad);
// Return the crypto context.
return new SymmetricCryptoContext(ctx, identity, keys.encryptionKey, keys.hmacKey, keys.wrappingKey);
}
/** Preshared keys store. */
private final KeySetStore store;
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 1,771 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/PresharedProfileAuthenticationFactory.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.entityauth;
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.crypto.SymmetricCryptoContext;
import com.netflix.msl.entityauth.KeySetStore.KeySet;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>Preshared keys profile entity authentication factory.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class PresharedProfileAuthenticationFactory extends EntityAuthenticationFactory {
/**
* Construct a new preshared keys profile authentication factory instance.
*
* @param store preshared key store.
* @param authutils authentication utilities.
*/
public PresharedProfileAuthenticationFactory(final KeySetStore store, final AuthenticationUtils authutils) {
super(EntityAuthenticationScheme.PSK_PROFILE);
this.store = store;
this.authutils = authutils;
}
/* (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 {
return new PresharedProfileAuthenticationData(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 PresharedProfileAuthenticationData))
throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + ".");
final PresharedProfileAuthenticationData ppad = (PresharedProfileAuthenticationData)authdata;
// Check for revocation.
final String pskId = ppad.getPresharedKeysId();
if (authutils.isEntityRevoked(pskId))
throw new MslEntityAuthException(MslError.ENTITY_REVOKED, "psk profile " + pskId).setEntityAuthenticationData(ppad);
// Verify the scheme is permitted.
if (!authutils.isSchemePermitted(pskId, getScheme()))
throw new MslEntityAuthException(MslError.INCORRECT_ENTITYAUTH_DATA, "Authentication Scheme for Device Type Not Supported " + pskId + ":" + getScheme()).setEntityAuthenticationData(ppad);
// Load key set.
final KeySet keys = store.getKeys(pskId);
if (keys == null)
throw new MslEntityAuthException(MslError.ENTITY_NOT_FOUND, "psk profile " + pskId).setEntityAuthenticationData(ppad);
// Return the crypto context.
final String identity = ppad.getIdentity();
return new SymmetricCryptoContext(ctx, identity, keys.encryptionKey, keys.hmacKey, keys.wrappingKey);
}
/** Preshared keys store. */
private final KeySetStore store;
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 1,772 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/PresharedAuthenticationData.java
|
/**
* Copyright (c) 2012-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.entityauth;
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;
/**
* <p>Preshared keys entity authentication data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "identity" ],
* "identity" : "string"
* }} where:
* <ul>
* <li>{@code identity} is the entity identity</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class PresharedAuthenticationData extends EntityAuthenticationData {
/** Key entity identity. */
private static final String KEY_IDENTITY = "identity";
/**
* Construct a new preshared keys authentication data instance from the
* specified entity identity.
*
* @param identity the entity identity.
*/
public PresharedAuthenticationData(final String identity) {
super(EntityAuthenticationScheme.PSK);
this.identity = identity;
}
/**
* Construct a new preshared keys authentication data instance from the
* provided MSL object.
*
* @param presharedAuthMo the authentication data MSL object.
* @throws MslEncodingException if there is an error parsing the entity
* authentication data.
*/
PresharedAuthenticationData(final MslObject presharedAuthMo) throws MslEncodingException {
super(EntityAuthenticationScheme.PSK);
try {
identity = presharedAuthMo.getString(KEY_IDENTITY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "psk authdata " + presharedAuthMo, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#getIdentity()
*/
@Override
public String getIdentity() {
return identity;
}
/* (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) {
final MslObject mo = encoder.createObject();
mo.put(KEY_IDENTITY, identity);
return mo;
}
/** Entity identity. */
private final String identity;
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof PresharedAuthenticationData)) return false;
final PresharedAuthenticationData that = (PresharedAuthenticationData)obj;
return super.equals(obj) && this.identity.equals(that.identity);
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ identity.hashCode();
}
}
| 1,773 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/X509AuthenticationData.java
|
/**
* Copyright (c) 2012-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.entityauth;
import java.io.ByteArrayInputStream;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
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.util.Base64;
/**
* <p>X.509 asymmetric keys entity authentication data.</p>
*
* <p>The X.509 certificate should be used to enumerate any entity
* properties. The certificate subject canonical name is considered the device
* identity. X.509 authentication data is considered equal based on the device
* identity.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "x509certificate" ],
* "x509certificate" : "string"
* }} where:
* <ul>
* <li>{@code x509certificate} is the Base64-encoded X.509 certificate</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class X509AuthenticationData extends EntityAuthenticationData {
/** Key entity X.509 certificate. */
private static final String KEY_X509_CERT = "x509certificate";
/**
* Construct a new X.509 asymmetric keys authentication data instance from
* the provided X.509 certificate.
*
* @param x509cert entity X.509 certificate.
* @throws MslCryptoException if the X.509 certificate data cannot be
* parsed.
*/
public X509AuthenticationData(final X509Certificate x509cert) throws MslCryptoException {
super(EntityAuthenticationScheme.X509);
this.x509cert = x509cert;
this.identity = x509cert.getSubjectX500Principal().getName();
}
/**
* Construct a new X.509 asymmetric keys authentication data instance from
* the provided MSL object.
*
* @param x509AuthMo the authentication data MSL object.
* @throws MslCryptoException if the X.509 certificate data cannot be
* parsed.
* @throws MslEncodingException if the X.509 certificate cannot be found.
*/
public X509AuthenticationData(final MslObject x509AuthMo) throws MslCryptoException, MslEncodingException {
super(EntityAuthenticationScheme.X509);
// Extract X.509 certificate representation.
final String x509;
try {
x509 = x509AuthMo.getString(KEY_X509_CERT);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "X.509 authdata " + x509AuthMo, e);
}
// Get the X.509 certificate factory.
final CertificateFactory factory;
try {
factory = CertificateFactory.getInstance("X.509");
} catch (final CertificateException e) {
throw new MslInternalException("No certificate X.509 certificate factory.", e);
}
// Create X.509 cert.
final byte[] x509bytes;
try {
x509bytes = Base64.decode(x509);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.X509CERT_INVALID, x509, e);
}
try {
final ByteArrayInputStream bais = new ByteArrayInputStream(x509bytes);
x509cert = (X509Certificate)factory.generateCertificate(bais);
identity = x509cert.getSubjectX500Principal().getName();
} catch (final CertificateException e) {
throw new MslCryptoException(MslError.X509CERT_PARSE_ERROR, Base64.encode(x509bytes), e);
}
}
/**
* @return the X.509 certificate.
*/
public X509Certificate getX509Cert() {
return x509cert;
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#getIdentity()
*/
@Override
public String getIdentity() {
return identity;
}
@Override
public MslObject getAuthData(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
try {
mo.put(KEY_X509_CERT, Base64.encode(x509cert.getEncoded()));
} catch (final CertificateEncodingException | IllegalArgumentException e) {
throw new MslEncoderException("Error encoding X.509 authdata", e);
}
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof X509AuthenticationData)) return false;
final X509AuthenticationData that = (X509AuthenticationData)obj;
return super.equals(obj) && this.identity.equals(that.identity);
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ identity.hashCode();
}
/** Entity X.509 certificate. */
private final X509Certificate x509cert;
/** Entity identity. */
private final String identity;
}
| 1,774 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/KeySetStore.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.entityauth;
import javax.crypto.SecretKey;
/**
* A key set store contains trusted key sets.
*
* @author Wesley Miaw <[email protected]>
*/
public interface KeySetStore {
/**
* A set of encryption, HMAC, and wrapping keys.
*/
public static class KeySet {
/**
* Create a new key set with the given keys.
*
* @param encryptionKey the encryption key.
* @param hmacKey the HMAC key.
* @param wrappingKey the wrapping key.
*/
public KeySet(final SecretKey encryptionKey, final SecretKey hmacKey, final SecretKey wrappingKey) {
this.encryptionKey = encryptionKey;
this.hmacKey = hmacKey;
this.wrappingKey = wrappingKey;
}
/** Encryption key. */
public final SecretKey encryptionKey;
/** HMAC key. */
public final SecretKey hmacKey;
/** Wrapping key. */
public final SecretKey wrappingKey;
}
/**
* Return the encryption, HMAC, and wrapping keys for the given identity.
*
* @param identity key set identity.
* @return the keys set associated with the identity or null if not found.
*/
public KeySet getKeys(final String identity);
}
| 1,775 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/RsaStore.java
|
/**
* Copyright (c) 2012-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.entityauth;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Set;
/**
* An RSA public key store contains trusted RSA public and private keys.
*
* @author Wesley Miaw <[email protected]>
*/
public interface RsaStore {
/**
* @return the known key pair identities.
*/
public Set<String> getIdentities();
/**
* Return the public key of the identified RSA key pair.
*
* @param identity RSA key pair identity.
* @return the public key of the identified key pair or null if not found.
*/
public PublicKey getPublicKey(final String identity);
/**
* Return the private key of the identified RSA key pair.
*
* @param identity RSA key pair identity.
* @return the private key of the identified key pair or null if not found.
*/
public PrivateKey getPrivateKey(final String identity);
}
| 1,776 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/EntityAuthenticationFactory.java
|
/**
* Copyright (c) 2012-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.entityauth;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.MslContext;
/**
* A entity authentication factory creates authentication data instances and
* authenticators for a specific entity authentication scheme.
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class EntityAuthenticationFactory {
/**
* Create a new entity authentication factory for the specified scheme.
*
* @param scheme the entity authentication scheme.
*/
protected EntityAuthenticationFactory(final EntityAuthenticationScheme scheme) {
this.scheme = scheme;
}
/**
* @return the entity authentication scheme this factory is for.
*/
public EntityAuthenticationScheme getScheme() {
return scheme;
}
/**
* Construct a new entity authentication data instance from the provided
* MSL object.
*
* @param ctx MSL context.
* @param entityAuthMo the MSL object.
* @return the entity authentication data.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException if there is an error with the entity
* authentication data cryptography.
* @throws MslEntityAuthException if there is an error creating the entity
* authentication data.
*/
public abstract EntityAuthenticationData createData(final MslContext ctx, final MslObject entityAuthMo) throws MslEncodingException, MslCryptoException, MslEntityAuthException;
/**
* Create a crypto context that can be used to encrypt/decrypt and
* authenticate data from the entity. The implementation of this function
* must, by necessity, authenticate the entity authentication data.
*
* @param ctx MSL context.
* @param authdata the authentication data.
* @return the entity crypto context.
* @throws MslCryptoException if there is an error instantiating the crypto
* context.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
*/
public abstract ICryptoContext getCryptoContext(final MslContext ctx, final EntityAuthenticationData authdata) throws MslCryptoException, MslEntityAuthException;
/** The factory's entity authentication scheme. */
private final EntityAuthenticationScheme scheme;
}
| 1,777 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/EccAuthenticationFactory.java
|
/**
* Copyright (c) 2016-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.entityauth;
import java.security.PrivateKey;
import java.security.PublicKey;
import com.netflix.msl.MslCryptoException;
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.EccCryptoContext;
import com.netflix.msl.crypto.EccCryptoContext.Mode;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>ECC asymmetric keys entity authentication factory.</p>
*/
public class EccAuthenticationFactory extends EntityAuthenticationFactory {
/**
* <p>Construct a new ECC asymmetric keys authentication factory
* instance.</p>
*
* @param store ECC key store.
* @param authutils authentication utilities.
*/
public EccAuthenticationFactory(final EccStore store, final AuthenticationUtils authutils) {
this(null, store, authutils);
}
/**
* <p>Construct a new ECC asymmetric keys authentication factory instance
* with the specified key pair ID for the local entity. The ECC key store
* must contain a private key for the local entity (a public key is
* optional).</p>
*
* @param keyPairId local entity key pair ID.
* @param store ECC key store.
* @param authutils authentication utilities.
*/
public EccAuthenticationFactory(final String keyPairId, final EccStore store, final AuthenticationUtils authutils) {
super(EntityAuthenticationScheme.ECC);
this.keyPairId = keyPairId;
this.store = store;
this.authutils = authutils;
}
/* (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, MslCryptoException {
return new EccAuthenticationData(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 EccAuthenticationData))
throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + ".");
final EccAuthenticationData ead = (EccAuthenticationData)authdata;
// Check for revocation.
final String identity = ead.getIdentity();
if (authutils.isEntityRevoked(identity))
throw new MslEntityAuthException(MslError.ENTITY_REVOKED, "ecc" + identity).setEntityAuthenticationData(ead);
// Verify the scheme is permitted.
if (!authutils.isSchemePermitted(identity, getScheme()))
throw new MslEntityAuthException(MslError.INCORRECT_ENTITYAUTH_DATA, "Authentication Scheme for Device Type Not Supported " + identity + ":" + getScheme()).setEntityAuthenticationData(ead);
// Extract ECC authentication data.
final String pubkeyid = ead.getPublicKeyId();
final PublicKey publicKey = store.getPublicKey(pubkeyid);
final PrivateKey privateKey = store.getPrivateKey(pubkeyid);
// The local entity must have a private key.
if (pubkeyid.equals(keyPairId) && privateKey == null)
throw new MslEntityAuthException(MslError.ECC_PRIVATEKEY_NOT_FOUND, pubkeyid).setEntityAuthenticationData(ead);
// Remote entities must have a public key.
else if (!pubkeyid.equals(keyPairId) && publicKey == null)
throw new MslEntityAuthException(MslError.ECC_PUBLICKEY_NOT_FOUND, pubkeyid).setEntityAuthenticationData(ead);
// Return the crypto context.
return new EccCryptoContext(identity, privateKey, publicKey, Mode.SIGN_VERIFY);
}
/** Local entity key pair ID. */
private final String keyPairId;
/** ECC key store. */
private final EccStore store;
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 1,778 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/MasterTokenProtectedAuthenticationData.java
|
/**
* Copyright (c) 2015-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.entityauth;
import java.util.HashMap;
import java.util.Map;
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.MslMasterTokenException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.SessionCryptoContext;
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.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* <p>Master token protected entity authentication data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "mastertoken", "authdata", "signature" ],
* "mastertoken" : mastertoken,
* "authdata" : "binary",
* "signature" : "binary",
* }} where:
* <ul>
* <li>{@code mastertoken} is the master token used to protect the encapsulated authentication data</li>
* <li>{@code authdata} is the ciphertext envelope containing the encapsulated authentication data</li>
* <li>{@code signature} is the signature envelope verifying the encapsulated authentication data</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MasterTokenProtectedAuthenticationData extends EntityAuthenticationData {
/** Key master token. */
protected static final String KEY_MASTER_TOKEN = "mastertoken";
/** Key authentication data. */
protected static final String KEY_AUTHENTICATION_DATA = "authdata";
/** Key signature. */
protected static final String KEY_SIGNATURE = "signature";
/**
* <p>Construct a new master token protected entity authentication data
* instance using the provided master token and actual entity
* authentication data.</p>
*
* @param ctx MSL context.
* @param masterToken the master token.
* @param authdata encapsulated authentication data.
* @throws MslCryptoException if there is an error encrypting or signing
* the encapsulated authentication data.
* @throws MslEntityAuthException if the master token crypto context cannot
* be found in the MSL store and cannot be created.
*/
public MasterTokenProtectedAuthenticationData(final MslContext ctx, final MasterToken masterToken, final EntityAuthenticationData authdata) throws MslCryptoException, MslEntityAuthException {
super(EntityAuthenticationScheme.MT_PROTECTED);
this.ctx = ctx;
this.masterToken = masterToken;
this.authdata = authdata;
}
/**
* <p>Construct a new master token protected entity authentication data
* instance from the provided MSL object.</p>
*
* @param ctx MSL context.
* @param authdataMo the authentication data MSL object.
* @throws MslEncodingException if there is an error parsing the MSL
* representation.
* @throws MslCryptoException if there is an error decrypting or verifying
* the encapsulated authentication data.
* @throws MslEntityAuthException if the encapsulated authentication data
* or signature are invalid, if the master token is invalid, or if
* the master token crypto context cannot be found in the MSL store
* and cannot be created.
*/
MasterTokenProtectedAuthenticationData(final MslContext ctx, final MslObject authdataMo) throws MslEncodingException, MslCryptoException, MslEntityAuthException {
super(EntityAuthenticationScheme.MT_PROTECTED);
this.ctx = ctx;
// Extract authentication data fields.
final byte[] ciphertext, signature;
try {
ciphertext = authdataMo.getBytes(KEY_AUTHENTICATION_DATA);
signature = authdataMo.getBytes(KEY_SIGNATURE);
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
try {
this.masterToken = new MasterToken(ctx, authdataMo.getMslObject(KEY_MASTER_TOKEN, encoder));
} catch (final MslException e) {
throw new MslEntityAuthException(MslError.ENTITYAUTH_MASTERTOKEN_INVALID, "master token protected authdata " + authdataMo, e);
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "master token protected authdata " + authdataMo, e);
}
// Grab master token crypto context.
final ICryptoContext cryptoContext;
try {
final ICryptoContext cachedCryptoContext = ctx.getMslStore().getCryptoContext(masterToken);
if (cachedCryptoContext != null)
cryptoContext = cachedCryptoContext;
else
cryptoContext = new SessionCryptoContext(ctx, masterToken);
} catch (final MslMasterTokenException e) {
throw new MslEntityAuthException(MslError.ENTITYAUTH_MASTERTOKEN_NOT_DECRYPTED, e);
}
// Verify and decrypt the authentication data.
try {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
if (!cryptoContext.verify(ciphertext, signature, encoder))
throw new MslEntityAuthException(MslError.ENTITYAUTH_VERIFICATION_FAILED, "master token protected authdata " + authdataMo);
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
final MslObject internalAuthdataMo = encoder.parseObject(plaintext);
this.authdata = EntityAuthenticationData.create(ctx, internalAuthdataMo);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "master token protected authdata " + authdataMo, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#getIdentity()
*/
@Override
public String getIdentity() throws MslCryptoException {
return authdata.getIdentity();
}
/**
* Return the encapsulated entity authentication data.
*
* @return the encapsulated entity authentication data.
*/
public EntityAuthenticationData getEncapsulatedAuthdata() {
return authdata;
}
/* (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 {
// Return any cached object.
if (objects.containsKey(format))
return objects.get(format);
// Grab master token crypto context.
final ICryptoContext cryptoContext;
try {
final ICryptoContext cachedCryptoContext = ctx.getMslStore().getCryptoContext(masterToken);
if (cachedCryptoContext != null)
cryptoContext = cachedCryptoContext;
else
cryptoContext = new SessionCryptoContext(ctx, masterToken);
} catch (final MslMasterTokenException e) {
throw new MslEncoderException("Master token is not trusted; cannot create session crypto context.", e);
}
// Encrypt and sign the authentication data.
final byte[] plaintext = authdata.toMslEncoding(encoder, format);
final byte[] ciphertext, signature;
try {
ciphertext = cryptoContext.encrypt(plaintext, encoder, format);
signature = cryptoContext.sign(ciphertext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error encrypting and signing the authentication data.", e);
}
// Return the authentication data.
final MslObject mo = encoder.createObject();
mo.put(KEY_MASTER_TOKEN, masterToken);
mo.put(KEY_AUTHENTICATION_DATA, ciphertext);
mo.put(KEY_SIGNATURE, signature);
// Cache and return the object.
final byte[] encoded = encoder.encodeObject(mo, format);
final MslObject decoded = encoder.parseObject(encoded);
objects.put(format, decoded);
return decoded;
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof MasterTokenProtectedAuthenticationData)) return false;
final MasterTokenProtectedAuthenticationData that = (MasterTokenProtectedAuthenticationData)obj;
return super.equals(obj) &&
this.masterToken.equals(that.masterToken) &&
this.authdata.equals(that.authdata);
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^
masterToken.hashCode() ^
authdata.hashCode();
}
/** MSL context. */
private final MslContext ctx;
/** Master token. */
private final MasterToken masterToken;
/** Entity authentication data. */
private final EntityAuthenticationData authdata;
/** Cached encoded objects. */
private final Map<MslEncoderFormat,MslObject> objects = new HashMap<MslEncoderFormat,MslObject>();
}
| 1,779 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/UnauthenticatedSuffixedAuthenticationData.java
|
/**
* Copyright (c) 2015-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.entityauth;
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;
/**
* <p>Unauthenticated suffixed entity authentication data. This form of
* authentication is used by entities that cannot provide any form of entity
* authentication, and wish to share a root identity across themselves. This
* scheme may also be useful in cases where multiple MSL stacks need to execute
* independently on a single entity.</p>
*
* <p>A suffixed scheme can expose an entity to cloning attacks of the root
* identity as the master token sequence number will now be tied to the
* root and suffix pair. This is probably acceptable for unauthenticated
* entities anyway as they have no credentials to provide as proof of their
* claimed identity.</p>
*
* <p>Unauthenticated suffixed entity authentication data is represented as
* {@code
* unauthenticatedauthdata = {
* "#mandatory" : [ "root", "suffix" ],
* "root" : "string",
* "suffix" : "string"
* }} where:
* <ul>
* <li>{@code root} is the entity identity root</li>
* <li>{@code suffix} is the entity identity suffix</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class UnauthenticatedSuffixedAuthenticationData extends EntityAuthenticationData {
/** Key entity root. */
private static final String KEY_ROOT = "root";
/** Key entity suffix. */
private static final String KEY_SUFFIX = "suffix";
/** Identity concatenation character. */
private static final String CONCAT_CHAR = ".";
/**
* Construct a new unauthenticated suffixed entity authentication data
* instance from the specified entity identity root and suffix.
*
* @param root the entity identity root.
* @param suffix the entity identity suffix.
*/
public UnauthenticatedSuffixedAuthenticationData(final String root, final String suffix) {
super(EntityAuthenticationScheme.NONE_SUFFIXED);
this.root = root;
this.suffix = suffix;
}
/**
* Construct a new unauthenticated suffixed entity authentication data
* instance from the provided MSL object.
*
* @param unauthSuffixedAuthMo the authentication data MSL object.
* @throws MslEncodingException if there is an error parsing the MSL data.
*/
public UnauthenticatedSuffixedAuthenticationData(final MslObject unauthSuffixedAuthMo) throws MslEncodingException {
super(EntityAuthenticationScheme.NONE_SUFFIXED);
try {
root = unauthSuffixedAuthMo.getString(KEY_ROOT);
suffix = unauthSuffixedAuthMo.getString(KEY_SUFFIX);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "unauthenticated suffixed authdata " + unauthSuffixedAuthMo, e);
}
}
/**
* <p>Returns the entity identity. This is equal to the root and suffix
* strings moined with a period, e.g. {@code root.suffix}.</p>
*
* @return the entity identity.
*/
@Override
public String getIdentity() {
return root + CONCAT_CHAR + suffix;
}
/**
* @return the entity identity root.
*/
public String getRoot() {
return root;
}
/**
* @return the entity identity suffix.
*/
public String getSuffix() {
return suffix;
}
/* (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) {
final MslObject mo = encoder.createObject();
mo.put(KEY_ROOT, root);
mo.put(KEY_SUFFIX, suffix);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof UnauthenticatedSuffixedAuthenticationData)) return false;
final UnauthenticatedSuffixedAuthenticationData that = (UnauthenticatedSuffixedAuthenticationData)obj;
return super.equals(obj) && this.root.equals(that.root) && this.suffix.equals(that.suffix);
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ root.hashCode() ^ suffix.hashCode();
}
/** Entity identity root. */
private final String root;
/** Entity identity suffix. */
private final String suffix;
}
| 1,780 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/UnauthenticatedSuffixedAuthenticationFactory.java
|
/**
* Copyright (c) 2015-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.entityauth;
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.crypto.NullCryptoContext;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>Unauthenticated suffixed entity authentication factory.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class UnauthenticatedSuffixedAuthenticationFactory extends EntityAuthenticationFactory {
/**
* Construct a new unauthenticated suffixed authentication factory instance.
*
* @param authutils authentication utilities.
*/
public UnauthenticatedSuffixedAuthenticationFactory(final AuthenticationUtils authutils) {
super(EntityAuthenticationScheme.NONE_SUFFIXED);
this.authutils = authutils;
}
/* (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 {
return new UnauthenticatedSuffixedAuthenticationData(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 UnauthenticatedSuffixedAuthenticationData))
throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + ".");
final UnauthenticatedSuffixedAuthenticationData usad = (UnauthenticatedSuffixedAuthenticationData)authdata;
// Check for revocation.
final String root = usad.getRoot();
if (authutils.isEntityRevoked(root))
throw new MslEntityAuthException(MslError.ENTITY_REVOKED, "none suffixed " + root).setEntityAuthenticationData(usad);
// Verify the scheme is permitted.
if (!authutils.isSchemePermitted(root, getScheme()))
throw new MslEntityAuthException(MslError.INCORRECT_ENTITYAUTH_DATA, "Authentication Scheme for Device Type Not Supported " + root + ":" + getScheme()).setEntityAuthenticationData(usad);
// Return the crypto context.
return new NullCryptoContext();
}
/** Authentication utilities. */
final AuthenticationUtils authutils;
}
| 1,781 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/MasterTokenProtectedAuthenticationFactory.java
|
/**
* Copyright (c) 2015-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.entityauth;
import com.netflix.msl.MslCryptoException;
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.io.MslObject;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>Master token protected entity authentication factory.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MasterTokenProtectedAuthenticationFactory extends EntityAuthenticationFactory {
/**
* <p>Construct a new master token protected entity authentication factory
* instance.</p>
*
* @param authutils authentication utilities.
*/
public MasterTokenProtectedAuthenticationFactory(final AuthenticationUtils authutils) {
super(EntityAuthenticationScheme.MT_PROTECTED);
this.authutils = authutils;
}
/* (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, MslCryptoException, MslEntityAuthException {
return new MasterTokenProtectedAuthenticationData(ctx, 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 MslCryptoException, MslEntityAuthException {
// Make sure we have the right kind of entity authentication data.
if (!(authdata instanceof MasterTokenProtectedAuthenticationData))
throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + ".");
final MasterTokenProtectedAuthenticationData mtpad = (MasterTokenProtectedAuthenticationData)authdata;
// Check for revocation.
final String identity = mtpad.getIdentity();
if (authutils.isEntityRevoked(identity))
throw new MslEntityAuthException(MslError.ENTITY_REVOKED, "none " + identity).setEntityAuthenticationData(mtpad);
// Verify the scheme is permitted.
if (!authutils.isSchemePermitted(identity, getScheme()))
throw new MslEntityAuthException(MslError.INCORRECT_ENTITYAUTH_DATA, "Authentication Scheme for Device Type Not Supported " + identity + ":" + getScheme()).setEntityAuthenticationData(mtpad);
// Authenticate using the encapsulated authentication data.
final EntityAuthenticationData ead = mtpad.getEncapsulatedAuthdata();
final EntityAuthenticationScheme scheme = ead.getScheme();
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(scheme);
if (factory == null)
throw new MslEntityAuthException(MslError.ENTITYAUTH_FACTORY_NOT_FOUND, scheme.name()).setEntityAuthenticationData(mtpad);
return factory.getCryptoContext(ctx, ead);
}
/** Authentication utilities. */
final AuthenticationUtils authutils;
}
| 1,782 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/PresharedProfileAuthenticationData.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.entityauth;
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;
/**
* <p>Preshared keys profile entity authentication data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "pskid", "profile" ],
* "pskid" : "string",
* "profile" : "string",
* }} where:
* <ul>
* <li>{@code pskid} is the entity preshared keys identity</li>
* <li>{@code profile} is the entity profile</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class PresharedProfileAuthenticationData extends EntityAuthenticationData {
/** Key entity preshared keys identity. */
private static final String KEY_PSKID = "pskid";
/** Key entity profile. */
private static final String KEY_PROFILE = "profile";
/** Identity concatenation character. */
private static final String CONCAT_CHAR = "-";
/**
* Construct a new preshared keys authentication data instance from the
* specified entity preshared keys identity and profile.
*
* @param pskid the entity preshared keys identity.
* @param profile the entity profile.
*/
public PresharedProfileAuthenticationData(final String pskid, final String profile) {
super(EntityAuthenticationScheme.PSK_PROFILE);
this.pskid = pskid;
this.profile = profile;
}
/**
* Construct a new preshared keys profile authentication data instance from
* the provided MSL object.
*
* @param authMo the authentication data MSL object.
* @throws MslEncodingException if there is an error parsing the entity
* authentication data.
*/
public PresharedProfileAuthenticationData(final MslObject authMo) throws MslEncodingException {
super(EntityAuthenticationScheme.PSK_PROFILE);
try {
pskid = authMo.getString(KEY_PSKID);
profile = authMo.getString(KEY_PROFILE);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "psk profile authdata " + authMo.toString(), e);
}
}
/**
* <p>Returns the entity identity. This is equal to the preshared keys
* identity and profile strings joined with a hyphen, e.g.
* {@code pskid-profile}.</p>
*
* @return the entity identity.
*/
@Override
public String getIdentity() {
return pskid + CONCAT_CHAR + profile;
}
/**
* @return the entity preshared keys identity.
*/
public String getPresharedKeysId() {
return pskid;
}
/**
* @return the entity profile.
*/
public String getProfile() {
return profile;
}
/* (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) {
final MslObject mo = encoder.createObject();
mo.put(KEY_PSKID, pskid);
mo.put(KEY_PROFILE, profile);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof PresharedProfileAuthenticationData)) return false;
final PresharedProfileAuthenticationData that = (PresharedProfileAuthenticationData)obj;
return super.equals(obj) && this.pskid.equals(that.pskid) && this.profile.equals(that.profile);
}
/* (non-Javadoc)
* @see com.netflix.msl.entityauth.EntityAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ pskid.hashCode() ^ profile.hashCode();
}
/** Entity preshared keys identity. */
private final String pskid;
/** Entity profile. */
private final String profile;
}
| 1,783 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/EntityAuthenticationScheme.java
|
/**
* Copyright (c) 2012-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.entityauth;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* <p>Entity authentication schemes.</p>
*
* <p>The scheme name is used to uniquely identify entity authentication
* schemes.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class EntityAuthenticationScheme {
/** Map of names onto schemes. */
private static Map<String,EntityAuthenticationScheme> schemes = new HashMap<String,EntityAuthenticationScheme>();
/** Pre-shared keys. */
public static final EntityAuthenticationScheme PSK = new EntityAuthenticationScheme("PSK", true, true);
/** Pre-shared keys with entity profiles. */
public static final EntityAuthenticationScheme PSK_PROFILE = new EntityAuthenticationScheme("PSK_PROFILE", true, true);
/** X.509 public/private key pair. */
public static final EntityAuthenticationScheme X509 = new EntityAuthenticationScheme("X509", false, true);
/** RSA public/private key pair. */
public static final EntityAuthenticationScheme RSA = new EntityAuthenticationScheme("RSA", false, true);
/** ECC public/private key pair. */
public static final EntityAuthenticationScheme ECC = new EntityAuthenticationScheme("ECC", false, true);
/** Unauthenticated. */
public static final EntityAuthenticationScheme NONE = new EntityAuthenticationScheme("NONE", false, false);
/** Unauthenticated suffixed. */
public static final EntityAuthenticationScheme NONE_SUFFIXED = new EntityAuthenticationScheme("NONE_SUFFIXED", false, false);
/** Master token protected. */
public static final EntityAuthenticationScheme MT_PROTECTED = new EntityAuthenticationScheme("MT_PROTECTED", false, false);
/** Provisioned. */
public static final EntityAuthenticationScheme PROVISIONED = new EntityAuthenticationScheme("PROVISIONED", false, false);
/**
* 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 EntityAuthenticationScheme(final String name, final boolean encrypts, final boolean protects) {
this.name = name;
this.encrypts = encrypts;
this.protects = protects;
// Add this scheme to the map.
synchronized (schemes) {
schemes.put(name, this);
}
}
/**
* @param name the entity authentication scheme name.
* @return the scheme identified by the specified name or {@code null} if
* there is none.
*/
public static EntityAuthenticationScheme getScheme(final String name) {
return schemes.get(name);
}
/**
* @return all known entity authentication schemes.
*/
public static Collection<EntityAuthenticationScheme> values() {
return schemes.values();
}
/**
* @return the scheme identifier.
*/
public String name() {
return name;
}
/**
* @return true if the scheme encrypts message data.
*/
public boolean encrypts() {
return encrypts;
}
/**
* @return true if the scheme protects message integrity.
*/
public boolean protectsIntegrity() {
return protects;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
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 EntityAuthenticationScheme)) return false;
final EntityAuthenticationScheme that = (EntityAuthenticationScheme)obj;
return this.name.equals(that.name);
}
/** Scheme name. */
private final String name;
/** Encrypts message data. */
private final boolean encrypts;
/** Protects message integrity. */
private final boolean protects;
}
| 1,784 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/RsaAuthenticationFactory.java
|
/**
* Copyright (c) 2012-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.entityauth;
import java.security.PrivateKey;
import java.security.PublicKey;
import com.netflix.msl.MslCryptoException;
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.crypto.RsaCryptoContext;
import com.netflix.msl.crypto.RsaCryptoContext.Mode;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>RSA asymmetric keys entity authentication factory.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class RsaAuthenticationFactory extends EntityAuthenticationFactory {
/**
* <p>Construct a new RSA asymmetric keys authentication factory
* instance.</p>
*
* @param store RSA key store.
* @param authutils authentication utilities.
*/
public RsaAuthenticationFactory(final RsaStore store, final AuthenticationUtils authutils) {
this(null, store, authutils);
}
/**
* <p>Construct a new RSA asymmetric keys authentication factory instance
* with the specified key pair ID for the local entity. The RSA key store
* must contain a private key for the local entity (a public key is
* optional).</p>
*
* @param keyPairId local entity key pair ID.
* @param store RSA key store.
* @param authutils authentication utilities.
*/
public RsaAuthenticationFactory(final String keyPairId, final RsaStore store, final AuthenticationUtils authutils) {
super(EntityAuthenticationScheme.RSA);
this.keyPairId = keyPairId;
this.store = store;
this.authutils = authutils;
}
/* (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, MslCryptoException {
return new RsaAuthenticationData(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 RsaAuthenticationData))
throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + ".");
final RsaAuthenticationData rad = (RsaAuthenticationData)authdata;
// Check for revocation.
final String identity = rad.getIdentity();
if (authutils.isEntityRevoked(identity))
throw new MslEntityAuthException(MslError.ENTITY_REVOKED, "rsa " + identity).setEntityAuthenticationData(rad);
// Verify the scheme is permitted.
if (!authutils.isSchemePermitted(identity, getScheme()))
throw new MslEntityAuthException(MslError.INCORRECT_ENTITYAUTH_DATA, "Authentication Scheme for Device Type Not Supported " + identity + ":" + getScheme()).setEntityAuthenticationData(rad);
// Extract RSA authentication data.
final String pubkeyid = rad.getPublicKeyId();
final PublicKey publicKey = store.getPublicKey(pubkeyid);
final PrivateKey privateKey = store.getPrivateKey(pubkeyid);
// The local entity must have a private key.
if (pubkeyid.equals(keyPairId) && privateKey == null)
throw new MslEntityAuthException(MslError.RSA_PRIVATEKEY_NOT_FOUND, pubkeyid).setEntityAuthenticationData(rad);
// Remote entities must have a public key.
else if (!pubkeyid.equals(keyPairId) && publicKey == null)
throw new MslEntityAuthException(MslError.RSA_PUBLICKEY_NOT_FOUND, pubkeyid).setEntityAuthenticationData(rad);
// Return the crypto context.
return new RsaCryptoContext(ctx, identity, privateKey, publicKey, Mode.SIGN_VERIFY);
}
/** Local entity key pair ID. */
private final String keyPairId;
/** RSA key store. */
private final RsaStore store;
/** Authentication utilities. */
final AuthenticationUtils authutils;
}
| 1,785 |
0 |
Create_ds/msl/core/src/main/java/com/netflix/msl
|
Create_ds/msl/core/src/main/java/com/netflix/msl/entityauth/X509AuthenticationFactory.java
|
/**
* Copyright (c) 2012-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.entityauth;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import com.netflix.msl.MslCryptoException;
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.crypto.RsaCryptoContext;
import com.netflix.msl.crypto.RsaCryptoContext.Mode;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>X.509 asymmetric keys entity authentication factory.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class X509AuthenticationFactory extends EntityAuthenticationFactory {
/**
* Construct a new X.509 asymmetric keys authentication factory instance.
*
* @param store X.509 certificate authority store.
* @param authutils entity authentication utilities.
*/
public X509AuthenticationFactory(final X509Store store, final AuthenticationUtils authutils) {
super(EntityAuthenticationScheme.X509);
this.caStore = store;
this.authutils = authutils;
}
/* (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 MslCryptoException, MslEncodingException {
return new X509AuthenticationData(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 MslCryptoException, MslEntityAuthException {
// Make sure we have the right kind of entity authentication data.
if (!(authdata instanceof X509AuthenticationData))
throw new MslInternalException("Incorrect authentication data type " + authdata.getClass().getName() + ".");
final X509AuthenticationData x509ad = (X509AuthenticationData)authdata;
// Extract X.509 authentication data.
final X509Certificate cert = x509ad.getX509Cert();
final String identity = cert.getSubjectX500Principal().getName();
final PublicKey publicKey = cert.getPublicKey();
// Check for revocation.
if (authutils.isEntityRevoked(identity))
throw new MslEntityAuthException(MslError.ENTITY_REVOKED, cert.toString()).setEntityAuthenticationData(x509ad);
// Verify the scheme is permitted.
if (!authutils.isSchemePermitted(identity, getScheme()))
throw new MslEntityAuthException(MslError.INCORRECT_ENTITYAUTH_DATA, "Authentication Scheme for Device Type Not Supported " + identity + ":" + getScheme()).setEntityAuthenticationData(x509ad);
// Verify entity certificate.
try {
if (!caStore.isAccepted(cert))
throw new MslEntityAuthException(MslError.X509CERT_VERIFICATION_FAILED, cert.toString()).setEntityAuthenticationData(x509ad);
} catch (final CertificateExpiredException e) {
throw new MslEntityAuthException(MslError.X509CERT_EXPIRED, cert.toString(), e).setEntityAuthenticationData(x509ad);
} catch (final CertificateNotYetValidException e) {
throw new MslEntityAuthException(MslError.X509CERT_NOT_YET_VALID, cert.toString(), e).setEntityAuthenticationData(x509ad);
}
// Grab the optional private key.
final PrivateKey privkey = caStore.getPrivateKey(cert);
// Return the crypto context.
return new RsaCryptoContext(ctx, identity, privkey, publicKey, Mode.SIGN_VERIFY);
}
/** X.509 CA store. */
private final X509Store caStore;
/** Entity authentication utilities. */
private final AuthenticationUtils authutils;
}
| 1,786 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/MslExceptionTest.java
|
/**
* Copyright (c) 2012-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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.EmailPasswordAuthenticationData;
import com.netflix.msl.userauth.MockEmailPasswordAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.util.MockMslContext;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslTestUtils;
/**
* MslException unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
public class MslExceptionTest {
/**
* @return dummy user authentication data.
*/
private static UserAuthenticationData getUserAuthenticationData() {
return new EmailPasswordAuthenticationData("email", "password");
}
/** MSL context. */
private MslContext ctx;
@Before
public void setup() throws MslEncodingException, MslCryptoException {
ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
}
@Test
public void error() {
final MslException e = new MslException(MslError.MSL_PARSE_ERROR);
assertEquals(MslError.MSL_PARSE_ERROR, e.getError());
assertEquals(MslError.MSL_PARSE_ERROR.getMessage(), e.getMessage());
}
@Test
public void errorDetails() {
final MslException e = new MslException(MslError.MSL_ENCODE_ERROR, "details");
assertEquals(MslError.MSL_ENCODE_ERROR, e.getError());
assertEquals(MslError.MSL_ENCODE_ERROR.getMessage() + " [details]", e.getMessage());
}
@Test
public void errorDetailsCause() {
final MslException e = new MslException(MslError.ENCRYPT_ERROR, "details", new RuntimeException("cause"));
assertEquals(MslError.ENCRYPT_ERROR, e.getError());
assertEquals(MslError.ENCRYPT_ERROR.getMessage() + " [details]", e.getMessage());
final Throwable cause = e.getCause();
assertTrue(cause instanceof RuntimeException);
assertEquals("cause", cause.getMessage());
}
@Test
public void errorCause() {
final MslException e = new MslException(MslError.DECRYPT_ERROR, new RuntimeException("cause"));
assertEquals(MslError.DECRYPT_ERROR, e.getError());
assertEquals(MslError.DECRYPT_ERROR.getMessage(), e.getMessage());
final Throwable cause = e.getCause();
assertTrue(cause instanceof RuntimeException);
assertEquals("cause", cause.getMessage());
}
@Test
public void setEntityMasterToken() throws MslEncodingException, MslCryptoException {
final MslException e = new MslException(MslError.MSL_PARSE_ERROR);
assertNull(e.getMasterToken());
assertNull(e.getEntityAuthenticationData());
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(ctx.getEntityAuthenticationData(null));
assertEquals(masterToken, e.getMasterToken());
assertNull(e.getEntityAuthenticationData());
}
@Test
public void setEntityEntityAuthData() {
final MslException e = new MslException(MslError.MSL_PARSE_ERROR);
assertNull(e.getMasterToken());
assertNull(e.getEntityAuthenticationData());
final EntityAuthenticationData entityAuthData = ctx.getEntityAuthenticationData(null);
e.setEntityAuthenticationData(entityAuthData);
assertNull(e.getMasterToken());
assertEquals(entityAuthData, e.getEntityAuthenticationData());
}
@Test
public void setUserUserIdToken() throws MslEncodingException, MslCryptoException {
final MslException e = new MslException(MslError.MSL_PARSE_ERROR);
assertNull(e.getUserIdToken());
assertNull(e.getUserAuthenticationData());
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserAuthenticationData userAuthData = getUserAuthenticationData();
e.setUserIdToken(userIdToken);
e.setUserAuthenticationData(userAuthData);
assertEquals(userIdToken, e.getUserIdToken());
assertNull(e.getUserAuthenticationData());
}
@Test
public void setUserUserAuthData() {
final MslException e = new MslException(MslError.MSL_PARSE_ERROR);
assertNull(e.getUserIdToken());
assertNull(e.getUserAuthenticationData());
final UserAuthenticationData userAuthData = getUserAuthenticationData();
e.setUserAuthenticationData(userAuthData);
assertNull(e.getUserIdToken());
assertEquals(userAuthData, e.getUserAuthenticationData());
}
@Test
public void setMessageId() {
final MslException e = new MslException(MslError.MSL_PARSE_ERROR);
assertNull(e.getMessageId());
e.setMessageId(1);
assertEquals(Long.valueOf(1), e.getMessageId());
}
@Test(expected = IllegalArgumentException.class)
public void negativeMessageId() {
final MslException e = new MslException(MslError.MSL_PARSE_ERROR);
e.setMessageId(-1);
}
@Test(expected = IllegalArgumentException.class)
public void tooLargeMessageId() {
final MslException e = new MslException(MslError.MSL_PARSE_ERROR);
e.setMessageId(MslConstants.MAX_LONG_VALUE + 1);
}
}
| 1,787 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/crypto/JsonWebKeyTest.java
|
/**
* Copyright (c) 2013-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.crypto;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.json.JSONArray;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.crypto.JsonWebKey.Algorithm;
import com.netflix.msl.crypto.JsonWebKey.KeyOp;
import com.netflix.msl.crypto.JsonWebKey.Type;
import com.netflix.msl.crypto.JsonWebKey.Usage;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.io.MslArray;
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.test.ExpectedMslException;
import com.netflix.msl.util.MockMslContext;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslTestUtils;
/**
* JSON web key unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
public class JsonWebKeyTest {
/** JSON key key type. */
private static final String KEY_TYPE = "kty";
/** JSON key usage. */
private static final String KEY_USAGE = "use";
/** JSON key key operations. */
private static final String KEY_KEY_OPS = "key_ops";
/** JSON key algorithm. */
private static final String KEY_ALGORITHM = "alg";
/** JSON key extractable. */
private static final String KEY_EXTRACTABLE = "extractable";
/** JSON key key ID. */
private static final String KEY_KEY_ID = "kid";
// RSA keys.
/** JSON key modulus. */
private static final String KEY_MODULUS = "n";
/** JSON key public exponent. */
private static final String KEY_PUBLIC_EXPONENT = "e";
/** JSON key private exponent. */
private static final String KEY_PRIVATE_EXPONENT = "d";
// Symmetric keys.
/** JSON key key. */
private static final String KEY_KEY = "k";
// Key operations.
/** Encrypt/decrypt key operations. */
private static final Set<KeyOp> ENCRYPT_DECRYPT = new HashSet<KeyOp>(Arrays.asList(KeyOp.encrypt, KeyOp.decrypt));
/** Wrap/unwrap key operations. */
private static final Set<KeyOp> WRAP_UNWRAP = new HashSet<KeyOp>(Arrays.asList(KeyOp.wrapKey, KeyOp.unwrapKey));
/** Sign/verify key operations. */
private static final Set<KeyOp> SIGN_VERIFY = new HashSet<KeyOp>(Arrays.asList(KeyOp.sign, KeyOp.verify));
// Expected key operations MSL arrays.
/** Sign/verify. */
private static final MslArray MA_SIGN_VERIFY = new MslArray(Arrays.asList(KeyOp.sign.name(), KeyOp.verify.name()).toArray());
/** Encrypt/decrypt. */
private static final MslArray MA_ENCRYPT_DECRYPT = new MslArray(Arrays.asList(KeyOp.encrypt.name(), KeyOp.verify.name()).toArray());
/** Wrap/unwrap. */
private static final MslArray MA_WRAP_UNWRAP = new MslArray(Arrays.asList(KeyOp.wrapKey.name(), KeyOp.unwrapKey.name()).toArray());
/** Null usage. */
private static final Usage NULL_USAGE = null;
/** Null key operations. */
private static final Set<KeyOp> NULL_KEYOPS = null;
/**
* Returns the big integer in big-endian format without any leading sign
* bits.
*
* @param bi the big integer.
* @return the big integer in big-endian form.
*/
private static byte[] bi2bytes(final BigInteger bi) {
final byte[] bib = bi.toByteArray();
final int len = (int)Math.ceil((double)bi.bitLength() / Byte.SIZE);
return Arrays.copyOfRange(bib, bib.length - len, bib.length);
}
private static final boolean EXTRACTABLE = true;
private static final String KEY_ID = "kid";
private static RSAPublicKey PUBLIC_KEY;
private static RSAPrivateKey PRIVATE_KEY;
private static SecretKey SECRET_KEY;
private static final Random random = new Random();
/** MSL encoder factory. */
private static MslEncoderFactory encoder;
/** Encoder format. */
private static MslEncoderFormat ENCODER_FORMAT = MslEncoderFormat.JSON;
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
@BeforeClass
public static void setup() throws NoSuchAlgorithmException, MslEncodingException, MslCryptoException {
Security.addProvider(new BouncyCastleProvider());
final MslContext ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
encoder = ctx.getMslEncoderFactory();
final KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA");
keypairGenerator.initialize(512);
final KeyPair keypair = keypairGenerator.generateKeyPair();
PRIVATE_KEY = (RSAPrivateKey)keypair.getPrivate();
PUBLIC_KEY = (RSAPublicKey)keypair.getPublic();
final byte[] keydata = new byte[16];
random.nextBytes(keydata);
SECRET_KEY = new SecretKeySpec(keydata, JcaAlgorithm.AES);
}
@AfterClass
public static void teardown() {
encoder = null;
}
@Test
public void rsaUsageCtor() throws MslCryptoException, MslEncodingException, MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(Usage.sig, Algorithm.RSA1_5, EXTRACTABLE, KEY_ID, PUBLIC_KEY, PRIVATE_KEY);
assertEquals(EXTRACTABLE, jwk.isExtractable());
assertEquals(Algorithm.RSA1_5, jwk.getAlgorithm());
assertEquals(KEY_ID, jwk.getId());
final KeyPair keypair = jwk.getRsaKeyPair();
assertNotNull(keypair);
final RSAPublicKey pubkey = (RSAPublicKey)keypair.getPublic();
assertEquals(PUBLIC_KEY.getModulus(), pubkey.getModulus());
assertEquals(PUBLIC_KEY.getPublicExponent(), pubkey.getPublicExponent());
final RSAPrivateKey privkey = (RSAPrivateKey)keypair.getPrivate();
assertEquals(PRIVATE_KEY.getModulus(), privkey.getModulus());
assertEquals(PRIVATE_KEY.getPrivateExponent(), privkey.getPrivateExponent());
assertNull(jwk.getSecretKey());
assertEquals(Type.rsa, jwk.getType());
assertEquals(Usage.sig, jwk.getUsage());
assertNull(jwk.getKeyOps());
final byte[] encode = jwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(encode);
final JsonWebKey moJwk = new JsonWebKey(encoder.parseObject(encode));
assertEquals(jwk.isExtractable(), moJwk.isExtractable());
assertEquals(jwk.getAlgorithm(), moJwk.getAlgorithm());
assertEquals(jwk.getId(), moJwk.getId());
final KeyPair moKeypair = moJwk.getRsaKeyPair();
assertNotNull(moKeypair);
final RSAPublicKey moPubkey = (RSAPublicKey)moKeypair.getPublic();
assertEquals(pubkey.getModulus(), moPubkey.getModulus());
assertEquals(pubkey.getPublicExponent(), moPubkey.getPublicExponent());
final RSAPrivateKey moPrivkey = (RSAPrivateKey)moKeypair.getPrivate();
assertEquals(privkey.getModulus(), moPrivkey.getModulus());
assertEquals(privkey.getPrivateExponent(), moPrivkey.getPrivateExponent());
assertNull(moJwk.getSecretKey());
assertEquals(jwk.getType(), moJwk.getType());
assertEquals(jwk.getUsage(), moJwk.getUsage());
assertEquals(jwk.getKeyOps(), moJwk.getKeyOps());
final byte[] moEncode = moJwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(moEncode);
assertArrayEquals(encode, moEncode);
}
@Test
public void rsaKeyOpsCtor() throws MslCryptoException, MslEncodingException, MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(SIGN_VERIFY, Algorithm.RSA1_5, EXTRACTABLE, KEY_ID, PUBLIC_KEY, PRIVATE_KEY);
assertEquals(EXTRACTABLE, jwk.isExtractable());
assertEquals(Algorithm.RSA1_5, jwk.getAlgorithm());
assertEquals(KEY_ID, jwk.getId());
final KeyPair keypair = jwk.getRsaKeyPair();
assertNotNull(keypair);
final RSAPublicKey pubkey = (RSAPublicKey)keypair.getPublic();
assertEquals(PUBLIC_KEY.getModulus(), pubkey.getModulus());
assertEquals(PUBLIC_KEY.getPublicExponent(), pubkey.getPublicExponent());
final RSAPrivateKey privkey = (RSAPrivateKey)keypair.getPrivate();
assertEquals(PRIVATE_KEY.getModulus(), privkey.getModulus());
assertEquals(PRIVATE_KEY.getPrivateExponent(), privkey.getPrivateExponent());
assertNull(jwk.getSecretKey());
assertEquals(Type.rsa, jwk.getType());
assertNull(jwk.getUsage());
assertEquals(SIGN_VERIFY, jwk.getKeyOps());
final byte[] encode = jwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(encode);
final JsonWebKey moJwk = new JsonWebKey(encoder.parseObject(encode));
assertEquals(jwk.isExtractable(), moJwk.isExtractable());
assertEquals(jwk.getAlgorithm(), moJwk.getAlgorithm());
assertEquals(jwk.getId(), moJwk.getId());
final KeyPair moKeypair = moJwk.getRsaKeyPair();
assertNotNull(moKeypair);
final RSAPublicKey moPubkey = (RSAPublicKey)moKeypair.getPublic();
assertEquals(pubkey.getModulus(), moPubkey.getModulus());
assertEquals(pubkey.getPublicExponent(), moPubkey.getPublicExponent());
final RSAPrivateKey moPrivkey = (RSAPrivateKey)moKeypair.getPrivate();
assertEquals(privkey.getModulus(), moPrivkey.getModulus());
assertEquals(privkey.getPrivateExponent(), moPrivkey.getPrivateExponent());
assertNull(moJwk.getSecretKey());
assertEquals(jwk.getType(), moJwk.getType());
assertEquals(jwk.getUsage(), moJwk.getUsage());
assertEquals(jwk.getKeyOps(), moJwk.getKeyOps());
final byte[] moEncode = moJwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(moEncode);
// This test will not always pass since the key operations are
// unordered.
//assertArrayEquals(encode, moEncode);
}
@Test
public void rsaUsageJson() throws MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(Usage.sig, Algorithm.RSA1_5, EXTRACTABLE, KEY_ID, PUBLIC_KEY, PRIVATE_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
assertEquals(EXTRACTABLE, mo.optBoolean(KEY_EXTRACTABLE));
assertEquals(Algorithm.RSA1_5.name(), mo.getString(KEY_ALGORITHM));
assertEquals(KEY_ID, mo.getString(KEY_KEY_ID));
assertEquals(Type.rsa.name(), mo.getString(KEY_TYPE));
assertEquals(Usage.sig.name(), mo.getString(KEY_USAGE));
assertFalse(mo.has(KEY_KEY_OPS));
final String modulus = MslEncoderUtils.b64urlEncode(bi2bytes(PUBLIC_KEY.getModulus()));
final String pubexp = MslEncoderUtils.b64urlEncode(bi2bytes(PUBLIC_KEY.getPublicExponent()));
final String privexp = MslEncoderUtils.b64urlEncode(bi2bytes(PRIVATE_KEY.getPrivateExponent()));
assertEquals(modulus, mo.getString(KEY_MODULUS));
assertEquals(pubexp, mo.getString(KEY_PUBLIC_EXPONENT));
assertEquals(privexp, mo.getString(KEY_PRIVATE_EXPONENT));
assertFalse(mo.has(KEY_KEY));
}
@Test
public void rsaKeyOpsJson() throws MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(SIGN_VERIFY, Algorithm.RSA1_5, EXTRACTABLE, KEY_ID, PUBLIC_KEY, PRIVATE_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
assertEquals(EXTRACTABLE, mo.optBoolean(KEY_EXTRACTABLE));
assertEquals(Algorithm.RSA1_5.name(), mo.getString(KEY_ALGORITHM));
assertEquals(KEY_ID, mo.getString(KEY_KEY_ID));
assertEquals(Type.rsa.name(), mo.getString(KEY_TYPE));
assertFalse(mo.has(KEY_USAGE));
assertTrue(MslEncoderUtils.equalSets(MA_SIGN_VERIFY, mo.getMslArray(KEY_KEY_OPS)));
final String modulus = MslEncoderUtils.b64urlEncode(bi2bytes(PUBLIC_KEY.getModulus()));
final String pubexp = MslEncoderUtils.b64urlEncode(bi2bytes(PUBLIC_KEY.getPublicExponent()));
final String privexp = MslEncoderUtils.b64urlEncode(bi2bytes(PRIVATE_KEY.getPrivateExponent()));
assertEquals(modulus, mo.getString(KEY_MODULUS));
assertEquals(pubexp, mo.getString(KEY_PUBLIC_EXPONENT));
assertEquals(privexp, mo.getString(KEY_PRIVATE_EXPONENT));
assertFalse(mo.has(KEY_KEY));
}
@Test
public void rsaNullCtorPublic() throws MslCryptoException, MslEncodingException, MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, PUBLIC_KEY, null);
assertFalse(jwk.isExtractable());
assertNull(jwk.getAlgorithm());
assertNull(jwk.getId());
final KeyPair keypair = jwk.getRsaKeyPair();
assertNotNull(keypair);
final RSAPublicKey pubkey = (RSAPublicKey)keypair.getPublic();
assertEquals(PUBLIC_KEY.getModulus(), pubkey.getModulus());
assertEquals(PUBLIC_KEY.getPublicExponent(), pubkey.getPublicExponent());
final RSAPrivateKey privkey = (RSAPrivateKey)keypair.getPrivate();
assertNull(privkey);
assertNull(jwk.getSecretKey());
assertEquals(Type.rsa, jwk.getType());
assertNull(jwk.getUsage());
assertNull(jwk.getKeyOps());
final byte[] encode = jwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(encode);
final JsonWebKey moJwk = new JsonWebKey(encoder.parseObject(encode));
assertEquals(jwk.isExtractable(), moJwk.isExtractable());
assertEquals(jwk.getAlgorithm(), moJwk.getAlgorithm());
assertEquals(jwk.getId(), moJwk.getId());
final KeyPair moKeypair = moJwk.getRsaKeyPair();
assertNotNull(moKeypair);
final RSAPublicKey moPubkey = (RSAPublicKey)moKeypair.getPublic();
assertEquals(pubkey.getModulus(), moPubkey.getModulus());
assertEquals(pubkey.getPublicExponent(), moPubkey.getPublicExponent());
final RSAPrivateKey moPrivkey = (RSAPrivateKey)moKeypair.getPrivate();
assertNull(moPrivkey);
assertNull(moJwk.getSecretKey());
assertEquals(jwk.getType(), moJwk.getType());
assertEquals(jwk.getUsage(), moJwk.getUsage());
assertEquals(jwk.getKeyOps(), moJwk.getKeyOps());
final byte[] moEncode = moJwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(moEncode);
assertArrayEquals(encode, moEncode);
}
@Test
public void rsaNullCtorPrivate() throws MslCryptoException, MslEncodingException, MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, null, PRIVATE_KEY);
assertFalse(jwk.isExtractable());
assertNull(jwk.getAlgorithm());
assertNull(jwk.getId());
final KeyPair keypair = jwk.getRsaKeyPair();
assertNotNull(keypair);
final RSAPublicKey pubkey = (RSAPublicKey)keypair.getPublic();
assertNull(pubkey);
final RSAPrivateKey privkey = (RSAPrivateKey)keypair.getPrivate();
assertEquals(PRIVATE_KEY.getModulus(), privkey.getModulus());
assertEquals(PRIVATE_KEY.getPrivateExponent(), privkey.getPrivateExponent());
assertNull(jwk.getSecretKey());
assertEquals(Type.rsa, jwk.getType());
assertNull(jwk.getUsage());
assertNull(jwk.getKeyOps());
final byte[] encode = jwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(encode);
final JsonWebKey moJwk = new JsonWebKey(encoder.parseObject(encode));
assertEquals(jwk.isExtractable(), moJwk.isExtractable());
assertEquals(jwk.getAlgorithm(), moJwk.getAlgorithm());
assertEquals(jwk.getId(), moJwk.getId());
final KeyPair moKeypair = moJwk.getRsaKeyPair();
assertNotNull(moKeypair);
final RSAPublicKey moPubkey = (RSAPublicKey)moKeypair.getPublic();
assertNull(moPubkey);
final RSAPrivateKey moPrivkey = (RSAPrivateKey)moKeypair.getPrivate();
assertEquals(privkey.getModulus(), moPrivkey.getModulus());
assertEquals(privkey.getPrivateExponent(), moPrivkey.getPrivateExponent());
assertNull(moJwk.getSecretKey());
assertEquals(jwk.getType(), moJwk.getType());
assertEquals(jwk.getUsage(), moJwk.getUsage());
assertEquals(jwk.getKeyOps(), moJwk.getKeyOps());
final byte[] moEncode = moJwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(moEncode);
assertArrayEquals(encode, moEncode);
}
@Test
public void rsaNullJsonPublic() throws MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, PUBLIC_KEY, null);
final byte[] encode = jwk.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
assertFalse(mo.getBoolean(KEY_EXTRACTABLE));
assertFalse(mo.has(KEY_ALGORITHM));
assertFalse(mo.has(KEY_KEY_ID));
assertEquals(Type.rsa.name(), mo.getString(KEY_TYPE));
assertFalse(mo.has(KEY_USAGE));
assertFalse(mo.has(KEY_KEY_OPS));
final String modulus = MslEncoderUtils.b64urlEncode(bi2bytes(PUBLIC_KEY.getModulus()));
final String pubexp = MslEncoderUtils.b64urlEncode(bi2bytes(PUBLIC_KEY.getPublicExponent()));
assertEquals(modulus, mo.getString(KEY_MODULUS));
assertEquals(pubexp, mo.getString(KEY_PUBLIC_EXPONENT));
assertFalse(mo.has(KEY_PRIVATE_EXPONENT));
assertFalse(mo.has(KEY_KEY));
}
@Test
public void rsaNullJsonPrivate() throws MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, null, PRIVATE_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
assertFalse(mo.getBoolean(KEY_EXTRACTABLE));
assertFalse(mo.has(KEY_ALGORITHM));
assertFalse(mo.has(KEY_KEY_ID));
assertEquals(Type.rsa.name(), mo.getString(KEY_TYPE));
assertFalse(mo.has(KEY_USAGE));
assertFalse(mo.has(KEY_KEY_OPS));
final String modulus = MslEncoderUtils.b64urlEncode(bi2bytes(PUBLIC_KEY.getModulus()));
final String privexp = MslEncoderUtils.b64urlEncode(bi2bytes(PRIVATE_KEY.getPrivateExponent()));
assertEquals(modulus, mo.getString(KEY_MODULUS));
assertFalse(mo.has(KEY_PUBLIC_EXPONENT));
assertEquals(privexp, mo.getString(KEY_PRIVATE_EXPONENT));
assertFalse(mo.has(KEY_KEY));
}
@Test(expected = MslInternalException.class)
public void rsaCtorNullKeys() {
new JsonWebKey(NULL_USAGE, null, false, null, null, null);
}
@Test(expected = MslInternalException.class)
public void rsaCtorMismatchedAlgorithm() {
new JsonWebKey(NULL_USAGE, Algorithm.A128CBC, false, null, PUBLIC_KEY, PRIVATE_KEY);
}
@Test
public void octUsageCtor() throws MslCryptoException, MslEncodingException, MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(Usage.enc, Algorithm.A128CBC, EXTRACTABLE, KEY_ID, SECRET_KEY);
assertEquals(EXTRACTABLE, jwk.isExtractable());
assertEquals(Algorithm.A128CBC, jwk.getAlgorithm());
assertEquals(KEY_ID, jwk.getId());
assertNull(jwk.getRsaKeyPair());
assertArrayEquals(SECRET_KEY.getEncoded(), jwk.getSecretKey().getEncoded());
assertEquals(Type.oct, jwk.getType());
assertEquals(Usage.enc, jwk.getUsage());
assertNull(jwk.getKeyOps());
final byte[] encode = jwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(encode);
final JsonWebKey moJwk = new JsonWebKey(encoder.parseObject(encode));
assertEquals(jwk.isExtractable(), moJwk.isExtractable());
assertEquals(jwk.getAlgorithm(), moJwk.getAlgorithm());
assertEquals(jwk.getId(), moJwk.getId());
assertNull(moJwk.getRsaKeyPair());
assertArrayEquals(jwk.getSecretKey().getEncoded(), moJwk.getSecretKey().getEncoded());
assertEquals(jwk.getType(), moJwk.getType());
assertEquals(jwk.getUsage(), moJwk.getUsage());
assertEquals(jwk.getKeyOps(), moJwk.getKeyOps());
final byte[] moEncode = moJwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(moEncode);
assertArrayEquals(encode, moEncode);
}
@Test
public void octKeyOpsCtor() throws MslCryptoException, MslEncodingException, MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(ENCRYPT_DECRYPT, Algorithm.A128CBC, EXTRACTABLE, KEY_ID, SECRET_KEY);
assertEquals(EXTRACTABLE, jwk.isExtractable());
assertEquals(Algorithm.A128CBC, jwk.getAlgorithm());
assertEquals(KEY_ID, jwk.getId());
assertNull(jwk.getRsaKeyPair());
assertArrayEquals(SECRET_KEY.getEncoded(), jwk.getSecretKey().getEncoded());
assertEquals(Type.oct, jwk.getType());
assertNull(jwk.getUsage());
assertEquals(ENCRYPT_DECRYPT, jwk.getKeyOps());
final byte[] encode = jwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(encode);
final JsonWebKey moJwk = new JsonWebKey(encoder.parseObject(encode));
assertEquals(jwk.isExtractable(), moJwk.isExtractable());
assertEquals(jwk.getAlgorithm(), moJwk.getAlgorithm());
assertEquals(jwk.getId(), moJwk.getId());
assertNull(moJwk.getRsaKeyPair());
assertArrayEquals(jwk.getSecretKey().getEncoded(), moJwk.getSecretKey().getEncoded());
assertEquals(jwk.getType(), moJwk.getType());
assertEquals(jwk.getUsage(), moJwk.getUsage());
assertEquals(jwk.getKeyOps(), moJwk.getKeyOps());
final byte[] moEncode = moJwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(moEncode);
// This test will not always pass since the key operations are
// unordered.
//assertArrayEquals(encode, moEncode);
}
@Test
public void octUsageJson() throws MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(Usage.wrap, Algorithm.A128KW, EXTRACTABLE, KEY_ID, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
assertEquals(EXTRACTABLE, mo.optBoolean(KEY_EXTRACTABLE));
assertEquals(Algorithm.A128KW.name(), mo.getString(KEY_ALGORITHM));
assertEquals(KEY_ID, mo.getString(KEY_KEY_ID));
assertEquals(Type.oct.name(), mo.getString(KEY_TYPE));
assertEquals(Usage.wrap.name(), mo.getString(KEY_USAGE));
assertFalse(mo.has(KEY_KEY_OPS));
assertFalse(mo.has(KEY_MODULUS));
assertFalse(mo.has(KEY_PUBLIC_EXPONENT));
assertFalse(mo.has(KEY_PRIVATE_EXPONENT));
final String key = MslEncoderUtils.b64urlEncode(SECRET_KEY.getEncoded());
assertEquals(key, mo.getString(KEY_KEY));
}
@Test
public void octKeyOpsJson() throws MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(WRAP_UNWRAP, Algorithm.A128KW, EXTRACTABLE, KEY_ID, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
assertEquals(EXTRACTABLE, mo.optBoolean(KEY_EXTRACTABLE));
assertEquals(Algorithm.A128KW.name(), mo.getString(KEY_ALGORITHM));
assertEquals(KEY_ID, mo.getString(KEY_KEY_ID));
assertEquals(Type.oct.name(), mo.getString(KEY_TYPE));
assertFalse(mo.has(KEY_USAGE));
assertTrue(MslEncoderUtils.equalSets(MA_WRAP_UNWRAP, mo.getMslArray(KEY_KEY_OPS)));
assertFalse(mo.has(KEY_MODULUS));
assertFalse(mo.has(KEY_PUBLIC_EXPONENT));
assertFalse(mo.has(KEY_PRIVATE_EXPONENT));
final String key = MslEncoderUtils.b64urlEncode(SECRET_KEY.getEncoded());
assertEquals(key, mo.getString(KEY_KEY));
}
@Test
public void octNullCtor() throws MslCryptoException, MslEncodingException, MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, SECRET_KEY);
assertFalse(jwk.isExtractable());
assertNull(jwk.getAlgorithm());
assertNull(jwk.getId());
assertNull(jwk.getRsaKeyPair());
assertArrayEquals(SECRET_KEY.getEncoded(), jwk.getSecretKey().getEncoded());
assertEquals(Type.oct, jwk.getType());
assertNull(jwk.getUsage());
assertNull(jwk.getKeyOps());
final byte[] encode = jwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(encode);
final JsonWebKey moJwk = new JsonWebKey(encoder.parseObject(encode));
assertEquals(jwk.isExtractable(), moJwk.isExtractable());
assertEquals(jwk.getAlgorithm(), moJwk.getAlgorithm());
assertEquals(jwk.getId(), moJwk.getId());
assertNull(moJwk.getRsaKeyPair());
assertArrayEquals(jwk.getSecretKey(SECRET_KEY.getAlgorithm()).getEncoded(), moJwk.getSecretKey(SECRET_KEY.getAlgorithm()).getEncoded());
assertEquals(jwk.getType(), moJwk.getType());
assertEquals(jwk.getUsage(), moJwk.getUsage());
assertEquals(jwk.getKeyOps(), moJwk.getKeyOps());
final byte[] moEncode = moJwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(moEncode);
assertArrayEquals(encode, moEncode);
}
@Test
public void octNullJson() throws MslEncoderException {
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
assertFalse(mo.getBoolean(KEY_EXTRACTABLE));
assertFalse(mo.has(KEY_ALGORITHM));
assertFalse(mo.has(KEY_KEY_ID));
assertEquals(Type.oct.name(), mo.getString(KEY_TYPE));
assertFalse(mo.has(KEY_USAGE));
assertFalse(mo.has(KEY_KEY_OPS));
assertFalse(mo.has(KEY_MODULUS));
assertFalse(mo.has(KEY_PUBLIC_EXPONENT));
assertFalse(mo.has(KEY_PRIVATE_EXPONENT));
final String key = MslEncoderUtils.b64urlEncode(SECRET_KEY.getEncoded());
assertEquals(key, mo.getString(KEY_KEY));
}
public void usageOnly() throws MslEncoderException, MslCryptoException, MslEncodingException {
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_USAGE, Usage.enc.name());
final JsonWebKey moJwk = new JsonWebKey(mo);
assertEquals(Usage.enc, moJwk.getUsage());
assertNull(moJwk.getKeyOps());
}
public void keyOpsOnly() throws MslEncoderException, MslCryptoException, MslEncodingException {
final JsonWebKey jwk = new JsonWebKey(NULL_KEYOPS, null, false, null, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_KEY_OPS, MA_ENCRYPT_DECRYPT);
final JsonWebKey moJwk = new JsonWebKey(mo);
assertNull(moJwk.getUsage());
assertEquals(new HashSet<KeyOp>(Arrays.asList(KeyOp.encrypt, KeyOp.decrypt)), moJwk.getKeyOps());
}
@Test(expected = MslInternalException.class)
public void octCtorMismatchedAlgo() {
new JsonWebKey(NULL_USAGE, Algorithm.RSA1_5, false, null, SECRET_KEY);
}
@Test
public void missingType() throws MslEncoderException, MslCryptoException, MslEncodingException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.remove(KEY_TYPE);
new JsonWebKey(mo);
}
@Test
public void invalidType() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNIDENTIFIED_JWK_TYPE);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_TYPE, "x");
new JsonWebKey(mo);
}
@Test
public void invalidUsage() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNIDENTIFIED_JWK_USAGE);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_USAGE, "x");
new JsonWebKey(mo);
}
@Test
public void invalidKeyOp() throws MslEncoderException, MslCryptoException, MslEncodingException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNIDENTIFIED_JWK_KEYOP);
final JsonWebKey jwk = new JsonWebKey(NULL_KEYOPS, null, false, null, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_KEY_OPS, new JSONArray(Arrays.asList(KeyOp.encrypt.name(), "x", KeyOp.decrypt.name()).toArray()));
new JsonWebKey(mo);
}
@Test
public void invalidAlgorithm() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNIDENTIFIED_JWK_ALGORITHM);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_ALGORITHM, "x");
new JsonWebKey(mo);
}
@Test
public void missingExtractable() throws MslEncoderException, MslCryptoException, MslEncodingException {
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, SECRET_KEY);
final byte[] encode = jwk.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
assertNotNull(mo.remove(KEY_EXTRACTABLE));
final JsonWebKey moJwk = new JsonWebKey(mo);
assertEquals(jwk.isExtractable(), moJwk.isExtractable());
assertEquals(jwk.getAlgorithm(), moJwk.getAlgorithm());
assertEquals(jwk.getId(), moJwk.getId());
assertNull(moJwk.getRsaKeyPair());
assertArrayEquals(jwk.getSecretKey(SECRET_KEY.getAlgorithm()).getEncoded(), moJwk.getSecretKey(SECRET_KEY.getAlgorithm()).getEncoded());
assertEquals(jwk.getType(), moJwk.getType());
assertEquals(jwk.getUsage(), moJwk.getUsage());
final byte[] moEncode = moJwk.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(moEncode);
assertArrayEquals(encode, moEncode);
}
@Test
public void invalidExtractable() throws MslEncodingException, MslEncoderException, MslCryptoException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_EXTRACTABLE, "x");
new JsonWebKey(mo);
}
@Test
public void missingKey() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.remove(KEY_KEY);
new JsonWebKey(mo);
}
@Test
public void emptyKey() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, SECRET_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_KEY, "");
new JsonWebKey(mo);
}
@Test
public void missingModulus() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, PUBLIC_KEY, PRIVATE_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.remove(KEY_MODULUS);
new JsonWebKey(mo);
}
@Test
public void emptyModulus() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, PUBLIC_KEY, PRIVATE_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_MODULUS, "");
new JsonWebKey(mo);
}
@Test
public void missingExponents() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, PUBLIC_KEY, PRIVATE_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.remove(KEY_PUBLIC_EXPONENT);
mo.remove(KEY_PRIVATE_EXPONENT);
new JsonWebKey(mo);
}
@Test
public void emptyPublicExponent() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, PUBLIC_KEY, PRIVATE_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_PUBLIC_EXPONENT, "");
new JsonWebKey(mo);
}
// This unit test no longer passes because
// Base64.decode() does not error when given invalid
// Base64 encoded data.
@Ignore
@Test
public void invalidPublicExpontent() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, PUBLIC_KEY, PRIVATE_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_PUBLIC_EXPONENT, "x");
new JsonWebKey(mo);
}
@Test
public void emptyPrivateExponent() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, PUBLIC_KEY, PRIVATE_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_PRIVATE_EXPONENT, "");
new JsonWebKey(mo);
}
// This unit test no longer passes because
// Base64.decode() does not error when given invalid
// Base64 encoded data.
@Ignore
@Test
public void invalidPrivateExponent() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
final JsonWebKey jwk = new JsonWebKey(NULL_USAGE, null, false, null, PUBLIC_KEY, PRIVATE_KEY);
final MslObject mo = MslTestUtils.toMslObject(encoder, jwk);
mo.put(KEY_PRIVATE_EXPONENT, "x");
new JsonWebKey(mo);
}
}
| 1,788 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/crypto/MslSignatureEnvelopeSuite.java
|
/**
* Copyright (c) 2013-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.crypto;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.netflix.msl.MslConstants.SignatureAlgo;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.crypto.MslSignatureEnvelope.Version;
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.MslObject;
import com.netflix.msl.util.MockMslContext;
import com.netflix.msl.util.MslContext;
/**
* MSL signature envelope unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
@RunWith(Suite.class)
@SuiteClasses({MslSignatureEnvelopeSuite.Version1.class,
MslSignatureEnvelopeSuite.Version2.class})
public class MslSignatureEnvelopeSuite {
/** MSL encoder format. */
private static final MslEncoderFormat ENCODER_FORMAT = MslEncoderFormat.JSON;
/** Key version. */
private static final String KEY_VERSION = "version";
/** Key algorithm. */
private static final String KEY_ALGORITHM = "algorithm";
/** Key signature. */
private static final String KEY_SIGNATURE = "signature";
private static final byte[] SIGNATURE = new byte[32];
/** MSL encoder factory. */
private static MslEncoderFactory encoder;
@BeforeClass
public static void setup() throws MslEncodingException, MslCryptoException {
final Random random = new Random();
random.nextBytes(SIGNATURE);
final MslContext ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
encoder = ctx.getMslEncoderFactory();
}
@AfterClass
public static void teardown() {
// Teardown causes problems because the data is shared by the inner
// classes, so don't do any cleanup.
}
public static class Version1 {
@Test
public void ctors() throws MslCryptoException, MslEncodingException, MslEncoderException {
final MslSignatureEnvelope envelope = new MslSignatureEnvelope(SIGNATURE);
assertNull(envelope.getAlgorithm());
assertArrayEquals(SIGNATURE, envelope.getSignature());
final byte[] envelopeBytes = envelope.getBytes(encoder, ENCODER_FORMAT);
assertNotNull(envelopeBytes);
final MslSignatureEnvelope moEnvelope = MslSignatureEnvelope.parse(envelopeBytes, encoder);
assertEquals(envelope.getAlgorithm(), moEnvelope.getAlgorithm());
assertArrayEquals(envelope.getSignature(), moEnvelope.getSignature());
final byte[] moEnvelopeBytes = moEnvelope.getBytes(encoder, ENCODER_FORMAT);
assertArrayEquals(envelopeBytes, moEnvelopeBytes);
}
@Test
public void encode() throws MslCryptoException, MslEncodingException, MslEncoderException {
final MslSignatureEnvelope envelope = new MslSignatureEnvelope(SIGNATURE);
final byte[] envelopeBytes = envelope.getBytes(encoder, ENCODER_FORMAT);
assertNotNull(envelopeBytes);
assertArrayEquals(SIGNATURE, envelopeBytes);
}
}
@RunWith(Parameterized.class)
public static class Version2 {
@Parameters
public static Collection<Object[]> data() throws MslEncodingException, MslCryptoException {
MslSignatureEnvelopeSuite.setup();
final List<Object[]> params = new ArrayList<Object[]>();
for (final SignatureAlgo algo: SignatureAlgo.values())
params.add(new Object[] { algo });
return params;
}
/** Algorithm. */
private final SignatureAlgo algorithm;
/**
* Create a new Version 2 test set with the provided algorithm.
*
* @param algorithm the algorithm.
*/
public Version2(final SignatureAlgo algorithm) {
this.algorithm = algorithm;
}
@Test
public void ctors() throws MslCryptoException, MslEncodingException, MslEncoderException {
final MslSignatureEnvelope envelope = new MslSignatureEnvelope(algorithm, SIGNATURE);
assertEquals(algorithm, envelope.getAlgorithm());
assertArrayEquals(SIGNATURE, envelope.getSignature());
final byte[] envelopeBytes = envelope.getBytes(encoder, ENCODER_FORMAT);
assertNotNull(envelopeBytes);
final MslSignatureEnvelope moEnvelope = MslSignatureEnvelope.parse(envelopeBytes, encoder);
assertEquals(envelope.getAlgorithm(), moEnvelope.getAlgorithm());
assertArrayEquals(envelope.getSignature(), moEnvelope.getSignature());
final byte[] moEnvelopeBytes = moEnvelope.getBytes(encoder, ENCODER_FORMAT);
assertArrayEquals(envelopeBytes, moEnvelopeBytes);
}
@Test
public void encode() throws MslEncoderException, MslEncoderException {
final MslSignatureEnvelope envelope = new MslSignatureEnvelope(algorithm, SIGNATURE);
final byte[] envelopeBytes = envelope.getBytes(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(envelopeBytes);
assertEquals(Version.V2.intValue(), mo.getInt(KEY_VERSION));
assertEquals(algorithm.toString(), mo.getString(KEY_ALGORITHM));
assertArrayEquals(SIGNATURE, mo.getBytes(KEY_SIGNATURE));
}
@Test
public void missingVersion() throws MslCryptoException, MslEncodingException, MslEncoderException {
final MslSignatureEnvelope envelope = new MslSignatureEnvelope(algorithm, SIGNATURE);
final byte[] envelopeBytes = envelope.getBytes(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(envelopeBytes);
mo.remove(KEY_VERSION);
final byte[] moEncode = encoder.encodeObject(mo, ENCODER_FORMAT);
final MslSignatureEnvelope moEnvelope = MslSignatureEnvelope.parse(moEncode, encoder);
assertNull(moEnvelope.getAlgorithm());
assertArrayEquals(moEncode, moEnvelope.getSignature());
}
@Test
public void invalidVersion() throws MslEncoderException, MslCryptoException, MslEncodingException {
final MslSignatureEnvelope envelope = new MslSignatureEnvelope(algorithm, SIGNATURE);
final byte[] envelopeBytes = envelope.getBytes(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(envelopeBytes);
mo.put(KEY_VERSION, "x");
final byte[] moEncode = encoder.encodeObject(mo, ENCODER_FORMAT);
final MslSignatureEnvelope moEnvelope = MslSignatureEnvelope.parse(moEncode, encoder);
assertNull(moEnvelope.getAlgorithm());
assertArrayEquals(moEncode, moEnvelope.getSignature());
}
@Test
public void unknownVersion() throws MslEncoderException, MslCryptoException, MslEncodingException {
final MslSignatureEnvelope envelope = new MslSignatureEnvelope(algorithm, SIGNATURE);
final byte[] envelopeBytes = envelope.getBytes(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(envelopeBytes);
mo.put(KEY_VERSION, -1);
final byte[] moEncode = encoder.encodeObject(mo, ENCODER_FORMAT);
final MslSignatureEnvelope moEnvelope = MslSignatureEnvelope.parse(moEncode, encoder);
assertNull(moEnvelope.getAlgorithm());
assertArrayEquals(moEncode, moEnvelope.getSignature());
}
@Test
public void missingAlgorithm() throws MslEncoderException, MslCryptoException, MslEncodingException {
final MslSignatureEnvelope envelope = new MslSignatureEnvelope(algorithm, SIGNATURE);
final byte[] envelopeBytes = envelope.getBytes(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(envelopeBytes);
mo.remove(KEY_ALGORITHM);
final byte[] moEncode = encoder.encodeObject(mo, ENCODER_FORMAT);
final MslSignatureEnvelope moEnvelope = MslSignatureEnvelope.parse(moEncode, encoder);
assertNull(moEnvelope.getAlgorithm());
assertArrayEquals(moEncode, moEnvelope.getSignature());
}
@Test
public void invalidAlgorithm() throws MslEncoderException, MslCryptoException, MslEncodingException {
final MslSignatureEnvelope envelope = new MslSignatureEnvelope(algorithm, SIGNATURE);
final byte[] envelopeBytes = envelope.getBytes(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(envelopeBytes);
mo.put(KEY_ALGORITHM, "x");
final byte[] moEncode = encoder.encodeObject(mo, ENCODER_FORMAT);
final MslSignatureEnvelope moEnvelope = MslSignatureEnvelope.parse(moEncode, encoder);
assertNull(moEnvelope.getAlgorithm());
assertArrayEquals(moEncode, moEnvelope.getSignature());
}
@Test
public void missingSignature() throws MslEncoderException, MslCryptoException, MslEncodingException {
final MslSignatureEnvelope envelope = new MslSignatureEnvelope(algorithm, SIGNATURE);
final byte[] envelopeBytes = envelope.getBytes(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(envelopeBytes);
mo.remove(KEY_SIGNATURE);
final byte[] moEncode = encoder.encodeObject(mo, ENCODER_FORMAT);
final MslSignatureEnvelope moEnvelope = MslSignatureEnvelope.parse(moEncode, encoder);
assertNull(moEnvelope.getAlgorithm());
assertArrayEquals(moEncode, moEnvelope.getSignature());
}
}
}
| 1,789 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/crypto/NullCryptoContextTest.java
|
/**
* Copyright (c) 2012-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.crypto;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Random;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.util.MockMslContext;
import com.netflix.msl.util.MslContext;
/**
* Null crypto context unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
public class NullCryptoContextTest {
/** MSL encoder format. */
private static final MslEncoderFormat ENCODER_FORMAT = MslEncoderFormat.JSON;
/** MSL encoder factory. */
private static MslEncoderFactory encoder;
@BeforeClass
public static void setup() throws MslEncodingException, MslCryptoException {
final MslContext ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
encoder = ctx.getMslEncoderFactory();
}
@AfterClass
public static void teardown() {
encoder = null;
}
@Test
public void encryptDecrypt() throws MslCryptoException {
final Random random = new Random();
final byte[] message = new byte[32];
random.nextBytes(message);
final NullCryptoContext cryptoContext = new NullCryptoContext();
final byte[] ciphertext = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void wrapUnwrap() throws MslCryptoException {
final Random random = new Random();
final byte[] message = new byte[32];
random.nextBytes(message);
final NullCryptoContext cryptoContext = new NullCryptoContext();
final byte[] ciphertext = cryptoContext.wrap(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final byte[] plaintext = cryptoContext.unwrap(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void signVerify() throws MslCryptoException {
final Random random = new Random();
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final NullCryptoContext cryptoContext = new NullCryptoContext();
final byte[] signatureA = cryptoContext.sign(messageA, encoder, ENCODER_FORMAT);
assertNotNull(signatureA);
assertEquals(0, signatureA.length);
assertTrue(cryptoContext.verify(messageA, signatureA, encoder));
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] signatureB = cryptoContext.sign(messageB, encoder, ENCODER_FORMAT);
assertArrayEquals(signatureA, signatureB);
assertTrue(cryptoContext.verify(messageB, signatureB, encoder));
assertTrue(cryptoContext.verify(messageB, signatureA, encoder));
}
}
| 1,790 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/crypto/JsonWebEncryptionCryptoContextSuite.java
|
/**
* Copyright (c) 2013-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.crypto;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.CekCryptoContext;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.Encryption;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.Format;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.io.MslArray;
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.test.ExpectedMslException;
import com.netflix.msl.util.MockMslContext;
import com.netflix.msl.util.MslContext;
/**
* JSON Web Encryption crypto context unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
@RunWith(Suite.class)
@SuiteClasses({JsonWebEncryptionCryptoContextSuite.JWE.class,
JsonWebEncryptionCryptoContextSuite.RsaOaepCompactSerialization.class,
JsonWebEncryptionCryptoContextSuite.RsaOaepJsonSerialization.class,
JsonWebEncryptionCryptoContextSuite.AesKwCompactSerialization.class,
JsonWebEncryptionCryptoContextSuite.AesKwJsonSerialization.class})
public class JsonWebEncryptionCryptoContextSuite {
/** Encoding charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/** Encoder format. */
private static final MslEncoderFormat ENCODER_FORMAT = MslEncoderFormat.JSON;
/** JSON key recipients. */
private static final String KEY_RECIPIENTS = "recipients";
/** JSON key header. */
private static final String KEY_HEADER = "header";
/** JSON key encrypted key. */
private static final String KEY_ENCRYPTED_KEY = "encrypted_key";
/** JSON key integrity value. */
private static final String KEY_INTEGRITY_VALUE = "integrity_value";
/** JSON key initialization vector. */
private static final String KEY_INITIALIZATION_VECTOR = "initialization_vector";
/** JSON key ciphertext. */
private static final String KEY_CIPHERTEXT = "ciphertext";
/** JSON key wrap algorithm. */
private static final String KEY_ALGORITHM = "alg";
/** JSON key encryption algorithm. */
private static final String KEY_ENCRYPTION = "enc";
/** Compact serialization header part index. */
private static final int HEADER_INDEX = 0;
/** Compact serialization encrypted content encryption key part index. */
private static final int ECEK_INDEX = 1;
/** Compact serialization initialization vector part index. */
private static final int IV_INDEX = 2;
/** Compact serialization ciphertext part index. */
private static final int CIPHERTEXT_INDEX = 3;
/** Compact serialization authentication tag part index. */
private static final int AUTHENTICATION_TAG_INDEX = 4;
/**
* Replace one part of the provided compact serialization with a specified
* value.
*
* @param serialization compact serialization.
* @param part zero-based part number to replace.
* @param value Base64-encoded replacement value.
* @return the modified compact serialization.
*/
private static byte[] replace(final byte[] serialization, final int part, final String value) {
final String s = new String(serialization, UTF_8);
final String[] parts = s.split("\\.");
parts[part] = value;
final StringBuilder b = new StringBuilder(parts[0]);
for (int i = 1; i < parts.length; ++i)
b.append("." + parts[i]);
return b.toString().getBytes(UTF_8);
}
/**
* Return the requested value of the provided JSON serialization.
*
* @param serialization JSON serialization.
* @param key JSON key.
* @return the requested Base64-encoded value.
* @throws MslEncoderException if there is an error parsing the serialization.
*/
private static String get(final byte[] serialization, final String key) throws MslEncoderException {
final MslObject serializationMo = encoder.parseObject(serialization);
final MslArray recipients = serializationMo.getMslArray(KEY_RECIPIENTS);
final MslObject recipient = recipients.getMslObject(0, encoder);
if (KEY_HEADER.equals(key) ||
KEY_ENCRYPTED_KEY.equals(key) ||
KEY_INTEGRITY_VALUE.equals(key))
{
return recipient.getString(key);
}
if (KEY_INITIALIZATION_VECTOR.equals(key) ||
KEY_CIPHERTEXT.equals(key))
{
return serializationMo.getString(key);
}
throw new IllegalArgumentException("Unknown JSON key: " + key);
}
/**
* Replace one part of the provided JSON serialization with a specified
* value.
*
* @param serialization JSON serialization.
* @param key JSON key.
* @param value replacement value.
* @return the modified JSON serialization.
* @throws MslEncoderException if there is an error modifying the JSON
* serialization.
*/
private static byte[] replace(final byte[] serialization, final String key, final Object value) throws MslEncoderException {
final MslObject serializationMo = encoder.parseObject(serialization);
final MslArray recipients = serializationMo.getMslArray(KEY_RECIPIENTS);
final MslObject recipient = recipients.getMslObject(0, encoder);
if (KEY_RECIPIENTS.equals(key)) {
// Return immediately after replacing because this creates a
// malformed serialization.
serializationMo.put(KEY_RECIPIENTS, value);
return serializationMo.toString().getBytes(UTF_8);
}
if (KEY_HEADER.equals(key) ||
KEY_ENCRYPTED_KEY.equals(key) ||
KEY_INTEGRITY_VALUE.equals(key))
{
recipient.put(key, value);
} else if (KEY_INITIALIZATION_VECTOR.equals(key) ||
KEY_CIPHERTEXT.equals(key))
{
serializationMo.put(key, value);
} else {
throw new IllegalArgumentException("Unknown JSON key: " + key);
}
recipients.put(0, recipient);
serializationMo.put(KEY_RECIPIENTS, recipients);
return serializationMo.toString().getBytes(UTF_8);
}
/**
* Remove one part of the provided JSON serialization.
*
* @param serialization JSON serialization.
* @param key JSON key.
* @return the modified JSON serialization.
* @throws MslEncoderException if there is an error modifying the JSON
* serialization.
*/
private static byte[] remove(final byte[] serialization, final String key) throws MslEncoderException {
final MslObject serializationJo = encoder.parseObject(serialization);
final MslArray recipients = serializationJo.getMslArray(KEY_RECIPIENTS);
final MslObject recipient = recipients.getMslObject(0, encoder);
if (KEY_RECIPIENTS.equals(key)) {
// Return immediately after removing because this creates a
// malformed serialization.
serializationJo.remove(KEY_RECIPIENTS);
return serializationJo.toString().getBytes(UTF_8);
}
if (KEY_HEADER.equals(key) ||
KEY_ENCRYPTED_KEY.equals(key) ||
KEY_INTEGRITY_VALUE.equals(key))
{
recipient.remove(key);
} else if (KEY_INITIALIZATION_VECTOR.equals(key) ||
KEY_CIPHERTEXT.equals(key))
{
serializationJo.remove(key);
} else {
throw new IllegalArgumentException("Unknown JSON key: " + key);
}
recipients.put(0, recipient);
serializationJo.put(KEY_RECIPIENTS, recipients);
return serializationJo.toString().getBytes(UTF_8);
}
/** MSL context. */
private static MslContext ctx;
/** MSL encoder factory. */
private static MslEncoderFactory encoder;
/** Random. */
private static Random random;
/** Random data. */
private static byte[] data;
/** RSA-OAEP content encryption key crypto context. */
private static CekCryptoContext rsaCryptoContext;
/** AES key wrap content encryption key crypto context. */
private static CekCryptoContext aesCryptoContext;
@BeforeClass
public static synchronized void setup() throws NoSuchAlgorithmException, MslEncodingException, MslCryptoException {
if (random == null) {
random = new Random();
data = new byte[1024];
random.nextBytes(data);
ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
encoder = ctx.getMslEncoderFactory();
final KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA");
keypairGenerator.initialize(512);
final KeyPair keypair = keypairGenerator.generateKeyPair();
final PrivateKey privateKey = keypair.getPrivate();
final PublicKey publicKey = keypair.getPublic();
rsaCryptoContext = new JsonWebEncryptionCryptoContext.RsaOaepCryptoContext(privateKey, publicKey);
final byte[] keydata = new byte[16];
random.nextBytes(keydata);
final SecretKey wrappingKey = new SecretKeySpec(keydata, JcaAlgorithm.AESKW);
aesCryptoContext = new JsonWebEncryptionCryptoContext.AesKwCryptoContext(wrappingKey);
}
}
@AfterClass
public static synchronized void teardown() {
// Teardown causes problems because the data is shared by the inner
// classes, so don't do any cleanup.
}
/** RSA-OAEP compact serialization unit tests. */
public static class RsaOaepCompactSerialization {
/** RFC RSA-OAEP keypair modulus. */
private static final byte[] RFC_MODULUS = {
(byte)161, (byte)168, (byte)84, (byte)34, (byte)133, (byte)176, (byte)208, (byte)173,
(byte)46, (byte)176, (byte)163, (byte)110, (byte)57, (byte)30, (byte)135, (byte)227,
(byte)9, (byte)31, (byte)226, (byte)128, (byte)84, (byte)92, (byte)116, (byte)241,
(byte)70, (byte)248, (byte)27, (byte)227, (byte)193, (byte)62, (byte)5, (byte)91,
(byte)241, (byte)145, (byte)224, (byte)205, (byte)141, (byte)176, (byte)184, (byte)133,
(byte)239, (byte)43, (byte)81, (byte)103, (byte)9, (byte)161, (byte)153, (byte)157,
(byte)179, (byte)104, (byte)123, (byte)51, (byte)189, (byte)34, (byte)152, (byte)69,
(byte)97, (byte)69, (byte)78, (byte)93, (byte)140, (byte)131, (byte)87, (byte)182,
(byte)169, (byte)101, (byte)92, (byte)142, (byte)3, (byte)22, (byte)167, (byte)8,
(byte)212, (byte)56, (byte)35, (byte)79, (byte)210, (byte)222, (byte)192, (byte)208,
(byte)252, (byte)49, (byte)109, (byte)138, (byte)173, (byte)253, (byte)210, (byte)166,
(byte)201, (byte)63, (byte)102, (byte)74, (byte)5, (byte)158, (byte)41, (byte)90,
(byte)144, (byte)108, (byte)160, (byte)79, (byte)10, (byte)89, (byte)222, (byte)231,
(byte)172, (byte)31, (byte)227, (byte)197, (byte)0, (byte)19, (byte)72, (byte)81,
(byte)138, (byte)78, (byte)136, (byte)221, (byte)121, (byte)118, (byte)196, (byte)17,
(byte)146, (byte)10, (byte)244, (byte)188, (byte)72, (byte)113, (byte)55, (byte)221,
(byte)162, (byte)217, (byte)171, (byte)27, (byte)57, (byte)233, (byte)210, (byte)101,
(byte)236, (byte)154, (byte)199, (byte)56, (byte)138, (byte)239, (byte)101, (byte)48,
(byte)198, (byte)186, (byte)202, (byte)160, (byte)76, (byte)111, (byte)234, (byte)71,
(byte)57, (byte)183, (byte)5, (byte)211, (byte)171, (byte)136, (byte)126, (byte)64,
(byte)40, (byte)75, (byte)58, (byte)89, (byte)244, (byte)254, (byte)107, (byte)84,
(byte)103, (byte)7, (byte)236, (byte)69, (byte)163, (byte)18, (byte)180, (byte)251,
(byte)58, (byte)153, (byte)46, (byte)151, (byte)174, (byte)12, (byte)103, (byte)197,
(byte)181, (byte)161, (byte)162, (byte)55, (byte)250, (byte)235, (byte)123, (byte)110,
(byte)17, (byte)11, (byte)158, (byte)24, (byte)47, (byte)133, (byte)8, (byte)199,
(byte)235, (byte)107, (byte)126, (byte)130, (byte)246, (byte)73, (byte)195, (byte)20,
(byte)108, (byte)202, (byte)176, (byte)214, (byte)187, (byte)45, (byte)146, (byte)182,
(byte)118, (byte)54, (byte)32, (byte)200, (byte)61, (byte)201, (byte)71, (byte)243,
(byte)1, (byte)255, (byte)131, (byte)84, (byte)37, (byte)111, (byte)211, (byte)168,
(byte)228, (byte)45, (byte)192, (byte)118, (byte)27, (byte)197, (byte)235, (byte)232,
(byte)36, (byte)10, (byte)230, (byte)248, (byte)190, (byte)82, (byte)182, (byte)140,
(byte)35, (byte)204, (byte)108, (byte)190, (byte)253, (byte)186, (byte)186, (byte)27 };
/** RFC RSA-OAEP keypair exponent. */
private static final byte[] RFC_PUBLIC_EXPONENT = { (byte)1, (byte)0, (byte)1 };
/** RFC RSA-OAEP private exponent. */
private static final byte[] RFC_PRIVATE_EXPONENT = {
(byte)144, (byte)183, (byte)109, (byte)34, (byte)62, (byte)134, (byte)108, (byte)57,
(byte)44, (byte)252, (byte)10, (byte)66, (byte)73, (byte)54, (byte)16, (byte)181,
(byte)233, (byte)92, (byte)54, (byte)219, (byte)101, (byte)42, (byte)35, (byte)178,
(byte)63, (byte)51, (byte)43, (byte)92, (byte)119, (byte)136, (byte)251, (byte)41,
(byte)53, (byte)23, (byte)191, (byte)164, (byte)164, (byte)60, (byte)88, (byte)227,
(byte)229, (byte)152, (byte)228, (byte)213, (byte)149, (byte)228, (byte)169, (byte)237,
(byte)104, (byte)71, (byte)151, (byte)75, (byte)88, (byte)252, (byte)216, (byte)77,
(byte)251, (byte)231, (byte)28, (byte)97, (byte)88, (byte)193, (byte)215, (byte)202,
(byte)248, (byte)216, (byte)121, (byte)195, (byte)211, (byte)245, (byte)250, (byte)112,
(byte)71, (byte)243, (byte)61, (byte)129, (byte)95, (byte)39, (byte)244, (byte)122,
(byte)225, (byte)217, (byte)169, (byte)211, (byte)165, (byte)48, (byte)253, (byte)220,
(byte)59, (byte)122, (byte)219, (byte)42, (byte)86, (byte)223, (byte)32, (byte)236,
(byte)39, (byte)48, (byte)103, (byte)78, (byte)122, (byte)216, (byte)187, (byte)88,
(byte)176, (byte)89, (byte)24, (byte)1, (byte)42, (byte)177, (byte)24, (byte)99,
(byte)142, (byte)170, (byte)1, (byte)146, (byte)43, (byte)3, (byte)108, (byte)64,
(byte)194, (byte)121, (byte)182, (byte)95, (byte)187, (byte)134, (byte)71, (byte)88,
(byte)96, (byte)134, (byte)74, (byte)131, (byte)167, (byte)69, (byte)106, (byte)143,
(byte)121, (byte)27, (byte)72, (byte)44, (byte)245, (byte)95, (byte)39, (byte)194,
(byte)179, (byte)175, (byte)203, (byte)122, (byte)16, (byte)112, (byte)183, (byte)17,
(byte)200, (byte)202, (byte)31, (byte)17, (byte)138, (byte)156, (byte)184, (byte)210,
(byte)157, (byte)184, (byte)154, (byte)131, (byte)128, (byte)110, (byte)12, (byte)85,
(byte)195, (byte)122, (byte)241, (byte)79, (byte)251, (byte)229, (byte)183, (byte)117,
(byte)21, (byte)123, (byte)133, (byte)142, (byte)220, (byte)153, (byte)9, (byte)59,
(byte)57, (byte)105, (byte)81, (byte)255, (byte)138, (byte)77, (byte)82, (byte)54,
(byte)62, (byte)216, (byte)38, (byte)249, (byte)208, (byte)17, (byte)197, (byte)49,
(byte)45, (byte)19, (byte)232, (byte)157, (byte)251, (byte)131, (byte)137, (byte)175,
(byte)72, (byte)126, (byte)43, (byte)229, (byte)69, (byte)179, (byte)117, (byte)82,
(byte)157, (byte)213, (byte)83, (byte)35, (byte)57, (byte)210, (byte)197, (byte)252,
(byte)171, (byte)143, (byte)194, (byte)11, (byte)47, (byte)163, (byte)6, (byte)253,
(byte)75, (byte)252, (byte)96, (byte)11, (byte)187, (byte)84, (byte)130, (byte)210,
(byte)7, (byte)121, (byte)78, (byte)91, (byte)79, (byte)57, (byte)251, (byte)138,
(byte)132, (byte)220, (byte)60, (byte)224, (byte)173, (byte)56, (byte)224, (byte)201 };
/** RFC RSA-OAEP wrapped compact serialization. */
private static final byte[] RFC_SERIALIZATION =
("eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ." +
"M2XxpbORKezKSzzQL_95-GjiudRBTqn_omS8z9xgoRb7L0Jw5UsEbxmtyHn2T71m" +
"rZLkjg4Mp8gbhYoltPkEOHvAopz25-vZ8C2e1cOaAo5WPcbSIuFcB4DjBOM3t0UA" +
"O6JHkWLuAEYoe58lcxIQneyKdaYSLbV9cKqoUoFQpvKWYRHZbfszIyfsa18rmgTj" +
"zrtLDTPnc09DSJE24aQ8w3i8RXEDthW9T1J6LsTH_vwHdwUgkI-tC2PNeGrnM-dN" +
"SfzF3Y7-lwcGy0FsdXkPXytvDV7y4pZeeUiQ-0VdibIN2AjjfW60nfrPuOjepMFG" +
"6BBBbR37pHcyzext9epOAQ." +
"48V1_ALb6US04U3b." +
"_e21tGGhac_peEFkLXr2dMPUZiUkrw." +
"7V5ZDko0v_mf2PAc4JMiUg").getBytes(UTF_8);
/** RFC RSA-OAEP plaintext. */
private static final byte[] RFC_PLAINTEXT =
("Live long and prosper.").getBytes(UTF_8);
/*{
(byte)76, (byte)105, (byte)118, (byte)101, (byte)32, (byte)108, (byte)111, (byte)110,
(byte)103, (byte)32, (byte)97, (byte)110, (byte)100, (byte)32, (byte)112, (byte)114,
(byte)111, (byte)115, (byte)112, (byte)101, (byte)114, (byte)46 };*/
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
/** JWE crypto context. */
private static ICryptoContext cryptoContext;
@BeforeClass
public static void setup() throws NoSuchAlgorithmException, MslEncodingException, MslCryptoException {
JsonWebEncryptionCryptoContextSuite.setup();
Security.addProvider(new BouncyCastleProvider());
cryptoContext = new JsonWebEncryptionCryptoContext(ctx, rsaCryptoContext, Encryption.A128GCM, Format.JWE_CS);
}
@AfterClass
public static void teardown() {
cryptoContext = null;
}
@Test
public void wrapUnwrap() throws MslCryptoException {
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
assertNotNull(wrapped);
assertFalse(Arrays.equals(data, wrapped));
final byte[] unwrapped = cryptoContext.unwrap(wrapped, encoder);
assertArrayEquals(data, unwrapped);
}
@Test
public void wrapUnwrapShort() throws MslCryptoException {
final byte[] data = new byte[3];
random.nextBytes(data);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
assertNotNull(wrapped);
assertFalse(Arrays.equals(data, wrapped));
final byte[] unwrapped = cryptoContext.unwrap(wrapped, encoder);
assertArrayEquals(data, unwrapped);
}
@Test
public void wrapUnwrapRfc() throws InvalidKeySpecException, NoSuchAlgorithmException, MslCryptoException {
final BigInteger modulus = new BigInteger(1, RFC_MODULUS);
final BigInteger publicExponent = new BigInteger(1, RFC_PUBLIC_EXPONENT);
final BigInteger privateExponent = new BigInteger(1, RFC_PRIVATE_EXPONENT);
final KeySpec privateKeySpec = new RSAPrivateKeySpec(modulus, privateExponent);
final KeySpec publicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
final KeyFactory factory = KeyFactory.getInstance("RSA");
final PrivateKey privateKey = factory.generatePrivate(privateKeySpec);
final PublicKey publicKey = factory.generatePublic(publicKeySpec);
final CekCryptoContext cekCryptoContext = new JsonWebEncryptionCryptoContext.RsaOaepCryptoContext(privateKey, publicKey);
final ICryptoContext cryptoContext = new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A256GCM, Format.JWE_CS);
final byte[] plaintext = cryptoContext.unwrap(RFC_SERIALIZATION, encoder);
assertNotNull(plaintext);
assertArrayEquals(RFC_PLAINTEXT, plaintext);
}
@Test
public void invalidSerialization() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = "x".getBytes(UTF_8);
cryptoContext.unwrap(wrapped, encoder);
}
@Test
public void shortSerialization() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String serialization = new String(wrapped, UTF_8);
final String shortSerialization = serialization.substring(0, serialization.lastIndexOf('.'));
final byte[] shortWrapped = shortSerialization.getBytes(UTF_8);
cryptoContext.unwrap(shortWrapped, encoder);
}
@Test
public void longSerialization() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] longWrapped = Arrays.copyOf(wrapped, 2 * wrapped.length);
System.arraycopy(wrapped, 0, longWrapped, wrapped.length, wrapped.length);
cryptoContext.unwrap(longWrapped, encoder);
}
@Test
public void missingHeader() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, "");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidHeader() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingCek() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, ECEK_INDEX, "");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidCek() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_BAD_PADDING);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, ECEK_INDEX, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingIv() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, IV_INDEX, "");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidIv() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, IV_INDEX, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingCiphertext() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, CIPHERTEXT_INDEX, "");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidCiphertext() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, CIPHERTEXT_INDEX, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingAuthenticationTag() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, AUTHENTICATION_TAG_INDEX, "");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidAuthenticationTag() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_ALGORITHM_PARAMS);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, AUTHENTICATION_TAG_INDEX, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void wrongAuthenticationTag() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] at = new byte[16];
random.nextBytes(at);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, AUTHENTICATION_TAG_INDEX, MslEncoderUtils.b64urlEncode(at));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingAlgorithm() throws MslEncoderException, MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String wrappedB64 = new String(wrapped, UTF_8);
final String headerB64 = wrappedB64.substring(0, wrappedB64.indexOf('.'));
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
assertNotNull(header.remove(KEY_ALGORITHM));
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidAlgorithm() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String wrappedB64 = new String(wrapped, UTF_8);
final String headerB64 = wrappedB64.substring(0, wrappedB64.indexOf('.'));
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
header.put(KEY_ALGORITHM, "x");
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingEncryption() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String wrappedB64 = new String(wrapped, UTF_8);
final String headerB64 = wrappedB64.substring(0, wrappedB64.indexOf('.'));
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
assertNotNull(header.remove(KEY_ENCRYPTION));
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidEncryption() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String wrappedB64 = new String(wrapped, UTF_8);
final String headerB64 = wrappedB64.substring(0, wrappedB64.indexOf('.'));
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
header.put(KEY_ENCRYPTION, "x");
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void badCek() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] ecek = new byte[137];
random.nextBytes(ecek);
final byte[] badWrapped = replace(wrapped, ECEK_INDEX, MslEncoderUtils.b64urlEncode(ecek));
cryptoContext.unwrap(badWrapped, encoder);
}
@Test
public void badIv() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] iv = new byte[31];
random.nextBytes(iv);
final byte[] badWrapped = replace(wrapped, IV_INDEX, MslEncoderUtils.b64urlEncode(iv));
cryptoContext.unwrap(badWrapped, encoder);
}
@Test
public void wrongCek() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] cek = new byte[16];
random.nextBytes(cek);
final byte[] ecek = rsaCryptoContext.encrypt(cek, encoder, ENCODER_FORMAT);
final byte[] wrongWrapped = replace(wrapped, ECEK_INDEX, MslEncoderUtils.b64urlEncode(ecek));
cryptoContext.unwrap(wrongWrapped, encoder);
}
@Test
public void wrongIv() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] iv = new byte[16];
random.nextBytes(iv);
final byte[] wrongWrapped = replace(wrapped, IV_INDEX, MslEncoderUtils.b64urlEncode(iv));
cryptoContext.unwrap(wrongWrapped, encoder);
}
}
/** RSA-OAEP JSON serialization unit tests. */
public static class RsaOaepJsonSerialization {
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
/** JWE crypto context. */
private static ICryptoContext cryptoContext;
@BeforeClass
public static void setup() throws NoSuchAlgorithmException, MslEncodingException, MslCryptoException {
JsonWebEncryptionCryptoContextSuite.setup();
Security.addProvider(new BouncyCastleProvider());
cryptoContext = new JsonWebEncryptionCryptoContext(ctx, rsaCryptoContext, Encryption.A128GCM, Format.JWE_JS);
}
@AfterClass
public static void teardown() {
cryptoContext = null;
}
@Test
public void wrapUnwrap() throws MslCryptoException {
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
assertNotNull(wrapped);
assertFalse(Arrays.equals(data, wrapped));
final byte[] unwrapped = cryptoContext.unwrap(wrapped, encoder);
assertArrayEquals(data, unwrapped);
}
@Test
public void wrapUnwrapShort() throws MslCryptoException {
final byte[] data = new byte[3];
random.nextBytes(data);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
assertNotNull(wrapped);
assertFalse(Arrays.equals(data, wrapped));
final byte[] unwrapped = cryptoContext.unwrap(wrapped, encoder);
assertArrayEquals(data, unwrapped);
}
@Test
public void invalidSerialization() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = "x".getBytes(UTF_8);
cryptoContext.unwrap(wrapped, encoder);
}
@Test
public void missingRecipients() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_RECIPIENTS);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidRecipients() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_RECIPIENTS, "x");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingRecipient() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_RECIPIENTS, encoder.createArray());
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidRecipient() throws MslEncoderException, MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final MslArray value = new MslArray(Arrays.asList("x"));
final byte[] missingWrapped = replace(wrapped, KEY_RECIPIENTS, value);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingHeader() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_HEADER);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidHeader() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_HEADER, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingCek() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_ENCRYPTED_KEY);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidCek() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_BAD_PADDING);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_ENCRYPTED_KEY, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingIv() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_INITIALIZATION_VECTOR);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidIv() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_INITIALIZATION_VECTOR, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingCiphertext() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_CIPHERTEXT);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidCiphertext() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_CIPHERTEXT, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingAuthenticationTag() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_INTEGRITY_VALUE);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidAuthenticationTag() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_ALGORITHM_PARAMS);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_INTEGRITY_VALUE, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void wrongAuthenticationTag() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] at = new byte[16];
random.nextBytes(at);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_INTEGRITY_VALUE, MslEncoderUtils.b64urlEncode(at));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingAlgorithm() throws MslEncoderException, MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String headerB64 = get(wrapped, KEY_HEADER);
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
assertNotNull(header.remove(KEY_ALGORITHM));
final byte[] missingWrapped = replace(wrapped, KEY_HEADER, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidAlgorithm() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String headerB64 = get(wrapped, KEY_HEADER);
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
header.put(KEY_ALGORITHM, "x");
final byte[] missingWrapped = replace(wrapped, KEY_HEADER, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingEncryption() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String headerB64 = get(wrapped, KEY_HEADER);
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
assertNotNull(header.remove(KEY_ENCRYPTION));
final byte[] missingWrapped = replace(wrapped, KEY_HEADER, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidEncryption() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String headerB64 = get(wrapped, KEY_HEADER);
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
header.put(KEY_ENCRYPTION, "x");
final byte[] missingWrapped = replace(wrapped, KEY_HEADER, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void badCek() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] ecek = new byte[137];
random.nextBytes(ecek);
final byte[] badWrapped = replace(wrapped, KEY_ENCRYPTED_KEY, MslEncoderUtils.b64urlEncode(ecek));
cryptoContext.unwrap(badWrapped, encoder);
}
@Test
public void badIv() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] iv = new byte[31];
random.nextBytes(iv);
final byte[] badWrapped = replace(wrapped, KEY_INITIALIZATION_VECTOR, MslEncoderUtils.b64urlEncode(iv));
cryptoContext.unwrap(badWrapped, encoder);
}
@Test
public void wrongCek() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] cek = new byte[16];
random.nextBytes(cek);
final byte[] ecek = rsaCryptoContext.encrypt(cek, encoder, ENCODER_FORMAT);
final byte[] wrongWrapped = replace(wrapped, KEY_ENCRYPTED_KEY, MslEncoderUtils.b64urlEncode(ecek));
cryptoContext.unwrap(wrongWrapped, encoder);
}
@Test
public void wrongIv() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] iv = new byte[16];
random.nextBytes(iv);
final byte[] wrongWrapped = replace(wrapped, KEY_INITIALIZATION_VECTOR, MslEncoderUtils.b64urlEncode(iv));
cryptoContext.unwrap(wrongWrapped, encoder);
}
}
/** AES key wrap compact serialization unit tests. */
public static class AesKwCompactSerialization {
/** RFC AES key wrap symmetric key. */
private static final byte[] RFC_KEY = {
(byte)25, (byte)172, (byte)32, (byte)130, (byte)225, (byte)114, (byte)26, (byte)181,
(byte)138, (byte)106, (byte)254, (byte)192, (byte)95, (byte)133, (byte)74, (byte)82 };
/** RFC AES key wrap wrapped compact serialization. */
private static final byte[] RFC_SERIALIZATION =
("eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4R0NNIn0." +
"pP_7AUDIQcgixVGPK9PwJr-htXV3RCxQ." +
"_dxQGaaYsqhhY0NZ." +
"4wxZhLkQ-F2RVzWCX3M-aIpgbUd806VnymMVwQTiVOX-apDxJ1aUhKBoWOjkbVUH" +
"VlCGaqYYXMfSvJm72kXj." +
"miNQayWUUQZnBDzOq6VxQw").getBytes(UTF_8);
/** RFC AES key wrap plaintext. */
private static final byte[] RFC_PLAINTEXT =
("The true sign of intelligence is not knowledge but imagination.").getBytes(UTF_8);
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
/** JWE crypto context. */
private static ICryptoContext cryptoContext;
@BeforeClass
public static void setup() throws NoSuchAlgorithmException, MslEncodingException, MslCryptoException {
JsonWebEncryptionCryptoContextSuite.setup();
Security.addProvider(new BouncyCastleProvider());
cryptoContext = new JsonWebEncryptionCryptoContext(ctx, aesCryptoContext, Encryption.A256GCM, Format.JWE_CS);
}
@AfterClass
public static void teardown() {
cryptoContext = null;
}
@Test
public void wrapUnwrap() throws MslCryptoException {
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
assertNotNull(wrapped);
assertFalse(Arrays.equals(data, wrapped));
final byte[] unwrapped = cryptoContext.unwrap(wrapped, encoder);
assertArrayEquals(data, unwrapped);
}
@Test
public void wrapUnwrapShort() throws MslCryptoException {
final byte[] data = new byte[3];
random.nextBytes(data);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
assertNotNull(wrapped);
assertFalse(Arrays.equals(data, wrapped));
final byte[] unwrapped = cryptoContext.unwrap(wrapped, encoder);
assertArrayEquals(data, unwrapped);
}
@Test
public void wrapUnwrapRfc() throws InvalidKeySpecException, NoSuchAlgorithmException, MslCryptoException {
final SecretKey key = new SecretKeySpec(RFC_KEY, JcaAlgorithm.AESKW);
final CekCryptoContext cekCryptoContext = new JsonWebEncryptionCryptoContext.AesKwCryptoContext(key);
final ICryptoContext cryptoContext = new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_CS);
final byte[] plaintext = cryptoContext.unwrap(RFC_SERIALIZATION, encoder);
assertNotNull(plaintext);
assertArrayEquals(RFC_PLAINTEXT, plaintext);
}
@Test
public void invalidSerialization() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = "x".getBytes(UTF_8);
cryptoContext.unwrap(wrapped, encoder);
}
@Test
public void shortSerialization() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String serialization = new String(wrapped, UTF_8);
final String shortSerialization = serialization.substring(0, serialization.lastIndexOf('.'));
final byte[] shortWrapped = shortSerialization.getBytes(UTF_8);
cryptoContext.unwrap(shortWrapped, encoder);
}
@Test
public void longSerialization() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] longWrapped = Arrays.copyOf(wrapped, 2 * wrapped.length);
System.arraycopy(wrapped, 0, longWrapped, wrapped.length, wrapped.length);
cryptoContext.unwrap(longWrapped, encoder);
}
@Test
public void missingHeader() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, "");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidHeader() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingCek() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, ECEK_INDEX, "");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidCek() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_SYMMETRIC_KEY);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, ECEK_INDEX, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingIv() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, IV_INDEX, "");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidIv() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, IV_INDEX, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingCiphertext() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, CIPHERTEXT_INDEX, "");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidCiphertext() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, CIPHERTEXT_INDEX, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingAuthenticationTag() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, AUTHENTICATION_TAG_INDEX, "");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidAuthenticationTag() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_ALGORITHM_PARAMS);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, AUTHENTICATION_TAG_INDEX, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void wrongAuthenticationTag() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] at = new byte[16];
random.nextBytes(at);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, AUTHENTICATION_TAG_INDEX, MslEncoderUtils.b64urlEncode(at));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingAlgorithm() throws MslEncoderException, MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String wrappedB64 = new String(wrapped, UTF_8);
final String headerB64 = wrappedB64.substring(0, wrappedB64.indexOf('.'));
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
assertNotNull(header.remove(KEY_ALGORITHM));
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidAlgorithm() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String wrappedB64 = new String(wrapped, UTF_8);
final String headerB64 = wrappedB64.substring(0, wrappedB64.indexOf('.'));
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
header.put(KEY_ALGORITHM, "x");
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingEncryption() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String wrappedB64 = new String(wrapped, UTF_8);
final String headerB64 = wrappedB64.substring(0, wrappedB64.indexOf('.'));
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
assertNotNull(header.remove(KEY_ENCRYPTION));
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidEncryption() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String wrappedB64 = new String(wrapped, UTF_8);
final String headerB64 = wrappedB64.substring(0, wrappedB64.indexOf('.'));
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
header.put(KEY_ENCRYPTION, "x");
final byte[] missingWrapped = replace(wrapped, HEADER_INDEX, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void badCek() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_SYMMETRIC_KEY);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] ecek = new byte[137];
random.nextBytes(ecek);
final byte[] badWrapped = replace(wrapped, ECEK_INDEX, MslEncoderUtils.b64urlEncode(ecek));
cryptoContext.unwrap(badWrapped, encoder);
}
@Test
public void badIv() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] iv = new byte[31];
random.nextBytes(iv);
final byte[] badWrapped = replace(wrapped, IV_INDEX, MslEncoderUtils.b64urlEncode(iv));
cryptoContext.unwrap(badWrapped, encoder);
}
@Test
public void wrongCek() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_SYMMETRIC_KEY);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] cek = new byte[16];
random.nextBytes(cek);
final byte[] ecek = aesCryptoContext.encrypt(cek, encoder, ENCODER_FORMAT);
final byte[] wrongWrapped = replace(wrapped, ECEK_INDEX, MslEncoderUtils.b64urlEncode(ecek));
cryptoContext.unwrap(wrongWrapped, encoder);
}
@Test
public void wrongIv() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] iv = new byte[16];
random.nextBytes(iv);
final byte[] wrongWrapped = replace(wrapped, IV_INDEX, MslEncoderUtils.b64urlEncode(iv));
cryptoContext.unwrap(wrongWrapped, encoder);
}
}
/** AES key wrap JSON serialization unit tests. */
public static class AesKwJsonSerialization {
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
/** JWE crypto context. */
private static ICryptoContext cryptoContext;
@BeforeClass
public static void setup() throws NoSuchAlgorithmException, MslEncodingException, MslCryptoException {
JsonWebEncryptionCryptoContextSuite.setup();
Security.addProvider(new BouncyCastleProvider());
cryptoContext = new JsonWebEncryptionCryptoContext(ctx, aesCryptoContext, Encryption.A256GCM, Format.JWE_JS);
}
@AfterClass
public static void teardown() {
cryptoContext = null;
}
@Test
public void wrapUnwrap() throws MslCryptoException {
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
assertNotNull(wrapped);
assertFalse(Arrays.equals(data, wrapped));
final byte[] unwrapped = cryptoContext.unwrap(wrapped, encoder);
assertArrayEquals(data, unwrapped);
}
@Test
public void wrapUnwrapShort() throws MslCryptoException {
final byte[] data = new byte[3];
random.nextBytes(data);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
assertNotNull(wrapped);
assertFalse(Arrays.equals(data, wrapped));
final byte[] unwrapped = cryptoContext.unwrap(wrapped, encoder);
assertArrayEquals(data, unwrapped);
}
@Test
public void invalidSerialization() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = "x".getBytes(UTF_8);
cryptoContext.unwrap(wrapped, encoder);
}
@Test
public void missingRecipients() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_RECIPIENTS);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidRecipients() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_RECIPIENTS, "x");
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingRecipient() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_RECIPIENTS, encoder.createArray());
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidRecipient() throws MslEncoderException, MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final MslArray value = new MslArray(Arrays.asList("x"));
final byte[] missingWrapped = replace(wrapped, KEY_RECIPIENTS, value);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingHeader() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_HEADER);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidHeader() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_HEADER, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingCek() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_ENCRYPTED_KEY);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidCek() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_SYMMETRIC_KEY);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_ENCRYPTED_KEY, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingIv() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_INITIALIZATION_VECTOR);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidIv() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_INITIALIZATION_VECTOR, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingCiphertext() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_CIPHERTEXT);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidCiphertext() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_CIPHERTEXT, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingAuthenticationTag() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = remove(wrapped, KEY_INTEGRITY_VALUE);
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidAuthenticationTag() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_ALGORITHM_PARAMS);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_INTEGRITY_VALUE, MslEncoderUtils.b64urlEncode("x"));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void wrongAuthenticationTag() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] at = new byte[16];
random.nextBytes(at);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] missingWrapped = replace(wrapped, KEY_INTEGRITY_VALUE, MslEncoderUtils.b64urlEncode(at));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingAlgorithm() throws MslEncoderException, MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String headerB64 = get(wrapped, KEY_HEADER);
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
assertNotNull(header.remove(KEY_ALGORITHM));
final byte[] missingWrapped = replace(wrapped, KEY_HEADER, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidAlgorithm() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String headerB64 = get(wrapped, KEY_HEADER);
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
header.put(KEY_ALGORITHM, "x");
final byte[] missingWrapped = replace(wrapped, KEY_HEADER, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void missingEncryption() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String headerB64 = get(wrapped, KEY_HEADER);
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
assertNotNull(header.remove(KEY_ENCRYPTION));
final byte[] missingWrapped = replace(wrapped, KEY_HEADER, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void invalidEncryption() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_PARSE_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final String headerB64 = get(wrapped, KEY_HEADER);
final MslObject header = encoder.parseObject(MslEncoderUtils.b64urlDecode(headerB64));
header.put(KEY_ENCRYPTION, "x");
final byte[] missingWrapped = replace(wrapped, KEY_HEADER, MslEncoderUtils.b64urlEncode(encoder.encodeObject(header, MslEncoderFormat.JSON)));
cryptoContext.unwrap(missingWrapped, encoder);
}
@Test
public void badCek() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_SYMMETRIC_KEY);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] ecek = new byte[137];
random.nextBytes(ecek);
final byte[] badWrapped = replace(wrapped, KEY_ENCRYPTED_KEY, MslEncoderUtils.b64urlEncode(ecek));
cryptoContext.unwrap(badWrapped, encoder);
}
@Test
public void badIv() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] iv = new byte[31];
random.nextBytes(iv);
final byte[] badWrapped = replace(wrapped, KEY_INITIALIZATION_VECTOR, MslEncoderUtils.b64urlEncode(iv));
cryptoContext.unwrap(badWrapped, encoder);
}
@Test
public void wrongCek() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_SYMMETRIC_KEY);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] cek = new byte[16];
random.nextBytes(cek);
final byte[] ecek = aesCryptoContext.encrypt(cek, encoder, ENCODER_FORMAT);
final byte[] wrongWrapped = replace(wrapped, KEY_ENCRYPTED_KEY, MslEncoderUtils.b64urlEncode(ecek));
cryptoContext.unwrap(wrongWrapped, encoder);
}
@Test
public void wrongIv() throws MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_ERROR);
final byte[] wrapped = cryptoContext.wrap(data, encoder, ENCODER_FORMAT);
final byte[] iv = new byte[16];
random.nextBytes(iv);
final byte[] wrongWrapped = replace(wrapped, KEY_INITIALIZATION_VECTOR, MslEncoderUtils.b64urlEncode(iv));
cryptoContext.unwrap(wrongWrapped, encoder);
}
}
/** JSON Web Encryption unit tests. */
public static class JWE {
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
/** JWE crypto context. */
private static ICryptoContext cryptoContext;
@BeforeClass
public static void setup() throws NoSuchAlgorithmException, MslEncodingException, MslCryptoException {
JsonWebEncryptionCryptoContextSuite.setup();
Security.addProvider(new BouncyCastleProvider());
cryptoContext = new JsonWebEncryptionCryptoContext(ctx, rsaCryptoContext, Encryption.A128GCM, Format.JWE_CS);
}
@AfterClass
public static void teardown() {
cryptoContext = null;
}
@Test
public void encrypt() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.ENCRYPT_NOT_SUPPORTED);
cryptoContext.encrypt(new byte[0], encoder, ENCODER_FORMAT);
}
@Test
public void decrypt() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.DECRYPT_NOT_SUPPORTED);
cryptoContext.decrypt(new byte[0], encoder);
}
@Test
public void sign() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.SIGN_NOT_SUPPORTED);
cryptoContext.sign(new byte[0], encoder, ENCODER_FORMAT);
}
@Test
public void verify() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.VERIFY_NOT_SUPPORTED);
cryptoContext.verify(new byte[0], new byte[0], encoder);
}
@Test
public void algorithmMismatch() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_ALGORITHM_MISMATCH);
final ICryptoContext cryptoContextA = new JsonWebEncryptionCryptoContext(ctx, rsaCryptoContext, Encryption.A128GCM, Format.JWE_CS);
final ICryptoContext cryptoContextB = new JsonWebEncryptionCryptoContext(ctx, aesCryptoContext, Encryption.A128GCM, Format.JWE_CS);
final byte[] wrapped = cryptoContextA.wrap(data, encoder, ENCODER_FORMAT);
cryptoContextB.unwrap(wrapped, encoder);
}
@Test
public void encryptionMismatch() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.JWE_ALGORITHM_MISMATCH);
final ICryptoContext cryptoContextA = new JsonWebEncryptionCryptoContext(ctx, rsaCryptoContext, Encryption.A128GCM, Format.JWE_CS);
final ICryptoContext cryptoContextB = new JsonWebEncryptionCryptoContext(ctx, rsaCryptoContext, Encryption.A256GCM, Format.JWE_CS);
final byte[] wrapped = cryptoContextA.wrap(data, encoder, ENCODER_FORMAT);
cryptoContextB.unwrap(wrapped, encoder);
}
}
}
| 1,791 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/crypto/SessionCryptoContextTest.java
|
/**
* Copyright (c) 2012-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.crypto;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
import javax.crypto.SecretKey;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
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.EntityAuthenticationScheme;
import com.netflix.msl.entityauth.MockPresharedAuthenticationFactory;
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.test.ExpectedMslException;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.util.MockMslContext;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslTestUtils;
/**
* Session crypto context unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
public class SessionCryptoContextTest {
/** Key ciphertext. */
private final static String KEY_CIPHERTEXT = "ciphertext";
/** MSL encoder format. */
private static final MslEncoderFormat ENCODER_FORMAT = MslEncoderFormat.JSON;
/**
* @param ctx MSL context.
* @return a new master token.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
*/
private static MasterToken getTrustedMasterToken(final MslContext ctx) throws MslEncodingException, MslCryptoException {
final Date renewalWindow = new Date(System.currentTimeMillis() + 1000);
final Date expiration = new Date(System.currentTimeMillis() + 2000);
final String identity = MockPresharedAuthenticationFactory.PSK_ESN;
final SecretKey encryptionKey = MockPresharedAuthenticationFactory.KPE;
final SecretKey signatureKey = MockPresharedAuthenticationFactory.KPH;
final MasterToken masterToken = new MasterToken(ctx, renewalWindow, expiration, 1L, 1L, null, identity, encryptionKey, signatureKey);
return masterToken;
}
/**
* @param ctx MSL context.
* @param encryptionKey master token encryption key.
* @param signatureKey master token signature key.
* @return a new master token.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslException if the master token is constructed incorrectly.
* @throws MslEncoderException if there is an error editing the data.
*/
private static MasterToken getUntrustedMasterToken(final MslContext ctx, final SecretKey encryptionKey, final SecretKey signatureKey) throws MslEncodingException, MslCryptoException, MslException, MslEncoderException {
final Date renewalWindow = new Date(System.currentTimeMillis() + 1000);
final Date expiration = new Date(System.currentTimeMillis() + 2000);
final String identity = MockPresharedAuthenticationFactory.PSK_ESN;
final MasterToken masterToken = new MasterToken(ctx, renewalWindow, expiration, 1L, 1L, null, identity, encryptionKey, signatureKey);
final MslObject mo = MslTestUtils.toMslObject(encoder, masterToken);
final byte[] signature = mo.getBytes("signature");
++signature[1];
mo.put("signature", signature);
final MasterToken untrustedMasterToken = new MasterToken(ctx, mo);
return untrustedMasterToken;
}
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
/** MSL context. */
private static MslContext ctx;
/** MSL encoder factory. */
private static MslEncoderFactory encoder;
/** Random. */
private static Random random;
@BeforeClass
public static void setup() throws MslEncodingException, MslCryptoException {
ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
encoder = ctx.getMslEncoderFactory();
random = new Random();
}
@AfterClass
public static void teardown() {
random = null;
encoder = null;
ctx = null;
}
@Test
public void untrusted() throws MslEncoderException, MslException {
thrown.expect(MslMasterTokenException.class);
thrown.expectMslError(MslError.MASTERTOKEN_UNTRUSTED);
final SecretKey encryptionKey = MockPresharedAuthenticationFactory.KPE;
final SecretKey signatureKey = MockPresharedAuthenticationFactory.KPH;
final MasterToken masterToken = getUntrustedMasterToken(ctx, encryptionKey, signatureKey);
new SessionCryptoContext(ctx, masterToken);
}
@Test
public void encryptDecrypt() throws MslEncodingException, MslCryptoException, MslMasterTokenException {
final MasterToken masterToken = getTrustedMasterToken(ctx);
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] ciphertextA = cryptoContext.encrypt(messageA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(messageA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.decrypt(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(messageA, plaintextA);
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] ciphertextB = cryptoContext.encrypt(messageB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(messageB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.decrypt(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(messageB, plaintextB);
}
@Test
public void encryptDecryptKeys() throws MslEncoderException, MslException {
final String identity = MockPresharedAuthenticationFactory.PSK_ESN;
final SecretKey encryptionKey = MockPresharedAuthenticationFactory.KPE;
final SecretKey signatureKey = MockPresharedAuthenticationFactory.KPH;
final MasterToken masterToken = getUntrustedMasterToken(ctx, encryptionKey, signatureKey);
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken, identity, encryptionKey, signatureKey);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] ciphertextA = cryptoContext.encrypt(messageA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(messageA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.decrypt(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(messageA, plaintextA);
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] ciphertextB = cryptoContext.encrypt(messageB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(messageB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.decrypt(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(messageB, plaintextB);
}
@Test
public void invalidCiphertext() throws MslEncodingException, MslCryptoException, MslEncoderException, MslMasterTokenException, UnsupportedEncodingException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_BAD_PADDING);
final MasterToken masterToken = getTrustedMasterToken(ctx);
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] data = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
final MslObject envelopeMo = encoder.parseObject(data);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(envelopeMo);
final byte[] ciphertext = envelope.getCiphertext();
++ciphertext[ciphertext.length - 1];
final MslCiphertextEnvelope shortEnvelope = new MslCiphertextEnvelope(envelope.getKeyId(), envelope.getIv(), ciphertext);
cryptoContext.decrypt(shortEnvelope.toMslEncoding(encoder, ENCODER_FORMAT), encoder);
}
// I want this to catch the ArrayIndexOutOfBounds
// MslError.INSUFFICIENT_CIPHERTEXT but I'm not sure how to trigger it
// anymore.
@Test
public void insufficientCiphertext() throws MslCryptoException, MslEncoderException, MslEncodingException, MslMasterTokenException, UnsupportedEncodingException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE);
final MasterToken masterToken = getTrustedMasterToken(ctx);
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] data = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
final MslObject envelopeMo = encoder.parseObject(data);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(envelopeMo);
final byte[] ciphertext = envelope.getCiphertext();
final byte[] shortCiphertext = Arrays.copyOf(ciphertext, ciphertext.length - 1);
final MslCiphertextEnvelope shortEnvelope = new MslCiphertextEnvelope(envelope.getKeyId(), envelope.getIv(), shortCiphertext);
cryptoContext.decrypt(shortEnvelope.toMslEncoding(encoder, ENCODER_FORMAT), encoder);
}
@Test
public void notEnvelope() throws MslCryptoException, MslEncoderException, MslEncodingException, MslMasterTokenException, UnsupportedEncodingException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR);
final MasterToken masterToken = getTrustedMasterToken(ctx);
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] data = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
final MslObject envelopeMo = encoder.parseObject(data);
envelopeMo.remove(KEY_CIPHERTEXT);
cryptoContext.decrypt(encoder.encodeObject(envelopeMo, ENCODER_FORMAT), encoder);
}
@Test
public void corruptEnvelope() throws MslCryptoException, MslEncodingException, MslMasterTokenException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR);
final MasterToken masterToken = getTrustedMasterToken(ctx);
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] data = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
data[0] = 0;
cryptoContext.decrypt(data, encoder);
}
@Test
public void encryptDecryptNullEncryption() throws MslEncoderException, MslException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.ENCRYPT_NOT_SUPPORTED);
final String identity = MockPresharedAuthenticationFactory.PSK_ESN;
final SecretKey encryptionKey = MockPresharedAuthenticationFactory.KPE;
final SecretKey signatureKey = MockPresharedAuthenticationFactory.KPH;
final MasterToken masterToken;
try {
masterToken = getUntrustedMasterToken(ctx, encryptionKey, signatureKey);
} catch (final MslCryptoException e) {
fail(e.getMessage());
return;
}
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken, identity, null, signatureKey);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
cryptoContext.encrypt(messageA, encoder, ENCODER_FORMAT);
}
@Test
public void encryptDecryptNullSignature() throws MslEncoderException, MslException {
final String identity = MockPresharedAuthenticationFactory.PSK_ESN;
final SecretKey encryptionKey = MockPresharedAuthenticationFactory.KPE;
final SecretKey signatureKey = MockPresharedAuthenticationFactory.KPH;
final MasterToken masterToken = getUntrustedMasterToken(ctx, encryptionKey, signatureKey);
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken, identity, encryptionKey, null);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] ciphertextA = cryptoContext.encrypt(messageA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(messageA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.decrypt(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(messageA, plaintextA);
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] ciphertextB = cryptoContext.encrypt(messageB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(messageB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.decrypt(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(messageB, plaintextB);
}
@Test
public void encryptDecryptIdMismatch() throws MslEncoderException, MslException {
final String identity = MockPresharedAuthenticationFactory.PSK_ESN;
final SecretKey encryptionKey = MockPresharedAuthenticationFactory.KPE;
final SecretKey signatureKey = MockPresharedAuthenticationFactory.KPH;
final MasterToken masterToken;
try {
masterToken = getUntrustedMasterToken(ctx, encryptionKey, signatureKey);
} catch (final MslCryptoException e) {
fail(e.getMessage());
return;
}
// With untrusted master tokens, there is no way of verifying the
// identity provided against the internals of the master token. So this
// test makes use of two session crypto contexts with different
// identities.
final SessionCryptoContext cryptoContextA = new SessionCryptoContext(ctx, masterToken, identity + "A", encryptionKey, signatureKey);
final SessionCryptoContext cryptoContextB = new SessionCryptoContext(ctx, masterToken, identity + "B", encryptionKey, signatureKey);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertThat(message, is(not(ciphertext)));
final byte[] plaintext = cryptoContextB.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptDecryptKeysMismatch() throws MslEncoderException, MslException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_BAD_PADDING);
final String identity = MockPresharedAuthenticationFactory.PSK_ESN;
final SecretKey encryptionKeyA = MockPresharedAuthenticationFactory.KPE;
final SecretKey signatureKeyA = MockPresharedAuthenticationFactory.KPH;
final SecretKey encryptionKeyB = MockPresharedAuthenticationFactory.KPE2;
final SecretKey signatureKeyB = MockPresharedAuthenticationFactory.KPH2;
final MasterToken masterTokenA, masterTokenB;
try {
masterTokenA = getUntrustedMasterToken(ctx, encryptionKeyA, signatureKeyA);
masterTokenB = getUntrustedMasterToken(ctx, encryptionKeyB, signatureKeyB);
} catch (final MslCryptoException e) {
fail(e.getMessage());
return;
}
final SessionCryptoContext cryptoContextA = new SessionCryptoContext(ctx, masterTokenA, identity, encryptionKeyA, signatureKeyA);
final SessionCryptoContext cryptoContextB = new SessionCryptoContext(ctx, masterTokenB, identity, encryptionKeyB, signatureKeyB);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] ciphertext;
try {
ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
} catch (final MslCryptoException e) {
fail(e.getMessage());
return;
}
cryptoContextB.decrypt(ciphertext, encoder);
}
@Test
public void signVerify() throws MslCryptoException, MslEncodingException, MslMasterTokenException {
final MasterToken masterToken = getTrustedMasterToken(ctx);
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] signatureA = cryptoContext.sign(messageA, encoder, ENCODER_FORMAT);
assertNotNull(signatureA);
assertTrue(signatureA.length > 0);
assertThat(messageA, is(not(signatureA)));
assertTrue(cryptoContext.verify(messageA, signatureA, encoder));
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] signatureB = cryptoContext.sign(messageB, encoder, ENCODER_FORMAT);
assertTrue(signatureB.length > 0);
assertThat(signatureA, is(not(signatureB)));
assertTrue(cryptoContext.verify(messageB, signatureB, encoder));
assertFalse(cryptoContext.verify(messageB, signatureA, encoder));
}
@Test
public void signVerifyContextMismatch() throws MslEncoderException, MslException {
final String identity = MockPresharedAuthenticationFactory.PSK_ESN;
final SecretKey encryptionKeyA = MockPresharedAuthenticationFactory.KPE;
final SecretKey signatureKeyA = MockPresharedAuthenticationFactory.KPH;
final SecretKey encryptionKeyB = MockPresharedAuthenticationFactory.KPE2;
final SecretKey signatureKeyB = MockPresharedAuthenticationFactory.KPH2;
final MasterToken masterTokenA, masterTokenB;
try {
masterTokenA = getUntrustedMasterToken(ctx, encryptionKeyA, signatureKeyA);
masterTokenB = getUntrustedMasterToken(ctx, encryptionKeyB, signatureKeyB);
} catch (final MslCryptoException e) {
fail(e.getMessage());
return;
}
final SessionCryptoContext cryptoContextA = new SessionCryptoContext(ctx, masterTokenA, identity, encryptionKeyA, signatureKeyA);
final SessionCryptoContext cryptoContextB = new SessionCryptoContext(ctx, masterTokenB, identity, encryptionKeyB, signatureKeyB);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] signature = cryptoContextA.sign(message, encoder, ENCODER_FORMAT);
assertFalse(cryptoContextB.verify(message, signature, encoder));
}
@Test
public void signVerifyKeys() throws MslEncoderException, MslException {
final String identity = MockPresharedAuthenticationFactory.PSK_ESN;
final SecretKey encryptionKey = MockPresharedAuthenticationFactory.KPE;
final SecretKey signatureKey = MockPresharedAuthenticationFactory.KPH;
final MasterToken masterToken = getUntrustedMasterToken(ctx, encryptionKey, signatureKey);
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken, identity, encryptionKey, signatureKey);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] signatureA = cryptoContext.sign(messageA, encoder, ENCODER_FORMAT);
assertNotNull(signatureA);
assertTrue(signatureA.length > 0);
assertThat(messageA, is(not(signatureA)));
assertTrue(cryptoContext.verify(messageA, signatureA, encoder));
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] signatureB = cryptoContext.sign(messageB, encoder, ENCODER_FORMAT);
assertTrue(signatureB.length > 0);
assertThat(signatureA, is(not(signatureB)));
assertTrue(cryptoContext.verify(messageB, signatureB, encoder));
assertFalse(cryptoContext.verify(messageB, signatureA, encoder));
}
@Test
public void signVerifyNullEncryption() throws MslEncoderException, MslException {
final String identity = MockPresharedAuthenticationFactory.PSK_ESN;
final SecretKey encryptionKey = MockPresharedAuthenticationFactory.KPE;
final SecretKey signatureKey = MockPresharedAuthenticationFactory.KPH;
final MasterToken masterToken = getUntrustedMasterToken(ctx, encryptionKey, signatureKey);
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken, identity, null, signatureKey);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] signatureA = cryptoContext.sign(messageA, encoder, ENCODER_FORMAT);
assertNotNull(signatureA);
assertTrue(signatureA.length > 0);
assertThat(messageA, is(not(signatureA)));
assertTrue(cryptoContext.verify(messageA, signatureA, encoder));
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] signatureB = cryptoContext.sign(messageB, encoder, ENCODER_FORMAT);
assertTrue(signatureB.length > 0);
assertThat(signatureA, is(not(signatureB)));
assertTrue(cryptoContext.verify(messageB, signatureB, encoder));
assertFalse(cryptoContext.verify(messageB, signatureA, encoder));
}
@Test
public void verifyNullSignature() throws MslEncoderException, MslException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.SIGN_NOT_SUPPORTED);
final String identity = MockPresharedAuthenticationFactory.PSK_ESN;
final SecretKey encryptionKey = MockPresharedAuthenticationFactory.KPE;
final SecretKey signatureKey = MockPresharedAuthenticationFactory.KPH;
final MasterToken masterToken;
try {
masterToken = getUntrustedMasterToken(ctx, encryptionKey, signatureKey);
} catch (final MslCryptoException e) {
fail(e.getMessage());
return;
}
final SessionCryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken, identity, encryptionKey, null);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
cryptoContext.sign(messageA, encoder, ENCODER_FORMAT);
}
}
| 1,792 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/crypto/EccCryptoContextSuite.java
|
/**
* Copyright (c) 2012-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.crypto;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.util.Random;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.math.ec.ECCurve;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.crypto.EccCryptoContext.Mode;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.test.ExpectedMslException;
import com.netflix.msl.util.MockMslContext;
import com.netflix.msl.util.MslContext;
/**
* ECC crypto context unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
@RunWith(Suite.class)
@SuiteClasses({EccCryptoContextSuite.EncryptDecrypt.class,
EccCryptoContextSuite.SignVerify.class})
public class EccCryptoContextSuite {
/** MSL encoder format. */
private static final MslEncoderFormat ENCODER_FORMAT = MslEncoderFormat.JSON;
/** Key pair ID. */
private static final String KEYPAIR_ID = "keypairid";
/** EC curve q. */
private static final BigInteger EC_Q = new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839");
/** EC coefficient a. */
private static final BigInteger EC_A = new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16);
/** EC coefficient b. */
private static final BigInteger EC_B = new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16);
/** EC base point g. */
private static final BigInteger EC_G = new BigInteger("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf", 16);
/** EC generator order n. */
private static final BigInteger EC_N = new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307");
@AfterClass
public static synchronized void teardown() {
// Teardown causes problems because the data is shared by the inner
// classes, so don't do any cleanup.
}
/** Encrypt/decrypt mode unit tests. */
@Ignore // Cannot perform ECIES encryption/decryption at the moment.
public static class EncryptDecrypt {
}
/** Sign/verify mode unit tests. */
public static class SignVerify {
@BeforeClass
public static synchronized void setup() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidParameterSpecException, NoSuchProviderException, MslEncodingException, MslCryptoException {
if (random == null) {
Security.addProvider(new BouncyCastleProvider());
final MslContext ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
encoder = ctx.getMslEncoderFactory();
final ECCurve curve = new ECCurve.Fp(EC_Q, EC_A, EC_B);
final AlgorithmParameterSpec paramSpec = new ECParameterSpec(curve, curve.decodePoint(EC_G.toByteArray()), EC_N);
final KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("ECDSA", "BC");
keypairGenerator.initialize(paramSpec);
final KeyPair keypairA = keypairGenerator.generateKeyPair();
privateKeyA = keypairA.getPrivate();
publicKeyA = keypairA.getPublic();
keypairGenerator.initialize(paramSpec);
final KeyPair keypairB = keypairGenerator.generateKeyPair();
privateKeyB = keypairB.getPrivate();
publicKeyB = keypairB.getPublic();
random = new Random();
}
}
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
@Test
public void encryptDecrypt() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final EccCryptoContext cryptoContext = new EccCryptoContext(KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptNullPublic() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final EccCryptoContext cryptoContext = new EccCryptoContext(KEYPAIR_ID, privateKeyA, null, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void decryptNullPrivate() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final EccCryptoContext cryptoContext = new EccCryptoContext(KEYPAIR_ID, null, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptDecryptIdMismatch() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final EccCryptoContext cryptoContextA = new EccCryptoContext(KEYPAIR_ID + "A", privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final EccCryptoContext cryptoContextB = new EccCryptoContext(KEYPAIR_ID + "B", privateKeyB, publicKeyB, Mode.SIGN_VERIFY);
final byte[] plaintext = cryptoContextB.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptDecryptKeyMismatch() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final EccCryptoContext cryptoContextA = new EccCryptoContext(KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final EccCryptoContext cryptoContextB = new EccCryptoContext(KEYPAIR_ID, privateKeyB, publicKeyB, Mode.SIGN_VERIFY);
final byte[] plaintext = cryptoContextB.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void signVerify() throws MslCryptoException {
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final EccCryptoContext cryptoContext = new EccCryptoContext(KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] signatureA = cryptoContext.sign(messageA, encoder, ENCODER_FORMAT);
assertNotNull(signatureA);
assertTrue(signatureA.length > 0);
assertThat(messageA, is(not(signatureA)));
assertTrue(cryptoContext.verify(messageA, signatureA, encoder));
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] signatureB = cryptoContext.sign(messageB, encoder, ENCODER_FORMAT);
assertTrue(signatureB.length > 0);
assertThat(signatureA, is(not(signatureB)));
assertTrue(cryptoContext.verify(messageB, signatureB, encoder));
assertFalse(cryptoContext.verify(messageB, signatureA, encoder));
}
@Test
public void signVerifyContextMismatch() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final EccCryptoContext cryptoContextA = new EccCryptoContext(KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] signature = cryptoContextA.sign(message, encoder, ENCODER_FORMAT);
final EccCryptoContext cryptoContextB = new EccCryptoContext(KEYPAIR_ID, privateKeyB, publicKeyB, Mode.SIGN_VERIFY);
assertFalse(cryptoContextB.verify(message, signature, encoder));
}
@Test
public void signNullPrivate() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.SIGN_NOT_SUPPORTED);
final byte[] message = new byte[32];
random.nextBytes(message);
final EccCryptoContext cryptoContext = new EccCryptoContext(KEYPAIR_ID, null, publicKeyA, Mode.SIGN_VERIFY);
cryptoContext.sign(message, encoder, ENCODER_FORMAT);
}
@Test
public void verifyNullPublic() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.VERIFY_NOT_SUPPORTED);
final byte[] message = new byte[32];
random.nextBytes(message);
final EccCryptoContext cryptoContext = new EccCryptoContext(KEYPAIR_ID, privateKeyA, null, Mode.SIGN_VERIFY);
final byte[] signature;
try {
signature = cryptoContext.sign(message, encoder, ENCODER_FORMAT);
} catch (final MslCryptoException e) {
fail(e.getMessage());
return;
}
cryptoContext.verify(message, signature, encoder);
}
}
/** ECC public key A. */
private static PublicKey publicKeyA;
/** ECC private key A. */
private static PrivateKey privateKeyA;
/** ECC public key B. */
private static PublicKey publicKeyB;
/** ECC private key B. */
private static PrivateKey privateKeyB;
/** Random. */
private static Random random;
/** MSL encoder factory. */
private static MslEncoderFactory encoder;
}
| 1,793 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/crypto/MslCiphertextEnvelopeSuite.java
|
/**
* Copyright (c) 2012-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.crypto;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.netflix.msl.MslConstants.CipherSpec;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.crypto.MslCiphertextEnvelope.Version;
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.MslObject;
import com.netflix.msl.test.ExpectedMslException;
import com.netflix.msl.util.MockMslContext;
import com.netflix.msl.util.MslContext;
/**
* MSL encryption envelope unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
@RunWith(Suite.class)
@SuiteClasses({MslCiphertextEnvelopeSuite.Version1.class,
MslCiphertextEnvelopeSuite.Version2.class})
public class MslCiphertextEnvelopeSuite {
/** Key version. */
private final static String KEY_VERSION = "version";
/** Key key ID. */
private final static String KEY_KEY_ID = "keyid";
/** Key cipherspec. */
private final static String KEY_CIPHERSPEC = "cipherspec";
/** Key initialization vector. */
private final static String KEY_IV = "iv";
/** Key ciphertext. */
private final static String KEY_CIPHERTEXT = "ciphertext";
/** Key SHA-256. */
private final static String KEY_SHA256 = "sha256";
/** MSL encoder format. */
private final static MslEncoderFormat ENCODER_FORMAT = MslEncoderFormat.JSON;
/** Key ID. */
private final static String KEY_ID = "keyid";
private static final byte[] IV = new byte[16];
private static final byte[] CIPHERTEXT = new byte[32];
/** MSL encoder factory. */
private static MslEncoderFactory encoder;
@BeforeClass
public static void setup() throws MslEncodingException, MslCryptoException {
final Random random = new Random();
random.nextBytes(IV);
random.nextBytes(CIPHERTEXT);
final MslContext ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
encoder = ctx.getMslEncoderFactory();
}
@AfterClass
public static void teardown() {
// Teardown causes problems because the data is shared by the inner
// classes, so don't do any cleanup.
}
public static class Version1 {
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
@Test
public void ctors() throws MslCryptoException, MslEncodingException, MslEncoderException {
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(KEY_ID, IV, CIPHERTEXT);
assertEquals(KEY_ID, envelope.getKeyId());
assertNull(envelope.getCipherSpec());
assertArrayEquals(IV, envelope.getIv());
assertArrayEquals(CIPHERTEXT, envelope.getCiphertext());
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(encode);
final MslObject mo = encoder.parseObject(encode);
final MslCiphertextEnvelope moEnvelope = new MslCiphertextEnvelope(mo);
assertEquals(envelope.getKeyId(), moEnvelope.getKeyId());
assertEquals(envelope.getCipherSpec(), moEnvelope.getCipherSpec());
assertArrayEquals(envelope.getIv(), moEnvelope.getIv());
assertArrayEquals(envelope.getCiphertext(), moEnvelope.getCiphertext());
final byte[] moEncode = moEnvelope.toMslEncoding(encoder, ENCODER_FORMAT);
assertArrayEquals(encode, moEncode);
}
@Test
public void ctorsNullIv() throws MslEncoderException, MslCryptoException, MslEncodingException {
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(KEY_ID, null, CIPHERTEXT);
assertEquals(KEY_ID, envelope.getKeyId());
assertNull(envelope.getCipherSpec());
assertNull(envelope.getIv());
assertArrayEquals(CIPHERTEXT, envelope.getCiphertext());
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(encode);
final MslObject mo = encoder.parseObject(encode);
final MslCiphertextEnvelope moEnvelope = new MslCiphertextEnvelope(mo);
assertEquals(envelope.getKeyId(), moEnvelope.getKeyId());
assertEquals(envelope.getCipherSpec(), moEnvelope.getCipherSpec());
assertArrayEquals(envelope.getIv(), moEnvelope.getIv());
assertArrayEquals(envelope.getCiphertext(), moEnvelope.getCiphertext());
final byte[] moEncode = moEnvelope.toMslEncoding(encoder, ENCODER_FORMAT);
assertArrayEquals(encode, moEncode);
}
@Test
public void encode() throws MslEncoderException, MslCryptoException, MslEncodingException {
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(KEY_ID, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
assertEquals(KEY_ID, mo.getString(KEY_KEY_ID));
assertFalse(mo.has(KEY_CIPHERSPEC));
assertArrayEquals(IV, mo.getBytes(KEY_IV));
assertArrayEquals(CIPHERTEXT, mo.getBytes(KEY_CIPHERTEXT));
}
@Test
public void encodeNullIv() throws MslCryptoException, MslEncodingException, MslEncoderException {
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(KEY_ID, null, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
assertEquals(KEY_ID, mo.getString(KEY_KEY_ID));
assertFalse(mo.has(KEY_CIPHERSPEC));
assertFalse(mo.has(KEY_IV));
assertArrayEquals(CIPHERTEXT, mo.getBytes(KEY_CIPHERTEXT));
}
@Test
public void missingKeyId() throws MslEncoderException, MslCryptoException, MslEncodingException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(KEY_ID, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
mo.remove(KEY_KEY_ID);
new MslCiphertextEnvelope(mo);
}
@Test
public void missingCiphertext() throws MslEncoderException, MslCryptoException, MslEncodingException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(KEY_ID, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
mo.remove(KEY_CIPHERTEXT);
new MslCiphertextEnvelope(mo);
}
@Test
public void missingSha256() throws MslEncoderException, MslCryptoException, MslEncodingException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(KEY_ID, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
mo.remove(KEY_SHA256);
new MslCiphertextEnvelope(mo);
}
@Test
public void incorrectSha256() throws MslEncoderException, MslCryptoException, MslEncodingException {
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(KEY_ID, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
final byte[] hash = mo.getBytes(KEY_SHA256);
assertNotNull(hash);
hash[0] += 1;
mo.put(KEY_SHA256, hash);
final MslCiphertextEnvelope moEnvelope = new MslCiphertextEnvelope(mo);
assertEquals(KEY_ID, moEnvelope.getKeyId());
assertNull(moEnvelope.getCipherSpec());
assertArrayEquals(IV, moEnvelope.getIv());
assertArrayEquals(CIPHERTEXT, moEnvelope.getCiphertext());
}
}
@RunWith(Parameterized.class)
public static class Version2 {
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
@Parameters
public static Collection<Object[]> data() {
final List<Object[]> params = new ArrayList<Object[]>();
for (final CipherSpec spec : CipherSpec.values())
params.add(new Object[] { spec });
return params;
}
/** Cipher specification. */
private final CipherSpec cipherSpec;
/**
* Create a new Version 2 test set with the provided cipher
* specification.
*
* @param cipherSpec the cipher specification.
*/
public Version2(final CipherSpec cipherSpec) {
this.cipherSpec = cipherSpec;
}
@Test
public void ctors() throws MslCryptoException, MslEncodingException, MslEncoderException {
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(cipherSpec, IV, CIPHERTEXT);
assertNull(envelope.getKeyId());
assertEquals(cipherSpec, envelope.getCipherSpec());
assertArrayEquals(IV, envelope.getIv());
assertArrayEquals(CIPHERTEXT, envelope.getCiphertext());
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(encode);
final MslObject mo = encoder.parseObject(encode);
final MslCiphertextEnvelope moEnvelope = new MslCiphertextEnvelope(mo);
assertEquals(envelope.getKeyId(), moEnvelope.getKeyId());
assertEquals(envelope.getCipherSpec(), moEnvelope.getCipherSpec());
assertArrayEquals(envelope.getIv(), moEnvelope.getIv());
assertArrayEquals(envelope.getCiphertext(), moEnvelope.getCiphertext());
final byte[] moEncode = moEnvelope.toMslEncoding(encoder, ENCODER_FORMAT);
assertArrayEquals(encode, moEncode);
}
@Test
public void ctorsNullIv() throws MslEncoderException, MslCryptoException, MslEncodingException {
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(cipherSpec, null, CIPHERTEXT);
assertNull(envelope.getKeyId());
assertEquals(cipherSpec, envelope.getCipherSpec());
assertNull(envelope.getIv());
assertArrayEquals(CIPHERTEXT, envelope.getCiphertext());
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
assertNotNull(encode);
final MslObject mo = encoder.parseObject(encode);
final MslCiphertextEnvelope moEnvelope = new MslCiphertextEnvelope(mo);
assertEquals(envelope.getKeyId(), moEnvelope.getKeyId());
assertEquals(envelope.getCipherSpec(), moEnvelope.getCipherSpec());
assertArrayEquals(envelope.getIv(), moEnvelope.getIv());
assertArrayEquals(envelope.getCiphertext(), moEnvelope.getCiphertext());
final byte[] moEncode = moEnvelope.toMslEncoding(encoder, ENCODER_FORMAT);
assertArrayEquals(encode, moEncode);
}
@Test
public void encode() throws MslEncoderException, MslCryptoException, MslEncodingException {
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(cipherSpec, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
assertEquals(Version.V2.intValue(), mo.getInt(KEY_VERSION));
assertFalse(mo.has(KEY_KEY_ID));
assertEquals(cipherSpec.toString(), mo.getString(KEY_CIPHERSPEC));
assertArrayEquals(IV, mo.getBytes(KEY_IV));
assertArrayEquals(CIPHERTEXT, mo.getBytes(KEY_CIPHERTEXT));
}
@Test
public void encodeNullIv() throws MslCryptoException, MslEncodingException, MslEncoderException {
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(cipherSpec, null, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
assertEquals(Version.V2.intValue(), mo.getInt(KEY_VERSION));
assertFalse(mo.has(KEY_KEY_ID));
assertEquals(cipherSpec.toString(), mo.getString(KEY_CIPHERSPEC));
assertFalse(mo.has(KEY_IV));
assertArrayEquals(CIPHERTEXT, mo.getBytes(KEY_CIPHERTEXT));
}
@Test
public void misingVersion() throws MslEncoderException, MslCryptoException, MslEncodingException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(cipherSpec, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
mo.remove(KEY_VERSION);
new MslCiphertextEnvelope(mo);
}
@Test
public void invalidVersion() throws MslEncoderException, MslCryptoException, MslEncodingException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(cipherSpec, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
mo.put(KEY_VERSION, "x");
new MslCiphertextEnvelope(mo);
}
@Test
public void unknownVersion() throws MslEncoderException, MslCryptoException, MslEncodingException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNIDENTIFIED_CIPHERTEXT_ENVELOPE);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(cipherSpec, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
mo.put(KEY_VERSION, -1);
new MslCiphertextEnvelope(mo);
}
@Test
public void missingCipherSpec() throws MslEncoderException, MslCryptoException, MslEncodingException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(cipherSpec, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
mo.remove(KEY_CIPHERSPEC);
new MslCiphertextEnvelope(mo);
}
@Test
public void invalidCipherSpec() throws MslEncoderException, MslCryptoException, MslEncodingException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNIDENTIFIED_CIPHERSPEC);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(cipherSpec, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
mo.put(KEY_CIPHERSPEC, "x");
new MslCiphertextEnvelope(mo);
}
@Test
public void missingCiphertext() throws MslEncoderException, MslCryptoException, MslEncodingException {
thrown.expect(MslEncodingException.class);
thrown.expectMslError(MslError.MSL_PARSE_ERROR);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(cipherSpec, IV, CIPHERTEXT);
final byte[] encode = envelope.toMslEncoding(encoder, ENCODER_FORMAT);
final MslObject mo = encoder.parseObject(encode);
mo.remove(KEY_CIPHERTEXT);
new MslCiphertextEnvelope(mo);
}
}
}
| 1,794 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/crypto/RsaCryptoContextSuite.java
|
/**
* Copyright (c) 2012-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.crypto;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Random;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.RsaCryptoContext.Mode;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.test.ExpectedMslException;
import com.netflix.msl.util.MockMslContext;
import com.netflix.msl.util.MslContext;
/**
* RSA crypto context unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
@RunWith(Suite.class)
@SuiteClasses({RsaCryptoContextSuite.EncryptDecrypt.class,
RsaCryptoContextSuite.WrapUnwrap.class,
RsaCryptoContextSuite.SignVerify.class})
public class RsaCryptoContextSuite{
/** Key pair ID. */
private static final String KEYPAIR_ID = "keypairid";
/** MSL encoder format. */
private static final MslEncoderFormat ENCODER_FORMAT = MslEncoderFormat.JSON;
/** MSL encoder factory. */
private static MslEncoderFactory encoder;
@BeforeClass
public static synchronized void setup() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidParameterSpecException, NoSuchProviderException, MslEncodingException, MslCryptoException {
if (random == null) {
ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
encoder = ctx.getMslEncoderFactory();
Security.addProvider(new BouncyCastleProvider());
final KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA");
keypairGenerator.initialize(512);
final KeyPair keypairA = keypairGenerator.generateKeyPair();
privateKeyA = keypairA.getPrivate();
publicKeyA = keypairA.getPublic();
final KeyPair keypairB = keypairGenerator.generateKeyPair();
privateKeyB = keypairB.getPrivate();
publicKeyB = keypairB.getPublic();
random = new Random();
}
}
@AfterClass
public static synchronized void teardown() {
// Teardown causes problems because the data is shared by the inner
// classes, so don't do any cleanup.
}
/** Encrypt/decrypt mode unit tests. */
@RunWith(Parameterized.class)
public static class EncryptDecrypt {
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ Mode.ENCRYPT_DECRYPT_OAEP, 16 },
{ Mode.ENCRYPT_DECRYPT_PKCS1, 32 }
});
}
/** Crypto context mode. */
private final Mode mode;
/** Plaintext message size in bytes. */
private final int messageSize;
/**
* Create a new encrypt/decrypt test instance with the specified
* mode and plaintext message size.
*
* @param mode crypto context mode.
* @param messageSize plaintext message size in bytes.
*/
public EncryptDecrypt(final Mode mode, final int messageSize) {
this.mode = mode;
this.messageSize = messageSize;
}
@Test
public void encryptDecrypt() throws MslEncodingException, MslCryptoException, MslMasterTokenException {
final byte[] messageA = new byte[messageSize];
random.nextBytes(messageA);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, mode);
final byte[] ciphertextA = cryptoContext.encrypt(messageA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(messageA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.decrypt(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(messageA, plaintextA);
final byte[] messageB = new byte[messageSize];
random.nextBytes(messageB);
final byte[] ciphertextB = cryptoContext.encrypt(messageB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(messageB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.decrypt(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(messageB, plaintextB);
}
@Test
public void encryptNullPublic() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.ENCRYPT_NOT_SUPPORTED);
final byte[] message = new byte[messageSize];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, null, mode);
cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
}
@Test
public void decryptNullPrivate() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.DECRYPT_NOT_SUPPORTED);
final byte[] message = new byte[messageSize];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, null, publicKeyA, mode);
final byte[] ciphertext = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
cryptoContext.decrypt(ciphertext, encoder);
}
@Test
public void encryptDecryptIdMismatch() throws MslCryptoException {
final byte[] message = new byte[messageSize];
random.nextBytes(message);
final RsaCryptoContext cryptoContextA = new RsaCryptoContext(ctx, KEYPAIR_ID + "A", privateKeyA, publicKeyA, mode);
final byte[] ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertThat(message, is(not(ciphertext)));
final RsaCryptoContext cryptoContextB = new RsaCryptoContext(ctx, KEYPAIR_ID + "B", privateKeyA, publicKeyA, mode);
final byte[] plaintext = cryptoContextB.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptDecryptKeysMismatch() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_BAD_PADDING);
final byte[] message = new byte[messageSize];
random.nextBytes(message);
final RsaCryptoContext cryptoContextA = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, mode);
final byte[] ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
final RsaCryptoContext cryptoContextB = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyB, publicKeyB, mode);
cryptoContextB.decrypt(ciphertext, encoder);
}
@Test
public void wrapUnwrapOneBlock() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.WRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, mode);
final byte[] keydataA = new byte[8];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertArrayEquals(keydataA, ciphertextA);
}
@Test
public void wrapUnwrapBlockAligned() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.WRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, mode);
final byte[] keydataA = new byte[messageSize];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertArrayEquals(keydataA, ciphertextA);
}
@Test
public void wrapUnwrapBlockUnaligned() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.WRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, mode);
final byte[] keydataA = new byte[127];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertArrayEquals(keydataA, ciphertextA);
}
@Test
public void wrapNullPublic() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.WRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, null, mode);
final byte[] messageA = new byte[messageSize];
random.nextBytes(messageA);
final byte[] ciphertextA = cryptoContext.wrap(messageA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertArrayEquals(messageA, ciphertextA);
}
@Test
public void unwrapNullPrivate() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, null, publicKeyA, mode);
final byte[] messageA = new byte[messageSize];
random.nextBytes(messageA);
final byte[] plaintextA = cryptoContext.unwrap(messageA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(messageA, plaintextA);
}
@Test
public void unwrapUnalignedData() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, mode);
final byte[] keydataA = new byte[1];
random.nextBytes(keydataA);
final byte[] plaintextA = cryptoContext.unwrap(keydataA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(keydataA, plaintextA);
}
@Test
public void signVerify() throws MslCryptoException {
final byte[] message = new byte[messageSize];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, mode);
final byte[] signature = cryptoContext.sign(message, encoder, ENCODER_FORMAT);
assertNotNull(signature);
assertEquals(0, signature.length);
assertTrue(cryptoContext.verify(message, signature, encoder));
}
@Test
public void signVerifyContextMismatch() throws MslCryptoException {
final byte[] message = new byte[messageSize];
random.nextBytes(message);
final RsaCryptoContext cryptoContextA = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, mode);
final byte [] signature = cryptoContextA.sign(message, encoder, ENCODER_FORMAT);
final RsaCryptoContext cryptoContextB = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyB, publicKeyB, mode);
assertTrue(cryptoContextB.verify(message, signature, encoder));
}
@Test
public void signNullPrivate() throws MslCryptoException {
final byte[] message = new byte[messageSize];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, null, publicKeyA, mode);
final byte[] signature = cryptoContext.sign(message, encoder, ENCODER_FORMAT);
assertNotNull(signature);
assertEquals(0, signature.length);
assertTrue(cryptoContext.verify(message, signature, encoder));
}
@Test
public void verifyNullPublic() throws MslCryptoException {
final byte[] message = new byte[messageSize];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, null, mode);
final byte[] signature = cryptoContext.sign(message, encoder, ENCODER_FORMAT);
assertNotNull(signature);
assertEquals(0, signature.length);
assertTrue(cryptoContext.verify(message, signature, encoder));
}
}
/** Wrap/unwrap mode unit tests. */
@Ignore
public static class WrapUnwrap {
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
@Test
public void encryptDecrypt() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptNullPublic() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, null, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void decryptNullPrivate() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, null, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptDecryptIdMismatch() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContextA = new RsaCryptoContext(ctx, KEYPAIR_ID + "A", privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final RsaCryptoContext cryptoContextB = new RsaCryptoContext(ctx, KEYPAIR_ID + "B", privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] plaintext = cryptoContextB.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptDecryptKeysMismatch() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContextA = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final RsaCryptoContext cryptoContextB = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyB, publicKeyB, Mode.SIGN_VERIFY);
final byte[] plaintext = cryptoContextB.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void wrapUnwrapOneBlock() throws MslCryptoException {
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.WRAP_UNWRAP);
final byte[] keydataA = new byte[8];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(keydataA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.unwrap(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(keydataA, plaintextA);
final byte[] keydataB = new byte[8];
random.nextBytes(keydataB);
final byte[] ciphertextB = cryptoContext.wrap(keydataB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(keydataB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.unwrap(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(keydataB, plaintextB);
}
@Test
public void wrapUnwrapBlockAligned() throws MslCryptoException {
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.WRAP_UNWRAP);
final byte[] keydataA = new byte[32];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(keydataA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.unwrap(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(keydataA, plaintextA);
final byte[] keydataB = new byte[32];
random.nextBytes(keydataB);
final byte[] ciphertextB = cryptoContext.wrap(keydataB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(keydataB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.unwrap(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(keydataB, plaintextB);
}
@Test
public void wrapUnwrapBlockUnaligned() throws MslCryptoException {
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.WRAP_UNWRAP);
final byte[] keydataA = new byte[127];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(keydataA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.unwrap(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(keydataA, plaintextA);
final byte[] keydataB = new byte[127];
random.nextBytes(keydataB);
final byte[] ciphertextB = cryptoContext.wrap(keydataB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(keydataB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.unwrap(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(keydataB, plaintextB);
}
@Test
public void wrapNullPublic() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.WRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, null, Mode.WRAP_UNWRAP);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
cryptoContext.wrap(messageA, encoder, ENCODER_FORMAT);
}
@Test
public void unwrapNullPrivate() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, null, publicKeyA, Mode.WRAP_UNWRAP);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
cryptoContext.unwrap(messageA, encoder);
}
@Test
public void unwrapUnalignedData() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.INVALID_WRAP_CIPHERTEXT);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.WRAP_UNWRAP);
final byte[] keydataA = new byte[1];
random.nextBytes(keydataA);
cryptoContext.unwrap(keydataA, encoder);
}
@Test
public void signVerify() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.WRAP_UNWRAP);
final byte[] signature = cryptoContext.sign(message, encoder, ENCODER_FORMAT);
assertNotNull(signature);
assertEquals(0, signature.length);
assertTrue(cryptoContext.verify(message, signature, encoder));
}
@Test
public void signVerifyContextMismatch() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContextA = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.WRAP_UNWRAP);
final byte [] signature = cryptoContextA.sign(message, encoder, ENCODER_FORMAT);
final RsaCryptoContext cryptoContextB = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyB, publicKeyB, Mode.WRAP_UNWRAP);
assertTrue(cryptoContextB.verify(message, signature, encoder));
}
@Test
public void signNullPrivate() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, null, publicKeyA, Mode.WRAP_UNWRAP);
final byte[] signature = cryptoContext.sign(message, encoder, ENCODER_FORMAT);
assertNotNull(signature);
assertEquals(0, signature.length);
assertTrue(cryptoContext.verify(message, signature, encoder));
}
@Test
public void verifyNullPublic() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, null, Mode.WRAP_UNWRAP);
final byte[] signature = cryptoContext.sign(message, encoder, ENCODER_FORMAT);
assertNotNull(signature);
assertEquals(0, signature.length);
assertTrue(cryptoContext.verify(message, signature, encoder));
}
}
/** Sign/verify mode unit tests. */
public static class SignVerify {
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
@Test
public void encryptDecrypt() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptNullPublic() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, null, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void decryptNullPrivate() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, null, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptDecryptIdMismatch() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContextA = new RsaCryptoContext(ctx, KEYPAIR_ID + "A", privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final RsaCryptoContext cryptoContextB = new RsaCryptoContext(ctx, KEYPAIR_ID + "B", privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] plaintext = cryptoContextB.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptDecryptKeysMismatch() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContextA = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertArrayEquals(message, ciphertext);
final RsaCryptoContext cryptoContextB = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyB, publicKeyB, Mode.SIGN_VERIFY);
final byte[] plaintext = cryptoContextB.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void wrapUnwrapOneBlock() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.WRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] keydataA = new byte[8];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertArrayEquals(keydataA, ciphertextA);
}
@Test
public void wrapUnwrapBlockAligned() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.WRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] keydataA = new byte[32];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertArrayEquals(keydataA, ciphertextA);
}
@Test
public void wrapUnwrapBlockUnaligned() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.WRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] keydataA = new byte[127];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertArrayEquals(keydataA, ciphertextA);
}
@Test
public void wrapNullPublic() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.WRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, null, Mode.SIGN_VERIFY);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] ciphertextA = cryptoContext.wrap(messageA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertArrayEquals(messageA, ciphertextA);
}
@Test
public void unwrapNullPrivate() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, null, publicKeyA, Mode.SIGN_VERIFY);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] plaintextA = cryptoContext.unwrap(messageA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(messageA, plaintextA);
}
@Test
public void unwrapUnalignedData() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] keydataA = new byte[1];
random.nextBytes(keydataA);
final byte[] plaintextA = cryptoContext.unwrap(keydataA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(keydataA, plaintextA);
}
@Test
public void signVerify() throws MslCryptoException {
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte[] signatureA = cryptoContext.sign(messageA, encoder, ENCODER_FORMAT);
assertNotNull(signatureA);
assertTrue(signatureA.length > 0);
assertThat(messageA, is(not(signatureA)));
assertTrue(cryptoContext.verify(messageA, signatureA, encoder));
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] signatureB = cryptoContext.sign(messageB, encoder, ENCODER_FORMAT);
assertTrue(signatureB.length > 0);
assertThat(signatureA, is(not(signatureB)));
assertTrue(cryptoContext.verify(messageB, signatureB, encoder));
assertFalse(cryptoContext.verify(messageB, signatureA, encoder));
}
@Test
public void signVerifyContextMismatch() throws MslCryptoException {
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContextA = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, publicKeyA, Mode.SIGN_VERIFY);
final byte [] signature = cryptoContextA.sign(message, encoder, ENCODER_FORMAT);
final RsaCryptoContext cryptoContextB = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyB, publicKeyB, Mode.SIGN_VERIFY);
assertFalse(cryptoContextB.verify(message, signature, encoder));
}
@Test
public void signNullPrivate() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.SIGN_NOT_SUPPORTED);
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, null, publicKeyA, Mode.SIGN_VERIFY);
cryptoContext.sign(message, encoder, ENCODER_FORMAT);
}
@Test
public void verifyNullPublic() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.VERIFY_NOT_SUPPORTED);
final byte[] message = new byte[32];
random.nextBytes(message);
final RsaCryptoContext cryptoContext = new RsaCryptoContext(ctx, KEYPAIR_ID, privateKeyA, null, Mode.SIGN_VERIFY);
final byte[] signature;
try {
signature = cryptoContext.sign(message, encoder, ENCODER_FORMAT);
} catch (final MslCryptoException e) {
fail(e.getMessage());
return;
}
cryptoContext.verify(message, signature, encoder);
}
}
/** RSA public key A. */
private static PublicKey publicKeyA;
/** RSA private key A. */
private static PrivateKey privateKeyA;
/** RSA public key B. */
private static PublicKey publicKeyB;
/** RSA private key B. */
private static PrivateKey privateKeyB;
/** MSL context. */
private static MslContext ctx;
/** Random. */
private static Random random;
}
| 1,795 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/crypto/SymmetricCryptoContextTest.java
|
/**
* Copyright (c) 2012-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.crypto;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.entityauth.MockPresharedAuthenticationFactory;
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.test.ExpectedMslException;
import com.netflix.msl.util.MockMslContext;
import com.netflix.msl.util.MslContext;
/**
* Symmetric crypto context unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
@RunWith(Parameterized.class)
public class SymmetricCryptoContextTest {
/** MSL encoder format. */
private static final MslEncoderFormat ENCODER_FORMAT = MslEncoderFormat.JSON;
/** Key set ID. */
private static final String KEYSET_ID = "keysetid";
/** Key ciphertext. */
private static final String KEY_CIPHERTEXT = "ciphertext";
/** AES-128 CMAC key length in bytes. */
private static final int AES_CMAC_KEY_LENGTH = 16;
/** RFC 3394 encryption key. */
private final byte[] RFC_KEY = {
(byte)0x00, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07,
(byte)0x08, (byte)0x09, (byte)0x0A, (byte)0x0B, (byte)0x0C, (byte)0x0D, (byte)0x0E, (byte)0x0F };
/** RFC 3394 plaintext (key data). */
private final byte[] RFC_PLAINTEXT = {
(byte)0x00, (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66, (byte)0x77,
(byte)0x88, (byte)0x99, (byte)0xAA, (byte)0xBB, (byte)0xCC, (byte)0xDD, (byte)0xEE, (byte)0xFF };
/** RFC 3394 ciphertext. */
private final byte[] RFC_CIPHERTEXT = {
(byte)0x1F, (byte)0xA6, (byte)0x8B, (byte)0x0A, (byte)0x81, (byte)0x12, (byte)0xB4, (byte)0x47,
(byte)0xAE, (byte)0xF3, (byte)0x4B, (byte)0xD8, (byte)0xFB, (byte)0x5A, (byte)0x7B, (byte)0x82,
(byte)0x9D, (byte)0x3E, (byte)0x86, (byte)0x23, (byte)0x71, (byte)0xD2, (byte)0xCF, (byte)0xE5 };
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
@BeforeClass
public static void setup() throws MslEncodingException, MslCryptoException {
random = new Random();
ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
encoder = ctx.getMslEncoderFactory();
}
@AfterClass
public static void teardown() {
encoder = null;
ctx = null;
random = null;
}
@Parameters
public static List<Object[]> data() {
final byte[] aesKey = new byte[AES_CMAC_KEY_LENGTH];
new Random().nextBytes(aesKey);
final SecretKey aesCmacKey = new SecretKeySpec(aesKey, JcaAlgorithm.AES_CMAC);
return Arrays.asList(new Object[][] {
{ MockPresharedAuthenticationFactory.KPE, MockPresharedAuthenticationFactory.KPH, MockPresharedAuthenticationFactory.KPW },
{ MockPresharedAuthenticationFactory.KPE, aesCmacKey, MockPresharedAuthenticationFactory.KPW },
});
}
/** Crypto context. */
private final ICryptoContext cryptoContext;
/**
* Create a new symmetric crypto context test instance.
*
* @param encryptionKey encryption key.
* @param signatureKey signature key.
* @param wrappingKey wrpaping key.
*/
public SymmetricCryptoContextTest(final SecretKey encryptionKey, final SecretKey signatureKey, final SecretKey wrappingKey) {
this.cryptoContext = new SymmetricCryptoContext(ctx, KEYSET_ID, encryptionKey, signatureKey, wrappingKey);
}
@Test
public void encryptDecrypt() throws MslEncodingException, MslCryptoException, MslMasterTokenException {
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] ciphertextA = cryptoContext.encrypt(messageA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(messageA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.decrypt(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(messageA, plaintextA);
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] ciphertextB = cryptoContext.encrypt(messageB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(messageB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.decrypt(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(messageB, plaintextB);
}
@Test
public void invalidCiphertext() throws MslEncodingException, MslCryptoException, MslEncoderException, UnsupportedEncodingException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_BAD_PADDING);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] data = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
final MslObject envelopeMo = encoder.parseObject(data);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(envelopeMo);
final byte[] ciphertext = envelope.getCiphertext();
++ciphertext[ciphertext.length - 2];
final MslCiphertextEnvelope shortEnvelope = new MslCiphertextEnvelope(envelope.getKeyId(), envelope.getIv(), ciphertext);
cryptoContext.decrypt(shortEnvelope.toMslEncoding(encoder, ENCODER_FORMAT), encoder);
}
@Test
public void insufficientCiphertext() throws MslCryptoException, MslEncoderException, MslEncodingException, UnsupportedEncodingException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] data = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
final MslObject envelopeMo = encoder.parseObject(data);
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(envelopeMo);
final byte[] ciphertext = envelope.getCiphertext();
final byte[] shortCiphertext = Arrays.copyOf(ciphertext, ciphertext.length - 1);
final MslCiphertextEnvelope shortEnvelope = new MslCiphertextEnvelope(envelope.getKeyId(), envelope.getIv(), shortCiphertext);
cryptoContext.decrypt(shortEnvelope.toMslEncoding(encoder, ENCODER_FORMAT), encoder);
}
@Test
public void notEnvelope() throws MslCryptoException, MslEncoderException, MslEncodingException, UnsupportedEncodingException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] data = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
final MslObject envelopeMo = encoder.parseObject(data);
envelopeMo.remove(KEY_CIPHERTEXT);
cryptoContext.decrypt(encoder.encodeObject(envelopeMo, ENCODER_FORMAT), encoder);
}
@Test
public void corruptEnvelope() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] data = cryptoContext.encrypt(message, encoder, ENCODER_FORMAT);
data[0] = 0;
cryptoContext.decrypt(data, encoder);
}
@Test
public void encryptNullEncryption() throws MslEncodingException, MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.ENCRYPT_NOT_SUPPORTED);
final ICryptoContext cryptoContext= new SymmetricCryptoContext(ctx, KEYSET_ID, null, MockPresharedAuthenticationFactory.KPH, MockPresharedAuthenticationFactory.KPW);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
cryptoContext.encrypt(messageA, encoder, ENCODER_FORMAT);
}
@Test
public void decryptNullEncryption() throws MslEncodingException, MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.DECRYPT_NOT_SUPPORTED);
final ICryptoContext cryptoContext= new SymmetricCryptoContext(ctx, KEYSET_ID, null, MockPresharedAuthenticationFactory.KPH, MockPresharedAuthenticationFactory.KPW);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
cryptoContext.decrypt(messageA, encoder);
}
@Test
public void encryptDecryptNullKeys() throws MslEncodingException, MslCryptoException, MslEncoderException {
final ICryptoContext cryptoContext = new SymmetricCryptoContext(ctx, KEYSET_ID, MockPresharedAuthenticationFactory.KPE, null, null);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] ciphertextA = cryptoContext.encrypt(messageA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(messageA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.decrypt(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(messageA, plaintextA);
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] ciphertextB = cryptoContext.encrypt(messageB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(messageB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.decrypt(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(messageB, plaintextB);
}
@Test
public void encryptDecryptIdMismatch() throws MslEncodingException, MslCryptoException, MslEncoderException {
final ICryptoContext cryptoContextA = new SymmetricCryptoContext(ctx, KEYSET_ID + "A", MockPresharedAuthenticationFactory.KPE, MockPresharedAuthenticationFactory.KPH, MockPresharedAuthenticationFactory.KPW);
final ICryptoContext cryptoContextB = new SymmetricCryptoContext(ctx, KEYSET_ID + "B", MockPresharedAuthenticationFactory.KPE, MockPresharedAuthenticationFactory.KPH, MockPresharedAuthenticationFactory.KPW);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
assertNotNull(ciphertext);
assertThat(ciphertext, is(not(message)));
final byte[] plaintext = cryptoContextB.decrypt(ciphertext, encoder);
assertNotNull(plaintext);
assertArrayEquals(message, plaintext);
}
@Test
public void encryptDecryptKeysMismatch() throws MslEncodingException, MslCryptoException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_BAD_PADDING);
final ICryptoContext cryptoContextA = new SymmetricCryptoContext(ctx, KEYSET_ID, MockPresharedAuthenticationFactory.KPE, MockPresharedAuthenticationFactory.KPH, MockPresharedAuthenticationFactory.KPW);
final ICryptoContext cryptoContextB = new SymmetricCryptoContext(ctx, KEYSET_ID, MockPresharedAuthenticationFactory.KPE2, MockPresharedAuthenticationFactory.KPH2, MockPresharedAuthenticationFactory.KPW2);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] ciphertext;
try {
ciphertext = cryptoContextA.encrypt(message, encoder, ENCODER_FORMAT);
} catch (final MslCryptoException e) {
fail(e.getMessage());
return;
}
cryptoContextB.decrypt(ciphertext, encoder);
}
@Test
public void wrapUnwrapOneBlock() throws MslCryptoException {
final byte[] keydataA = new byte[8];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(keydataA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.unwrap(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(keydataA, plaintextA);
final byte[] keydataB = new byte[8];
random.nextBytes(keydataB);
final byte[] ciphertextB = cryptoContext.wrap(keydataB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(keydataB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.unwrap(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(keydataB, plaintextB);
}
@Test
public void wrapUnwrapBlockAligned() throws MslCryptoException {
final byte[] keydataA = new byte[32];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(keydataA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.unwrap(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(keydataA, plaintextA);
final byte[] keydataB = new byte[32];
random.nextBytes(keydataB);
final byte[] ciphertextB = cryptoContext.wrap(keydataB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(keydataB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.unwrap(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(keydataB, plaintextB);
}
@Test
public void wrapBlockUnaligned() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE);
final byte[] keydataA = new byte[127];
random.nextBytes(keydataA);
cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
}
@Test
public void unwrapBlockUnaligned() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE);
final byte[] ciphertextA = new byte[127];
random.nextBytes(ciphertextA);
cryptoContext.unwrap(ciphertextA, encoder);
}
@Test
public void wrapNullWrap() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.WRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext= new SymmetricCryptoContext(ctx, KEYSET_ID, MockPresharedAuthenticationFactory.KPE, MockPresharedAuthenticationFactory.KPH, null);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
cryptoContext.wrap(messageA, encoder, ENCODER_FORMAT);
}
@Test
public void unwrapNullWrap() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.UNWRAP_NOT_SUPPORTED);
final ICryptoContext cryptoContext= new SymmetricCryptoContext(ctx, KEYSET_ID, MockPresharedAuthenticationFactory.KPE, MockPresharedAuthenticationFactory.KPH, null);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
cryptoContext.unwrap(messageA, encoder);
}
@Test
public void wrapUnwrapNullKeys() throws MslCryptoException {
final ICryptoContext cryptoContext = new SymmetricCryptoContext(ctx, KEYSET_ID, null, null, MockPresharedAuthenticationFactory.KPW);
final byte[] keydataA = new byte[32];
random.nextBytes(keydataA);
final byte[] ciphertextA = cryptoContext.wrap(keydataA, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextA);
assertThat(keydataA, is(not(ciphertextA)));
final byte[] plaintextA = cryptoContext.unwrap(ciphertextA, encoder);
assertNotNull(plaintextA);
assertArrayEquals(keydataA, plaintextA);
final byte[] keydataB = new byte[32];
random.nextBytes(keydataB);
final byte[] ciphertextB = cryptoContext.wrap(keydataB, encoder, ENCODER_FORMAT);
assertNotNull(ciphertextB);
assertThat(keydataB, is(not(ciphertextB)));
assertThat(ciphertextB, is(not(ciphertextA)));
final byte[] plaintextB = cryptoContext.unwrap(ciphertextB, encoder);
assertNotNull(plaintextB);
assertArrayEquals(keydataB, plaintextB);
}
@Test
public void unwrapUnalignedData() throws MslCryptoException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE);
final byte[] keydataA = new byte[1];
random.nextBytes(keydataA);
cryptoContext.unwrap(keydataA, encoder);
}
@Test
public void rfcWrapUnwrap() throws MslEntityAuthException, MslCryptoException {
final SecretKey wrappingKey = new SecretKeySpec(RFC_KEY, JcaAlgorithm.AESKW);
final ICryptoContext cryptoContext = new SymmetricCryptoContext(ctx, "RFC", null, null, wrappingKey);
final byte[] wrapped = cryptoContext.wrap(RFC_PLAINTEXT, encoder, ENCODER_FORMAT);
assertArrayEquals(RFC_CIPHERTEXT, wrapped);
final byte[] unwrapped = cryptoContext.unwrap(wrapped, encoder);
assertArrayEquals(RFC_PLAINTEXT, unwrapped);
}
@Test
public void signVerify() throws MslCryptoException, MslEncodingException, MslMasterTokenException {
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] signatureA = cryptoContext.sign(messageA, encoder, ENCODER_FORMAT);
assertNotNull(signatureA);
assertTrue(signatureA.length > 0);
assertThat(messageA, is(not(signatureA)));
assertTrue(cryptoContext.verify(messageA, signatureA, encoder));
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] signatureB = cryptoContext.sign(messageB, encoder, ENCODER_FORMAT);
assertTrue(signatureB.length > 0);
assertThat(signatureA, is(not(signatureB)));
assertTrue(cryptoContext.verify(messageB, signatureB, encoder));
assertFalse(cryptoContext.verify(messageB, signatureA, encoder));
}
@Test
public void signVerifyContextMismatch() throws MslEncodingException, MslEncoderException, MslCryptoException {
final ICryptoContext cryptoContextA = new SymmetricCryptoContext(ctx, KEYSET_ID, MockPresharedAuthenticationFactory.KPE, MockPresharedAuthenticationFactory.KPH, MockPresharedAuthenticationFactory.KPW);
final ICryptoContext cryptoContextB = new SymmetricCryptoContext(ctx, KEYSET_ID, MockPresharedAuthenticationFactory.KPE2, MockPresharedAuthenticationFactory.KPH2, MockPresharedAuthenticationFactory.KPW2);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] signature = cryptoContextA.sign(message, encoder, ENCODER_FORMAT);
assertFalse(cryptoContextB.verify(message, signature, encoder));
}
@Test
public void signVerifyNullKeys() throws MslCryptoException, MslEncodingException, MslEncoderException {
final ICryptoContext cryptoContext = new SymmetricCryptoContext(ctx, KEYSET_ID, null, MockPresharedAuthenticationFactory.KPH, null);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
final byte[] signatureA = cryptoContext.sign(messageA, encoder, ENCODER_FORMAT);
assertNotNull(signatureA);
assertTrue(signatureA.length > 0);
assertThat(messageA, is(not(signatureA)));
assertTrue(cryptoContext.verify(messageA, signatureA, encoder));
final byte[] messageB = new byte[32];
random.nextBytes(messageB);
final byte[] signatureB = cryptoContext.sign(messageB, encoder, ENCODER_FORMAT);
assertTrue(signatureB.length > 0);
assertThat(signatureA, is(not(signatureB)));
assertTrue(cryptoContext.verify(messageB, signatureB, encoder));
assertFalse(cryptoContext.verify(messageB, signatureA, encoder));
}
@Test
public void signNullHmac() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.SIGN_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new SymmetricCryptoContext(ctx, KEYSET_ID, MockPresharedAuthenticationFactory.KPE, null, MockPresharedAuthenticationFactory.KPW);
final byte[] messageA = new byte[32];
random.nextBytes(messageA);
cryptoContext.sign(messageA, encoder, ENCODER_FORMAT);
}
@Test
public void verifyNullHmac() throws MslCryptoException, MslEncodingException, MslEncoderException {
thrown.expect(MslCryptoException.class);
thrown.expectMslError(MslError.VERIFY_NOT_SUPPORTED);
final ICryptoContext cryptoContext = new SymmetricCryptoContext(ctx, KEYSET_ID, MockPresharedAuthenticationFactory.KPE, null, MockPresharedAuthenticationFactory.KPW);
final byte[] message = new byte[32];
random.nextBytes(message);
final byte[] signature = new byte[32];
random.nextBytes(signature);
cryptoContext.verify(message, signature, encoder);
}
/** MSL context. */
private static MslContext ctx;
/** MSL encoder factory. */
private static MslEncoderFactory encoder;
/** Random. */
private static Random random;
}
| 1,796 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/util/Base64Test.java
|
/**
* Copyright (c) 2016-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.util;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import javax.xml.bind.DatatypeConverter;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.netflix.msl.util.Base64.Base64Impl;
/**
* Base64 tests.
*
* @author Wesley Miaw <[email protected]>
*/
@RunWith(Parameterized.class)
public class Base64Test {
/** UTF-8 charset. */
private static final Charset CHARSET = Charset.forName("utf-8");
/** Binary Base64 example. */
private static final String BINARY_B64 = "R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAKgALAAAAAA9AEQAAAj/AFEJHEiwoMGDCBMqXMiwocAbBww4nEhxoYkUpzJGrMixogkfGUNqlNixJEIDB0SqHGmyJSojM1bKZOmyop0gM3Oe2liTISKMOoPy7GnwY9CjIYcSRYm0aVKSLmE6nfq05QycVLPuhDrxBlCtYJUqNAq2bNWEBj6ZXRuyxZyDRtqwnXvkhACDV+euTeJm1Ki7A73qNWtFiF+/gA95Gly2CJLDhwEHMOUAAuOpLYDEgBxZ4GRTlC1fDnpkM+fOqD6DDj1aZpITp0dtGCDhr+fVuCu3zlg49ijaokTZTo27uG7Gjn2P+hI8+PDPERoUB318bWbfAJ5sUNFcuGRTYUqV/3ogfXp1rWlMc6awJjiAAd2fm4ogXjz56aypOoIde4OE5u/F9x199dlXnnGiHZWEYbGpsAEA3QXYnHwEFliKAgswgJ8LPeiUXGwedCAKABACCN+EA1pYIIYaFlcDhytd51sGAJbo3onOpajiihlO92KHGaUXGwWjUBChjSPiWJuOO/LYIm4v1tXfE6J4gCSJEZ7YgRYUNrkji9P55sF/ogxw5ZkSqIDaZBV6aSGYq/lGZplndkckZ98xoICbTcIJGQAZcNmdmUc210hs35nCyJ58fgmIKX5RQGOZowxaZwYA+JaoKQwswGijBV4C6SiTUmpphMspJx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+yXqqBANsgCtit4FWQAEkrNbpq7HSOmtwag5w57GrmlJBASEU18ADjUYb3ADTinIttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==";
/** Standard Base64 examples. */
private static final Object[][] EXAMPLES = {
{ "The long winded author is going for a walk while the light breeze bellows in his ears.".getBytes(CHARSET),
"VGhlIGxvbmcgd2luZGVkIGF1dGhvciBpcyBnb2luZyBmb3IgYSB3YWxrIHdoaWxlIHRoZSBsaWdodCBicmVlemUgYmVsbG93cyBpbiBoaXMgZWFycy4=" },
{ "Sometimes porcupines need beds to sleep on.".getBytes(CHARSET),
"U29tZXRpbWVzIHBvcmN1cGluZXMgbmVlZCBiZWRzIHRvIHNsZWVwIG9uLg==" },
{ "Even the restless dreamer enjoys home-cooked foods.".getBytes(CHARSET),
"RXZlbiB0aGUgcmVzdGxlc3MgZHJlYW1lciBlbmpveXMgaG9tZS1jb29rZWQgZm9vZHMu" },
// We use DatatypeConverter here knowing BINARY_B64 is valid and that
// DatatypeConverter is functionally correct.
{ DatatypeConverter.parseBase64Binary(BINARY_B64),
BINARY_B64 },
};
/** Invalid Base64 examples. */
private static final String[] INVALID_EXAMPLES = {
"AAAAA",
"AAAAAAA",
"%$#@=",
"ZZZZZZZZZZ=",
"ZZZZZZZZZ==",
"U29tZXRpbWVzIHBvcmN1cGluZX=gbmVlZCBiZWRzIHRvIHNsZWVwIG9uLg==",
"RXZlbiB0aGUgcmVzdGxlc3MgZHJ=YW1lciBlbmpveXMgaG9tZS1jb29rZWQgZm9vZHMu",
"RXZlbiB0aGUgcmVzdGxlc3MgZHJ=Y",
"VGhlIGxvbmcgd2luZGVkIGF1dGhvciBpcyBnb2luZyBmb3IgY幸B3YWxrIHdoaWxlIHRoZSBsaWdodCBicmVlemUgYmVsbG93cyBpbiBoaXMgZWFycy4=",
};
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ new Base64Jaxb() },
{ new Base64Secure() }
});
}
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* @param impl Base64 encode/decode implementation.
*/
public Base64Test(final Base64Impl impl) {
Base64.setImpl(impl);
}
@Test
public void standard() {
for (int i = 0; i < EXAMPLES.length; ++i) {
// Prepare.
final Object[] example = EXAMPLES[i];
final byte[] data = (byte[])example[0];
final String base64 = (String)example[1];
// Encode/decode.
final String encoded = Base64.encode(data);
final byte[] decoded = Base64.decode(base64);
// Validate.
assertEquals(base64, encoded);
assertArrayEquals(data, decoded);
}
}
@Test
public void whitespace() {
for (int i = 0; i < EXAMPLES.length; ++i) {
// Prepare.
final Object[] example = EXAMPLES[i];
final byte[] data = (byte[])example[0];
final String base64 = (String)example[1];
// Modify.
final int half = base64.length() / 2;
final String modifiedBase64 = " \t" + base64.substring(0, half) + "\r\n \r\n\t" + base64.substring(half) + " \t \n";
// Encode/decode.
final String encoded = Base64.encode(data);
final byte[] decoded = Base64.decode(modifiedBase64);
// Validate.
assertEquals(base64, encoded);
assertArrayEquals(data, decoded);
}
}
@Test
public void invalidPadding() {
for (int i = 0; i < EXAMPLES.length; ++i) {
// Prepare.
final Object[] example = EXAMPLES[i];
final String base64 = (String)example[1];
// Modify.
final String modifiedBase64 = base64 + "=";
// Decode.
boolean invalid = false;
try {
Base64.decode(modifiedBase64);
} catch (final IllegalArgumentException e) {
invalid = true;
}
assertTrue(invalid);
}
}
@Test
public void injectedPadding() {
for (int i = 0; i < EXAMPLES.length; ++i) {
// Prepare.
final Object[] example = EXAMPLES[i];
final String base64 = (String)example[1];
// Modify.
final int half = base64.length() / 2;
final String modifiedBase64 = base64.substring(0, half) + "=" + base64.substring(half);
// Decode.
boolean invalid = false;
try {
Base64.decode(modifiedBase64);
} catch (final IllegalArgumentException e) {
invalid = true;
}
assertTrue(invalid);
}
}
@Test
public void invalidCharacter() {
for (int i = 0; i < EXAMPLES.length; ++i) {
// Prepare.
final Object[] example = EXAMPLES[i];
final String base64 = (String)example[1];
// Modify.
final int half = base64.length() / 2;
final String modifiedBase64 = base64.substring(0, half) + "|" + base64.substring(half);
// Decode.
boolean invalid = false;
try {
Base64.decode(modifiedBase64);
} catch (final IllegalArgumentException e) {
invalid = true;
}
assertTrue(invalid);
}
}
@Test
public void outOfRangeCharacter() {
for (int i = 0; i < EXAMPLES.length; ++i) {
// Prepare.
final Object[] example = EXAMPLES[i];
final String base64 = (String)example[1];
// Modify.
final int half = base64.length() / 2;
final String modifiedBase64 = base64.substring(0, half) + new String(new byte[] {(byte)128}) + base64.substring(half);
// Decode.
boolean invalid = false;
try {
Base64.decode(modifiedBase64);
} catch (final IllegalArgumentException e) {
invalid = true;
}
assertTrue(invalid);
}
}
@Test
public void invalidLength() {
for (int i = 0; i < EXAMPLES.length; ++i) {
// Prepare.
final Object[] example = EXAMPLES[i];
final String base64 = (String)example[1];
// Modify.
final String modifiedBase64 = base64.substring(1);
// Decode.
boolean invalid = false;
try {
Base64.decode(modifiedBase64);
} catch (final IllegalArgumentException e) {
invalid = true;
}
assertTrue(invalid);
}
}
@Test
public void invalid() {
for (int i = 0; i < INVALID_EXAMPLES.length; ++i) {
final String base64 = INVALID_EXAMPLES[i];
boolean invalid = false;
try {
Base64.decode(base64);
} catch (final IllegalArgumentException e) {
invalid = true;
}
assertTrue(invalid);
}
}
@Test
public void emptyString() {
final String base64 = "";
final byte[] b = Base64.decode(base64);
assertEquals(0, b.length);
}
}
| 1,797 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/util/MslCompressionTest.java
|
/**
* Copyright (c) 2018 Netflix, Inc. All rights reserved.
*/
package com.netflix.msl.util;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Rule;
import org.junit.Test;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.test.ExpectedMslException;
/**
* <p>MSL compression unit tests.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class MslCompressionTest {
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
@Test
public void compressRatioExceeded() throws MslException {
final byte[] codes = new byte[] {
(byte)0x00, (byte)0x80, (byte)0x40, (byte)0x60, (byte)0x50, (byte)0x38, (byte)0x24, (byte)0x16, (byte)0x0d, (byte)0x07, (byte)0x84, (byte)0x42, (byte)0x61, (byte)0x50, (byte)0xb8, (byte)0x64,
(byte)0x36, (byte)0x1d, (byte)0x0f, (byte)0x88, (byte)0x44, (byte)0x62, (byte)0x51, (byte)0x38, (byte)0xa4, (byte)0x56, (byte)0x2d, (byte)0x17, (byte)0x8c, (byte)0x46, (byte)0x63, (byte)0x51,
(byte)0xb8, (byte)0xe4, (byte)0x76, (byte)0x3d, (byte)0x1f, (byte)0x90, (byte)0x48, (byte)0x64, (byte)0x52, (byte)0x39, (byte)0x24, (byte)0x96, (byte)0x4d, (byte)0x27, (byte)0x94, (byte)0x4a,
(byte)0x65, (byte)0x52, (byte)0x00 };
final byte[] data = new byte[1024];
final byte[] compressed = MslCompression.compress(CompressionAlgorithm.LZW, data);
assertArrayEquals(codes, compressed);
final byte[] uncompressed = MslCompression.uncompress(CompressionAlgorithm.LZW, codes);
assertArrayEquals(data, uncompressed);
thrown.expect(MslException.class);
thrown.expectMslError(MslError.UNCOMPRESSION_ERROR);
MslCompression.setMaxDeflateRatio(10);
MslCompression.uncompress(CompressionAlgorithm.LZW, codes);
}
}
| 1,798 |
0 |
Create_ds/msl/tests/src/test/java/com/netflix/msl
|
Create_ds/msl/tests/src/test/java/com/netflix/msl/util/SimpleMslStoreTest.java
|
/**
* Copyright (c) 2012-2020 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.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.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.MslInternalException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.NullCryptoContext;
import com.netflix.msl.crypto.SessionCryptoContext;
import com.netflix.msl.crypto.SymmetricCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.test.ExpectedMslException;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.MockEmailPasswordAuthenticationFactory;
/**
* Simple MSL store unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleMslStoreTest {
private static final String KEYSET_ID = "keyset";
private static final String USER_ID = "userid";
/** Maximum number of randomly generated tokens. */
private static final int MAX_TOKENS = 3;
/** Stress test pool shutdown timeout in milliseconds. */
private static final int STRESS_TIMEOUT_MILLIS = 3000;
/**
* @param c1 first collection.
* @param c2 second collection.
* @return true if each collection contain all elements found in the other.
*/
private static boolean equal(final Collection<? extends Object> c1, final Collection<? extends Object> c2) {
return c1.containsAll(c2) && c2.containsAll(c1);
}
@Rule
public ExpectedMslException thrown = ExpectedMslException.none();
@BeforeClass
public static void setup() throws MslEncodingException, MslCryptoException {
ctx = new MockMslContext(EntityAuthenticationScheme.NONE, false);
}
@AfterClass
public static void teardown() {
ctx = null;
}
@Before
public void createStore() {
store = new SimpleMslStore();
}
@After
public void destroyStore() {
store = null;
}
@Test
public void storeCryptoContext() throws MslEncodingException, MslCryptoException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
assertNull(store.getCryptoContext(masterToken));
final ICryptoContext cc1 = new SymmetricCryptoContext(ctx, KEYSET_ID, masterToken.getEncryptionKey(), masterToken.getSignatureKey(), null);
store.setCryptoContext(masterToken, cc1);
final ICryptoContext cc2 = store.getCryptoContext(masterToken);
assertNotNull(cc2);
assertSame(cc1, cc2);
assertEquals(masterToken, store.getMasterToken());
}
@Test
public void replaceCryptoContext() throws MslEncodingException, MslCryptoException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final ICryptoContext cc1 = new SymmetricCryptoContext(ctx, KEYSET_ID, masterToken.getEncryptionKey(), masterToken.getSignatureKey(), null);
final ICryptoContext cc2 = new NullCryptoContext();
store.setCryptoContext(masterToken, cc1);
final ICryptoContext cc3 = store.getCryptoContext(masterToken);
assertSame(cc1, cc3);
assertNotSame(cc2, cc3);
store.setCryptoContext(masterToken, cc2);
final ICryptoContext cc4 = store.getCryptoContext(masterToken);
assertNotSame(cc1, cc4);
assertSame(cc2, cc4);
assertEquals(masterToken, store.getMasterToken());
}
@Test
public void removeCryptoContext() throws MslEncodingException, MslCryptoException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final ICryptoContext cryptoContext = new NullCryptoContext();
store.setCryptoContext(masterToken, cryptoContext);
store.removeCryptoContext(masterToken);
assertNull(store.getMasterToken());
assertNull(store.getCryptoContext(masterToken));
}
@Test
public void clearCryptoContext() throws MslEncodingException, MslCryptoException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final ICryptoContext cc1 = new SymmetricCryptoContext(ctx, KEYSET_ID, masterToken.getEncryptionKey(), masterToken.getSignatureKey(), null);
store.setCryptoContext(masterToken, cc1);
store.clearCryptoContexts();
assertNull(store.getCryptoContext(masterToken));
assertNull(store.getMasterToken());
}
@Test
public void twoCryptoContexts() throws MslEncodingException, MslCryptoException, MslMasterTokenException {
final MasterToken mtA = MslTestUtils.getMasterToken(ctx, 1, 1);
final MasterToken mtB = MslTestUtils.getMasterToken(ctx, 2, 1);
final ICryptoContext ccMtA1 = new SessionCryptoContext(ctx, mtA);
final ICryptoContext ccMtB1 = new SessionCryptoContext(ctx, mtB);
store.setCryptoContext(mtA, ccMtA1);
store.setCryptoContext(mtB, ccMtB1);
final ICryptoContext ccMtA2 = store.getCryptoContext(mtA);
assertNotNull(ccMtA2);
assertSame(ccMtA1, ccMtA2);
final ICryptoContext ccMtB2 = store.getCryptoContext(mtB);
assertNotNull(ccMtB2);
assertSame(ccMtB1, ccMtB2);
assertEquals(mtB, store.getMasterToken());
}
@Test
public void replaceTwoCryptoContexts() throws MslEncodingException, MslCryptoException, MslMasterTokenException {
final MasterToken mtA = MslTestUtils.getMasterToken(ctx, 1, 1);
final MasterToken mtB = MslTestUtils.getMasterToken(ctx, 2, 1);
final ICryptoContext ccMtA1 = new SessionCryptoContext(ctx, mtA);
final ICryptoContext ccMtB1 = new SessionCryptoContext(ctx, mtB);
store.setCryptoContext(mtA, ccMtA1);
store.setCryptoContext(mtB, ccMtB1);
assertEquals(mtB, store.getMasterToken());
final ICryptoContext ccNull = new NullCryptoContext();
store.setCryptoContext(mtA, ccNull);
final ICryptoContext ccMtA2 = store.getCryptoContext(mtA);
assertNotNull(ccMtA2);
assertNotSame(ccMtA1, ccMtA2);
assertSame(ccNull, ccMtA2);
final ICryptoContext ccMtB2 = store.getCryptoContext(mtB);
assertNotNull(ccMtB2);
assertSame(ccMtB1, ccMtB2);
assertEquals(mtB, store.getMasterToken());
}
@Test
public void clearTwoCryptoContexts() throws MslEncodingException, MslCryptoException, MslMasterTokenException {
final MasterToken mtA = MslTestUtils.getMasterToken(ctx, 1, 1);
final MasterToken mtB = MslTestUtils.getMasterToken(ctx, 2, 1);
final ICryptoContext ccMtA1 = new SessionCryptoContext(ctx, mtA);
final ICryptoContext ccMtB1 = new SessionCryptoContext(ctx, mtB);
store.setCryptoContext(mtA, ccMtA1);
store.setCryptoContext(mtB, ccMtB1);
store.clearCryptoContexts();
assertNull(store.getCryptoContext(mtA));
assertNull(store.getCryptoContext(mtB));
assertNull(store.getMasterToken());
}
@Test
public void removeTwoCryptoContexts() throws MslEncodingException, MslCryptoException, MslMasterTokenException {
final MasterToken mtA = MslTestUtils.getMasterToken(ctx, 1, 1);
final MasterToken mtB = MslTestUtils.getMasterToken(ctx, 2, 1);
final ICryptoContext ccMtA1 = new SessionCryptoContext(ctx, mtA);
final ICryptoContext ccMtB1 = new SessionCryptoContext(ctx, mtB);
store.setCryptoContext(mtA, ccMtA1);
store.setCryptoContext(mtB, ccMtB1);
store.removeCryptoContext(mtA);
assertNull(store.getCryptoContext(mtA));
assertEquals(ccMtB1, store.getCryptoContext(mtB));
}
/**
* Crypto context add/remove stress test runner.
*
* Randomly adds or removes a crypto context for one of many master tokens
* (by master token entity identity). Also iterates through the set crypto
* contexts.
*/
private static class CryptoContextStressor implements Runnable {
/**
* Create a new crypto context stressor.
*
* @param ctx MSL context.
* @param store MSL store.
* @param count the number of master token identities to stress.
*/
public CryptoContextStressor(final MslContext ctx, final MslStore store, final int count) {
this.ctx = ctx;
this.store = store;
this.count = count;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
final Random r = new Random();
try {
for (int i = 0; i < 10 * count; ++i) {
final int tokenIndex = r.nextInt(count);
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, tokenIndex, 1);
final int option = r.nextInt(4);
switch (option) {
case 0:
store.setCryptoContext(masterToken, null);
break;
case 1:
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken);
store.setCryptoContext(masterToken, cryptoContext);
break;
case 2:
store.getCryptoContext(masterToken);
break;
case 3:
store.removeCryptoContext(masterToken);
break;
}
}
} catch (final MslMasterTokenException e) {
throw new MslInternalException("Unexpected master token exception.", e);
} catch (final MslEncodingException e) {
throw new MslInternalException("Unexpected master token encoding exception.", e);
} catch (final MslCryptoException e) {
throw new MslInternalException("Unexpected master token creation exception.", e);
}
}
/** MSL context. */
private final MslContext ctx;
/** MSL store. */
private final MslStore store;
/** Number of crypto context identities. */
private final int count;
}
@Test
public void stressCryptoContexts() throws InterruptedException, MslEncodingException, MslCryptoException {
final ExecutorService service = Executors.newCachedThreadPool();
for (int i = 0; i < 10 * MAX_TOKENS; ++i) {
service.execute(new CryptoContextStressor(ctx, store, MAX_TOKENS));
}
service.shutdown();
assertTrue(service.awaitTermination(STRESS_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
}
@Test
public void nonReplayableId() throws MslEncodingException, MslCryptoException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
for (int i = 1; i < 10; ++i)
assertEquals(i, store.getNonReplayableId(masterToken));
}
@Ignore
@Test
public void wrappedNonReplayableId() throws MslEncodingException, MslCryptoException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
for (long i = 1; i < MslConstants.MAX_LONG_VALUE; ++i)
store.getNonReplayableId(masterToken);
assertEquals(MslConstants.MAX_LONG_VALUE, store.getNonReplayableId(masterToken));
assertEquals(0, store.getNonReplayableId(masterToken));
assertEquals(1, store.getNonReplayableId(masterToken));
}
@Test
public void twoNonReplayableIds() throws MslEncodingException, MslCryptoException {
final MasterToken masterTokenA = MslTestUtils.getMasterToken(ctx, 1, 1);
final MasterToken masterTokenB = MslTestUtils.getMasterToken(ctx, 1, 2);
for (int i = 1; i < 10; ++i) {
assertEquals(i, store.getNonReplayableId(masterTokenA));
assertEquals(i, store.getNonReplayableId(masterTokenB));
}
}
@Test
public void addUserIdToken() throws MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final ICryptoContext cryptoContext = new NullCryptoContext();
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(USER_ID, userIdToken);
assertEquals(userIdToken, store.getUserIdToken(USER_ID));
assertNull(store.getUserIdToken(USER_ID + "x"));
}
@Test
public void removeUserIdToken() throws MslEncodingException, MslCryptoException, MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final ICryptoContext cryptoContext = new NullCryptoContext();
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(USER_ID, userIdToken);
store.removeUserIdToken(userIdToken);
assertNull(store.getUserIdToken(USER_ID));
}
@Test
public void replaceUserIdToken() throws MslEncodingException, MslCryptoException, MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final ICryptoContext cryptoContext = new NullCryptoContext();
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterToken, 2, MockEmailPasswordAuthenticationFactory.USER);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(USER_ID, userIdTokenA);
store.addUserIdToken(USER_ID, userIdTokenB);
assertEquals(userIdTokenB, store.getUserIdToken(USER_ID));
}
@Test
public void twoUserIdTokens() throws MslEncodingException, MslCryptoException, MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterToken, 2, MockEmailPasswordAuthenticationFactory.USER);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
assertEquals(userIdTokenA, store.getUserIdToken(userIdA));
assertEquals(userIdTokenB, store.getUserIdToken(userIdB));
}
@Test
public void replaceTwoUserIdTokens() throws MslEncodingException, MslCryptoException, MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterToken, 2, MockEmailPasswordAuthenticationFactory.USER);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
final UserIdToken userIdTokenC = MslTestUtils.getUserIdToken(ctx, masterToken, 3, MockEmailPasswordAuthenticationFactory.USER);
store.addUserIdToken(userIdA, userIdTokenC);
assertEquals(userIdTokenC, store.getUserIdToken(userIdA));
assertEquals(userIdTokenB, store.getUserIdToken(userIdB));
}
@Test
public void removeTwoUserIdTokens() throws MslEncodingException, MslCryptoException, MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterToken, 2, MockEmailPasswordAuthenticationFactory.USER);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
store.removeUserIdToken(userIdTokenA);
assertNull(store.getUserIdToken(userIdA));
assertEquals(userIdTokenB, store.getUserIdToken(userIdB));
}
@Test
public void clearUserIdTokens() throws MslEncodingException, MslCryptoException, MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterToken, 2, MockEmailPasswordAuthenticationFactory.USER);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
store.clearUserIdTokens();
assertNull(store.getUserIdToken(userIdA));
assertNull(store.getUserIdToken(userIdB));
}
@Test
public void unknownMasterTokenUserIdToken() throws MslEncodingException, MslCryptoException, MslException {
thrown.expect(MslException.class);
thrown.expectMslError(MslError.USERIDTOKEN_MASTERTOKEN_NOT_FOUND);
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
store.addUserIdToken(USER_ID, userIdToken);
}
@Test
public void removeMasterTokenSameSerialNumberUserIdTokens() throws MslEncodingException, MslCryptoException, MslException {
final MasterToken masterTokenA = MslTestUtils.getMasterToken(ctx, 1, 1);
final MasterToken masterTokenB = MslTestUtils.getMasterToken(ctx, 2, 1);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final String userIdC = USER_ID + "C";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterTokenA, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterTokenA, 2, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenC = MslTestUtils.getUserIdToken(ctx, masterTokenB, 1, MockEmailPasswordAuthenticationFactory.USER);
store.setCryptoContext(masterTokenA, cryptoContext);
store.setCryptoContext(masterTokenB, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
store.addUserIdToken(userIdC, userIdTokenC);
// We still have a master token with serial number 1 so no user ID
// tokens should be deleted.
store.removeCryptoContext(masterTokenA);
assertEquals(userIdTokenA, store.getUserIdToken(userIdA));
assertEquals(userIdTokenB, store.getUserIdToken(userIdB));
assertEquals(userIdTokenC, store.getUserIdToken(userIdC));
}
@Test
public void removeMasterTokenReissuedUserIdTokens() throws MslEncodingException, MslCryptoException, MslException {
// Master token B has a new serial number, to invalidate the old master
// token and its user ID tokens.
final MasterToken masterTokenA = MslTestUtils.getMasterToken(ctx, 1, 1);
final MasterToken masterTokenB = MslTestUtils.getMasterToken(ctx, 1, 2);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final String userIdC = USER_ID + "C";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterTokenA, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterTokenA, 2, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenC = MslTestUtils.getUserIdToken(ctx, masterTokenB, 1, MockEmailPasswordAuthenticationFactory.USER);
store.setCryptoContext(masterTokenA, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
store.setCryptoContext(masterTokenB, cryptoContext);
store.addUserIdToken(userIdC, userIdTokenC);
// All of master token A's user ID tokens should be deleted.
store.removeCryptoContext(masterTokenA);
assertNull(store.getUserIdToken(userIdA));
assertNull(store.getUserIdToken(userIdB));
assertEquals(userIdTokenC, store.getUserIdToken(userIdC));
}
@Test
public void clearCryptoContextsUserIdTokens() throws MslEncodingException, MslCryptoException, MslException {
// Master token B has a new serial number, to invalidate the old master
// token and its user ID tokens.
final MasterToken masterTokenA = MslTestUtils.getMasterToken(ctx, 1, 1);
final MasterToken masterTokenB = MslTestUtils.getMasterToken(ctx, 1, 2);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterTokenA, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterTokenB, 2, MockEmailPasswordAuthenticationFactory.USER);
store.setCryptoContext(masterTokenA, cryptoContext);
store.setCryptoContext(masterTokenB, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
// All user ID tokens should be deleted.
store.clearCryptoContexts();
assertNull(store.getUserIdToken(userIdA));
assertNull(store.getUserIdToken(userIdB));
}
/**
* User ID token add/remove stress test runner.
*
* Randomly adds or removes user ID tokens. Also iterates through the user
* ID tokens.
*/
private static class UserIdTokenStressor implements Runnable {
/**
* Create a new service token stressor.
*
* @param ctx MSL context.
* @param store MSL store.
* @param count the number of master token and user ID tokens to create
* combinations of.
*/
public UserIdTokenStressor(final MslContext ctx, final MslStore store, final int count) {
this.ctx = ctx;
this.store = store;
this.count = count;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
final Random r = new Random();
try {
for (int i = 0; i < 10 * count; ++i) {
final int tokenIndex = r.nextInt(count);
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, tokenIndex, 1);
final long userId = r.nextInt(count);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, userId, MockEmailPasswordAuthenticationFactory.USER);
final int option = r.nextInt(3);
switch (option) {
case 0:
{
store.setCryptoContext(masterToken, new NullCryptoContext());
store.addUserIdToken(USER_ID + userId, userIdToken);
break;
}
case 1:
{
store.getUserIdToken(USER_ID + userId);
break;
}
case 2:
{
store.removeUserIdToken(userIdToken);
break;
}
}
}
} catch (final MslMasterTokenException e) {
throw new MslInternalException("Unexpected master token exception.", e);
} catch (final MslEncodingException e) {
throw new MslInternalException("Unexpected master token encoding exception.", e);
} catch (final MslCryptoException e) {
throw new MslInternalException("Unexpected master token creation exception.", e);
} catch (final MslException e) {
throw new MslInternalException("Master token / user ID token service token query mismatch.", e);
}
}
/** MSL context. */
private final MslContext ctx;
/** MSL store. */
private final MslStore store;
/** Number of master token and user ID token identities. */
private final int count;
}
@Test
public void stressUserIdTokens() throws InterruptedException {
final ExecutorService service = Executors.newCachedThreadPool();
for (int i = 0; i < 10 * MAX_TOKENS; ++i) {
service.execute(new UserIdTokenStressor(ctx, store, MAX_TOKENS));
}
service.shutdown();
assertTrue(service.awaitTermination(STRESS_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
}
@Test
public void masterBoundServiceTokens() throws MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final ICryptoContext cryptoContext = new NullCryptoContext();
final Set<ServiceToken> tokens = MslTestUtils.getServiceTokens(ctx, masterToken, null);
store.setCryptoContext(masterToken, cryptoContext);
final Set<ServiceToken> emptyTokens = store.getServiceTokens(masterToken, null);
assertNotNull(emptyTokens);
assertEquals(0, emptyTokens.size());
store.addServiceTokens(tokens);
final Set<ServiceToken> storedTokens = store.getServiceTokens(masterToken, null);
assertNotNull(storedTokens);
assertTrue(equal(tokens, storedTokens));
}
@Test
public void missingMasterTokenAddServiceTokens() throws MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final Set<ServiceToken> tokens = MslTestUtils.getServiceTokens(ctx, masterToken, null);
MslException exception = null;
try {
store.addServiceTokens(tokens);
} catch (final MslException e) {
exception = e;
}
assertNotNull(exception);
final Set<ServiceToken> emptyTokens = store.getServiceTokens(masterToken, null);
assertNotNull(emptyTokens);
assertEquals(0, emptyTokens.size());
}
@Test
public void userBoundServiceTokens() throws MslEncodingException, MslCryptoException, MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final ICryptoContext cryptoContext = new NullCryptoContext();
final Set<ServiceToken> tokens = MslTestUtils.getServiceTokens(ctx, masterToken, userIdToken);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(USER_ID, userIdToken);
final Set<ServiceToken> emptyTokens = store.getServiceTokens(masterToken, userIdToken);
assertNotNull(emptyTokens);
assertEquals(0, emptyTokens.size());
store.addServiceTokens(tokens);
final Set<ServiceToken> storedTokens = store.getServiceTokens(masterToken, userIdToken);
assertNotNull(storedTokens);
assertTrue(equal(tokens, storedTokens));
}
@Test
public void missingUserIdTokenAddServiceTokens() throws MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final ICryptoContext cryptoContext = new NullCryptoContext();
final Set<ServiceToken> tokens = MslTestUtils.getServiceTokens(ctx, masterToken, userIdToken);
store.setCryptoContext(masterToken, cryptoContext);
MslException exception = null;
try {
store.addServiceTokens(tokens);
} catch (final MslException e) {
exception = e;
}
assertNotNull(exception);
final Set<ServiceToken> emptyTokens = store.getServiceTokens(masterToken, null);
assertNotNull(emptyTokens);
assertEquals(0, emptyTokens.size());
}
@Test
public void unboundServiceTokens() throws MslException {
final Set<ServiceToken> tokens = MslTestUtils.getServiceTokens(ctx, null, null);
final Set<ServiceToken> emptyTokens = store.getServiceTokens(null, null);
assertNotNull(emptyTokens);
assertEquals(0, emptyTokens.size());
store.addServiceTokens(tokens);
final Set<ServiceToken> storedTokens = store.getServiceTokens(null, null);
assertNotNull(storedTokens);
assertTrue(equal(tokens, storedTokens));
}
@Test
public void removeMasterBoundServiceTokens() throws MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final ICryptoContext cryptoContext = new NullCryptoContext();
final Set<ServiceToken> masterBoundTokens = MslTestUtils.getMasterBoundServiceTokens(ctx, masterToken);
final Set<ServiceToken> userBoundTokens = MslTestUtils.getUserBoundServiceTokens(ctx, masterToken, userIdToken);
final Set<ServiceToken> unboundTokens = MslTestUtils.getServiceTokens(ctx, null, null);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(USER_ID, userIdToken);
store.addServiceTokens(masterBoundTokens);
store.addServiceTokens(userBoundTokens);
store.addServiceTokens(unboundTokens);
store.removeServiceTokens(null, masterToken, null);
// This should only return the unbound tokens.
final Set<ServiceToken> storedMasterBoundTokens = store.getServiceTokens(masterToken, null);
assertNotNull(storedMasterBoundTokens);
assertTrue(equal(unboundTokens, storedMasterBoundTokens));
// This should only return the unbound and user-bound tokens.
final Set<ServiceToken> unboundAndUserBoundTokens = new HashSet<ServiceToken>();
unboundAndUserBoundTokens.addAll(unboundTokens);
unboundAndUserBoundTokens.addAll(userBoundTokens);
final Set<ServiceToken> storedUserBoundTokens = store.getServiceTokens(masterToken, userIdToken);
assertTrue(equal(unboundAndUserBoundTokens, storedUserBoundTokens));
// This should only return the unbound tokens.
final Set<ServiceToken> storedUnboundTokens = store.getServiceTokens(null, null);
assertNotNull(storedUnboundTokens);
assertTrue(equal(unboundTokens, storedUnboundTokens));
}
@Test
public void removeUserBoundServiceTokens() throws MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final ICryptoContext cryptoContext = new NullCryptoContext();
final Set<ServiceToken> masterBoundTokens = MslTestUtils.getMasterBoundServiceTokens(ctx, masterToken);
final Set<ServiceToken> userBoundTokens = MslTestUtils.getUserBoundServiceTokens(ctx, masterToken, userIdToken);
final Set<ServiceToken> unboundTokens = MslTestUtils.getServiceTokens(ctx, null, null);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(USER_ID, userIdToken);
store.addServiceTokens(masterBoundTokens);
store.addServiceTokens(userBoundTokens);
store.addServiceTokens(unboundTokens);
store.removeServiceTokens(null, null, userIdToken);
// This should only return the unbound and master bound-only tokens.
final Set<ServiceToken> storedMasterBoundTokens = store.getServiceTokens(masterToken, null);
assertNotNull(storedMasterBoundTokens);
final Set<ServiceToken> unboundAndMasterBoundTokens = new HashSet<ServiceToken>();
unboundAndMasterBoundTokens.addAll(unboundTokens);
unboundAndMasterBoundTokens.addAll(masterBoundTokens);
assertTrue(equal(unboundAndMasterBoundTokens, storedMasterBoundTokens));
// This should only return the unbound and master bound-only tokens.
final Set<ServiceToken> storedUserBoundTokens = store.getServiceTokens(masterToken, userIdToken);
assertNotNull(storedUserBoundTokens);
assertTrue(equal(unboundAndMasterBoundTokens, storedUserBoundTokens));
// This should only return the unbound tokens.
final Set<ServiceToken> storedUnboundTokens = store.getServiceTokens(null, null);
assertNotNull(storedUnboundTokens);
assertTrue(equal(unboundTokens, storedUnboundTokens));
}
@Test
public void removeNoServiceTokens() throws MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final ICryptoContext cryptoContext = new NullCryptoContext();
final Set<ServiceToken> masterBoundTokens = MslTestUtils.getMasterBoundServiceTokens(ctx, masterToken);
final Set<ServiceToken> userBoundTokens = MslTestUtils.getUserBoundServiceTokens(ctx, masterToken, userIdToken);
final Set<ServiceToken> unboundTokens = MslTestUtils.getServiceTokens(ctx, null, null);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(USER_ID, userIdToken);
store.addServiceTokens(masterBoundTokens);
store.addServiceTokens(userBoundTokens);
store.addServiceTokens(unboundTokens);
store.removeServiceTokens(null, null, null);
// This should only return the unbound and master bound tokens.
final Set<ServiceToken> storedMasterBoundTokens = store.getServiceTokens(masterToken, null);
assertNotNull(storedMasterBoundTokens);
final Set<ServiceToken> unboundAndMasterBoundTokens = new HashSet<ServiceToken>();
unboundAndMasterBoundTokens.addAll(unboundTokens);
unboundAndMasterBoundTokens.addAll(masterBoundTokens);
assertTrue(equal(unboundAndMasterBoundTokens, storedMasterBoundTokens));
// This should return all of the tokens.
final Set<ServiceToken> storedUserBoundTokens = store.getServiceTokens(masterToken, userIdToken);
assertNotNull(storedUserBoundTokens);
final Set<ServiceToken> allTokens = new HashSet<ServiceToken>();
allTokens.addAll(unboundTokens);
allTokens.addAll(userBoundTokens);
allTokens.addAll(masterBoundTokens);
assertTrue(equal(allTokens, storedUserBoundTokens));
// This should only return the unbound tokens.
final Set<ServiceToken> storedUnboundTokens = store.getServiceTokens(null, null);
assertNotNull(storedUnboundTokens);
assertTrue(equal(unboundTokens, storedUnboundTokens));
}
@Test
public void removeNamedServiceTokens() throws MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final ICryptoContext cryptoContext = new NullCryptoContext();
final Set<ServiceToken> masterBoundTokens = MslTestUtils.getMasterBoundServiceTokens(ctx, masterToken);
final Set<ServiceToken> userBoundTokens = MslTestUtils.getUserBoundServiceTokens(ctx, masterToken, userIdToken);
final Set<ServiceToken> unboundTokens = MslTestUtils.getServiceTokens(ctx, null, null);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(USER_ID, userIdToken);
store.addServiceTokens(masterBoundTokens);
store.addServiceTokens(userBoundTokens);
store.addServiceTokens(unboundTokens);
final Set<ServiceToken> allTokens = new HashSet<ServiceToken>();
allTokens.addAll(masterBoundTokens);
allTokens.addAll(userBoundTokens);
allTokens.addAll(unboundTokens);
final Random random = new Random();
final Set<ServiceToken> removedTokens = new HashSet<ServiceToken>();
for (final ServiceToken token : allTokens) {
if (random.nextBoolean()) continue;
store.removeServiceTokens(token.getName(), token.isMasterTokenBound() ? masterToken : null, token.isUserIdTokenBound() ? userIdToken : null);
removedTokens.add(token);
}
// This should only return tokens that haven't been removed.
final Set<ServiceToken> storedMasterBoundTokens = store.getServiceTokens(masterToken, null);
assertNotNull(storedMasterBoundTokens);
assertFalse(storedMasterBoundTokens.removeAll(removedTokens));
// This should only return tokens that haven't been removed.
final Set<ServiceToken> storedUserBoundTokens = store.getServiceTokens(masterToken, userIdToken);
assertNotNull(storedUserBoundTokens);
assertFalse(storedUserBoundTokens.removeAll(removedTokens));
// This should only return tokens that haven't been removed.
final Set<ServiceToken> storedUnboundTokens = store.getServiceTokens(null, null);
assertNotNull(storedUnboundTokens);
assertFalse(storedUnboundTokens.removeAll(removedTokens));
}
@Test
public void clearServiceTokens() throws MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final ICryptoContext cryptoContext = new NullCryptoContext();
final Set<ServiceToken> masterBoundTokens = MslTestUtils.getMasterBoundServiceTokens(ctx, masterToken);
final Set<ServiceToken> userBoundTokens = MslTestUtils.getUserBoundServiceTokens(ctx, masterToken, userIdToken);
final Set<ServiceToken> unboundTokens = MslTestUtils.getServiceTokens(ctx, null, null);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(USER_ID, userIdToken);
store.addServiceTokens(masterBoundTokens);
store.addServiceTokens(userBoundTokens);
store.addServiceTokens(unboundTokens);
store.clearServiceTokens();
final Set<ServiceToken> storedMasterBoundTokens = store.getServiceTokens(masterToken, null);
assertNotNull(storedMasterBoundTokens);
assertEquals(0, storedMasterBoundTokens.size());
final Set<ServiceToken> storedUserBoundTokens = store.getServiceTokens(masterToken, userIdToken);
assertNotNull(storedUserBoundTokens);
assertEquals(0, storedUserBoundTokens.size());
final Set<ServiceToken> storedUnboundTokens = store.getServiceTokens(null, null);
assertNotNull(storedUnboundTokens);
assertEquals(0, storedUserBoundTokens.size());
}
@Test
public void mismatchedGetServiceTokens() throws MslException {
thrown.expect(MslException.class);
thrown.expectMslError(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH);
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final MasterToken mismatchedMasterToken = MslTestUtils.getMasterToken(ctx, 2, 2);
store.getServiceTokens(mismatchedMasterToken, userIdToken);
}
@Test
public void missingMasterTokenGetServiceTokens() throws MslException {
thrown.expect(MslException.class);
thrown.expectMslError(MslError.USERIDTOKEN_MASTERTOKEN_NULL);
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
store.getServiceTokens(null, userIdToken);
}
@Test
public void mismatchedRemoveServiceTokens() throws MslException {
thrown.expect(MslException.class);
thrown.expectMslError(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH);
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final MasterToken mismatchedMasterToken = MslTestUtils.getMasterToken(ctx, 2, 2);
store.removeServiceTokens(null, mismatchedMasterToken, userIdToken);
}
@Test
public void removeMasterTokenSameSerialNumberServiceTokens() throws MslEncodingException, MslCryptoException, MslException {
final MasterToken masterTokenA = MslTestUtils.getMasterToken(ctx, 1, 1);
final MasterToken masterTokenB = MslTestUtils.getMasterToken(ctx, 2, 1);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterTokenA, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterTokenB, 2, MockEmailPasswordAuthenticationFactory.USER);
final Set<ServiceToken> masterBoundServiceTokens = MslTestUtils.getMasterBoundServiceTokens(ctx, masterTokenA);
final Set<ServiceToken> serviceTokensA = MslTestUtils.getUserBoundServiceTokens(ctx, masterTokenA, userIdTokenA);
final Set<ServiceToken> serviceTokensB = MslTestUtils.getUserBoundServiceTokens(ctx, masterTokenB, userIdTokenB);
store.setCryptoContext(masterTokenA, cryptoContext);
store.setCryptoContext(masterTokenB, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
store.addServiceTokens(masterBoundServiceTokens);
store.addServiceTokens(serviceTokensA);
store.addServiceTokens(serviceTokensB);
// We still have a master token with serial number 1 so no service
// tokens should have been deleted.
store.removeCryptoContext(masterTokenA);
final Set<ServiceToken> storedServiceTokensA = store.getServiceTokens(masterTokenB, userIdTokenA);
final Set<ServiceToken> storedServiceTokensB = store.getServiceTokens(masterTokenB, userIdTokenB);
final Set<ServiceToken> expectedServiceTokensA = new HashSet<ServiceToken>(masterBoundServiceTokens);
expectedServiceTokensA.addAll(serviceTokensA);
assertEquals(expectedServiceTokensA, storedServiceTokensA);
final Set<ServiceToken> expectedServiceTokensB = new HashSet<ServiceToken>(masterBoundServiceTokens);
expectedServiceTokensB.addAll(serviceTokensB);
assertEquals(expectedServiceTokensB, storedServiceTokensB);
}
@Test
public void removeMasterTokenReissuedServiceTokens() throws MslEncodingException, MslCryptoException, MslException {
// Master token B has a new serial number, to invalidate the old master
// token and its user ID tokens.
final MasterToken masterTokenA = MslTestUtils.getMasterToken(ctx, 1, 1);
final MasterToken masterTokenB = MslTestUtils.getMasterToken(ctx, 1, 2);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterTokenA, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterTokenB, 2, MockEmailPasswordAuthenticationFactory.USER);
final Set<ServiceToken> masterBoundServiceTokens = MslTestUtils.getMasterBoundServiceTokens(ctx, masterTokenA);
final Set<ServiceToken> serviceTokensA = MslTestUtils.getUserBoundServiceTokens(ctx, masterTokenA, userIdTokenA);
final Set<ServiceToken> serviceTokensB = MslTestUtils.getUserBoundServiceTokens(ctx, masterTokenB, userIdTokenB);
store.setCryptoContext(masterTokenA, cryptoContext);
store.setCryptoContext(masterTokenB, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
store.addServiceTokens(masterBoundServiceTokens);
store.addServiceTokens(serviceTokensA);
store.addServiceTokens(serviceTokensB);
// All of master token A's user ID tokens should be deleted.
store.removeCryptoContext(masterTokenA);
assertTrue(store.getServiceTokens(masterTokenA, userIdTokenA).isEmpty());
final Set<ServiceToken> storedServiceTokensB = store.getServiceTokens(masterTokenB, userIdTokenB);
assertEquals(serviceTokensB, storedServiceTokensB);
}
@Test
public void clearCryptoContextsServiceTokens() throws MslEncodingException, MslCryptoException, MslException {
// Master token B has a new serial number, to invalidate the old master
// token and its user ID tokens.
final MasterToken masterTokenA = MslTestUtils.getMasterToken(ctx, 1, 1);
final MasterToken masterTokenB = MslTestUtils.getMasterToken(ctx, 1, 2);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterTokenA, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterTokenB, 2, MockEmailPasswordAuthenticationFactory.USER);
final Set<ServiceToken> unboundServiceTokens = MslTestUtils.getServiceTokens(ctx, null, null);
final Set<ServiceToken> serviceTokensA = MslTestUtils.getUserBoundServiceTokens(ctx, masterTokenA, userIdTokenA);
final Set<ServiceToken> serviceTokensB = MslTestUtils.getUserBoundServiceTokens(ctx, masterTokenB, userIdTokenB);
store.setCryptoContext(masterTokenA, cryptoContext);
store.setCryptoContext(masterTokenB, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
store.addServiceTokens(unboundServiceTokens);
store.addServiceTokens(serviceTokensA);
store.addServiceTokens(serviceTokensB);
// All bound service tokens should be deleted.
store.clearCryptoContexts();
assertEquals(unboundServiceTokens, store.getServiceTokens(masterTokenA, userIdTokenA));
assertEquals(unboundServiceTokens, store.getServiceTokens(masterTokenB, userIdTokenB));
final Set<ServiceToken> storedServiceTokens = store.getServiceTokens(null, null);
assertEquals(unboundServiceTokens, storedServiceTokens);
}
@Test
public void removeUserIdTokenServiceTokens() throws MslEncodingException, MslCryptoException, MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterToken, 2, MockEmailPasswordAuthenticationFactory.USER);
final Set<ServiceToken> masterBoundServiceTokens = MslTestUtils.getMasterBoundServiceTokens(ctx, masterToken);
final Set<ServiceToken> serviceTokensA = MslTestUtils.getUserBoundServiceTokens(ctx, masterToken, userIdTokenA);
final Set<ServiceToken> serviceTokensB = MslTestUtils.getUserBoundServiceTokens(ctx, masterToken, userIdTokenB);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
store.addServiceTokens(masterBoundServiceTokens);
store.addServiceTokens(serviceTokensA);
store.addServiceTokens(serviceTokensB);
// We should still have all the master token bound and user ID token B
// bound service tokens.
store.removeUserIdToken(userIdTokenA);
final Set<ServiceToken> storedServiceTokens = store.getServiceTokens(masterToken, userIdTokenB);
final Set<ServiceToken> expectedServiceTokens = new HashSet<ServiceToken>(masterBoundServiceTokens);
expectedServiceTokens.addAll(serviceTokensB);
assertEquals(expectedServiceTokens, storedServiceTokens);
}
@Test
public void clearUserIdTokensServiceTokens() throws MslEncodingException, MslCryptoException, MslException {
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, 1, 1);
final ICryptoContext cryptoContext = new NullCryptoContext();
final String userIdA = USER_ID + "A";
final String userIdB = USER_ID + "B";
final UserIdToken userIdTokenA = MslTestUtils.getUserIdToken(ctx, masterToken, 1, MockEmailPasswordAuthenticationFactory.USER);
final UserIdToken userIdTokenB = MslTestUtils.getUserIdToken(ctx, masterToken, 2, MockEmailPasswordAuthenticationFactory.USER);
final Set<ServiceToken> masterBoundServiceTokens = MslTestUtils.getMasterBoundServiceTokens(ctx, masterToken);
final Set<ServiceToken> serviceTokensA = MslTestUtils.getUserBoundServiceTokens(ctx, masterToken, userIdTokenA);
final Set<ServiceToken> serviceTokensB = MslTestUtils.getUserBoundServiceTokens(ctx, masterToken, userIdTokenB);
store.setCryptoContext(masterToken, cryptoContext);
store.addUserIdToken(userIdA, userIdTokenA);
store.addUserIdToken(userIdB, userIdTokenB);
store.addServiceTokens(masterBoundServiceTokens);
store.addServiceTokens(serviceTokensA);
store.addServiceTokens(serviceTokensB);
// Only the master token bound service tokens should be left.
store.clearUserIdTokens();
final Set<ServiceToken> storedServiceTokens = store.getServiceTokens(masterToken, userIdTokenB);
assertEquals(masterBoundServiceTokens, storedServiceTokens);
}
/**
* Service token add/remove stress test runner.
*
* Randomly adds or removes service tokens in combinations of unbound,
* master token bound, and user ID token bound Also iterates through the
* service tokens.
*/
private static class ServiceTokenStressor implements Runnable {
/**
* Create a new service token stressor.
*
* @param ctx MSL context.
* @param store MSL store.
* @param count the number of master token and user ID tokens to create
* combinations of.
*/
public ServiceTokenStressor(final MslContext ctx, final MslStore store, final int count) {
this.ctx = ctx;
this.store = store;
this.count = count;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
final Random r = new Random();
try {
for (int i = 0; i < 10 * count; ++i) {
final int tokenIndex = r.nextInt(count);
final MasterToken masterToken = MslTestUtils.getMasterToken(ctx, tokenIndex, 1);
final long userId = r.nextInt(count);
final UserIdToken userIdToken = MslTestUtils.getUserIdToken(ctx, masterToken, userId, MockEmailPasswordAuthenticationFactory.USER);
final int option = r.nextInt(6);
switch (option) {
case 0:
{
final Set<ServiceToken> tokens = MslTestUtils.getServiceTokens(ctx, null, null);
store.addServiceTokens(tokens);
break;
}
case 1:
{
store.setCryptoContext(masterToken, new NullCryptoContext());
final Set<ServiceToken> tokens = MslTestUtils.getServiceTokens(ctx, masterToken, null);
store.addServiceTokens(tokens);
break;
}
case 2:
{
store.setCryptoContext(masterToken, new NullCryptoContext());
store.addUserIdToken(USER_ID + userId, userIdToken);
final Set<ServiceToken> tokens = MslTestUtils.getServiceTokens(ctx, masterToken, userIdToken);
store.addServiceTokens(tokens);
break;
}
case 3:
{
store.getServiceTokens(null, null);
break;
}
case 4:
{
store.getServiceTokens(masterToken, null);
break;
}
case 5:
{
store.getServiceTokens(masterToken, userIdToken);
break;
}
}
}
} catch (final MslMasterTokenException e) {
throw new MslInternalException("Unexpected master token exception.", e);
} catch (final MslEncodingException e) {
throw new MslInternalException("Unexpected master token encoding exception.", e);
} catch (final MslCryptoException e) {
throw new MslInternalException("Unexpected master token creation exception.", e);
} catch (final MslException e) {
throw new MslInternalException("Master token / user ID token service token query mismatch.", e);
}
}
/** MSL context. */
private final MslContext ctx;
/** MSL store. */
private final MslStore store;
/** Number of master token and user ID token identities. */
private final int count;
}
@Test
public void stressServiceTokens() throws InterruptedException {
final ExecutorService service = Executors.newCachedThreadPool();
for (int i = 0; i < 10 * MAX_TOKENS; ++i) {
service.execute(new ServiceTokenStressor(ctx, store, MAX_TOKENS));
}
service.shutdown();
assertTrue(service.awaitTermination(STRESS_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
}
/** MSL context. */
private static MslContext ctx;
/** MSL store. */
private MslStore store;
}
| 1,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.