index
int64 0
0
| repo_id
stringlengths 26
205
| file_path
stringlengths 51
246
| content
stringlengths 8
433k
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 |
Create_ds/msl/examples/proxy/src/main/java/com/netflix/msl
|
Create_ds/msl/examples/proxy/src/main/java/com/netflix/msl/tokens/FailoverTokenFactory.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.tokens;
import javax.crypto.SecretKey;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.ProxyMslError;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.userauth.ProxyMslUser;
import com.netflix.msl.util.MslContext;
/**
* <p>This token factory accepts all tokens and renews tokens by echoing them
* back.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class FailoverTokenFactory 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) throws MslException {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#createMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.entityauth.EntityAuthenticationData, javax.crypto.SecretKey, javax.crypto.SecretKey, com.netflix.msl.io.MslObject)
*/
@Override
public MasterToken createMasterToken(final MslContext ctx, final EntityAuthenticationData entityAuthData, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException, MslException {
// This method should not get called. If it does then throw an
// exception to trigger processing by the proxied MSL service.
throw new MslException(ProxyMslError.MASTERTOKEN_CREATION_REQUIRED);
}
/* (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) throws MslException {
return masterToken;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#isUserIdTokenRevoked(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public MslError isUserIdTokenRevoked(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken) {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#createUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MslUser, com.netflix.msl.tokens.MasterToken)
*/
@Override
public UserIdToken createUserIdToken(final MslContext ctx, final MslUser user, final MasterToken masterToken) throws MslException {
throw new MslException(ProxyMslError.USERIDTOKEN_CREATION_REQUIRED);
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#renewUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.UserIdToken, com.netflix.msl.tokens.MasterToken)
*/
@Override
public UserIdToken renewUserIdToken(final MslContext ctx, final UserIdToken userIdToken, final MasterToken masterToken) throws MslException {
return userIdToken;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#createUser(com.netflix.msl.util.MslContext, java.lang.String)
*/
@Override
public MslUser createUser(final MslContext ctx, final String userdata) {
return new ProxyMslUser(userdata);
}
}
| 1,900 |
0 |
Create_ds/msl/examples/proxy/src/main/java/com/netflix/msl
|
Create_ds/msl/examples/proxy/src/main/java/com/netflix/msl/entityauth/ProxyEntityAuthenticationFactory.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.crypto.ICryptoContext;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.MslContext;
/**
* <p>The proxy entity authentication factory acts as a front for the proxy's
* entity's authentication factory.</p>
*
* <p>Attempting to authenticate a remote entity using this factory will throw
* a {@link MslEntityAuthException} containing the specified MSL error. The
* proxy will be authenticated using the backing factory.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class ProxyEntityAuthenticationFactory extends EntityAuthenticationFactory {
/**
* <p>Create a new proxy entity authentication factory that will use the
* provided backing factory to authenticate the specified entity identity,
* and will throw exceptions using the specified MSL error.</p>
*
* @param proxyIdentity the proxy entity identity.
* @param proxyFactory the proxy entity authentication factory.
* @param error the error to throw.
*/
public ProxyEntityAuthenticationFactory(final String proxyIdentity, final EntityAuthenticationFactory proxyFactory, final MslError error) {
super(proxyFactory.getScheme());
this.proxyIdentity = proxyIdentity;
this.proxyFactory = proxyFactory;
this.error = error;
}
/* (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 proxyFactory.createData(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 {
// Authenticate the local entity.
final String identity = authdata.getIdentity();
if (proxyIdentity.equals(identity))
return proxyFactory.getCryptoContext(ctx, authdata);
// Otherwise throw an exception indicating the message requires
// external processing.
throw new MslEntityAuthException(error);
}
/** Proxy entity identity. */
private final String proxyIdentity;
/** Proxy entity authentication factory. */
private final EntityAuthenticationFactory proxyFactory;
/** MSL error. */
private final MslError error;
}
| 1,901 |
0 |
Create_ds/msl/examples/proxy/src/main/java/com/netflix/msl
|
Create_ds/msl/examples/proxy/src/main/java/com/netflix/msl/entityauth/ProxyEntityAuthenticationScheme.java
|
/**
* Copyright (c) 2015 Netflix, Inc. All rights reserved.
*/
package com.netflix.msl.entityauth;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
/**
* <p>Proxy entity authentication schemes.</p>
*
* <p>All entity authentication schemes are automatically re-mapped onto the
* proxy entity authentication scheme.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class ProxyEntityAuthenticationScheme extends EntityAuthenticationScheme {
/** Proxy entity authentication scheme. */
public static final EntityAuthenticationScheme PROXY = new ProxyEntityAuthenticationScheme("PROXY", 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 ProxyEntityAuthenticationScheme(String name, boolean encrypts, boolean protects) {
super(name, encrypts, protects);
}
}
| 1,902 |
0 |
Create_ds/msl/examples/proxy/src/main/java/com/netflix/msl
|
Create_ds/msl/examples/proxy/src/main/java/com/netflix/msl/entityauth/FailingEntityAuthenticationFactory.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.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.MslContext;
/**
* <p>Failing entity authentication factory.</p>
*
* <p>When used, this factory throws an {@link MslEntityAuthException}
* containing the MSL error specified when constructed.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class FailingEntityAuthenticationFactory extends EntityAuthenticationFactory {
/**
* Create a new failing entity authentication factory for the specified
* scheme.
*
* @param scheme the entity authentication scheme.
* @param error the error to throw.
*/
public FailingEntityAuthenticationFactory(final EntityAuthenticationScheme scheme, final MslError error) {
super(scheme);
this.error = error;
}
/* (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 MslEntityAuthException {
throw new MslEntityAuthException(error);
}
/* (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 {
throw new MslEntityAuthException(error);
}
/** MSL error. */
private final MslError error;
}
| 1,903 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IMessageEditorTabFactory.java
|
package burp;
/*
* @(#)IMessageEditorTabFactory.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerMessageEditorTabFactory()</code> to
* register a factory for custom message editor tabs. This allows extensions to
* provide custom rendering or editing of HTTP messages, within Burp's own HTTP
* editor.
*/
public interface IMessageEditorTabFactory
{
/**
* Burp will call this method once for each HTTP message editor, and the
* factory should provide a new instance of an
* <code>IMessageEditorTab</code> object.
*
* @param controller An
* <code>IMessageEditorController</code> object, which the new tab can query
* to retrieve details about the currently displayed message. This may be
* <code>null</code> for extension-invoked message editors where the
* extension has not provided an editor controller.
* @param editable Indicates whether the hosting editor is editable or
* read-only.
* @return A new
* <code>IMessageEditorTab</code> object for use within the message editor.
*/
IMessageEditorTab createNewInstance(IMessageEditorController controller,
boolean editable);
}
| 1,904 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IResponseInfo.java
|
package burp;
/*
* @(#)IResponseInfo.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.util.List;
/**
* This interface is used to retrieve key details about an HTTP response.
* Extensions can obtain an
* <code>IResponseInfo</code> object for a given response by calling
* <code>IExtensionHelpers.analyzeResponse()</code>.
*/
public interface IResponseInfo
{
/**
* This method is used to obtain the HTTP headers contained in the response.
*
* @return The HTTP headers contained in the response.
*/
List<String> getHeaders();
/**
* This method is used to obtain the offset within the response where the
* message body begins.
*
* @return The offset within the response where the message body begins.
*/
int getBodyOffset();
/**
* This method is used to obtain the HTTP status code contained in the
* response.
*
* @return The HTTP status code contained in the response.
*/
short getStatusCode();
/**
* This method is used to obtain details of the HTTP cookies set in the
* response.
*
* @return A list of <code>ICookie</code> objects representing the cookies
* set in the response, if any.
*/
List<ICookie> getCookies();
/**
* This method is used to obtain the MIME type of the response, as stated in
* the HTTP headers.
*
* @return A textual label for the stated MIME type, or an empty String if
* this is not known or recognized. The possible labels are the same as
* those used in the main Burp UI.
*/
String getStatedMimeType();
/**
* This method is used to obtain the MIME type of the response, as inferred
* from the contents of the HTTP message body.
*
* @return A textual label for the inferred MIME type, or an empty String if
* this is not known or recognized. The possible labels are the same as
* those used in the main Burp UI.
*/
String getInferredMimeType();
}
| 1,905 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IScannerCheck.java
|
package burp;
/*
* @(#)IScannerCheck.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.util.List;
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerScannerCheck()</code> to register a
* custom Scanner check. When performing scanning, Burp will ask the check to
* perform active or passive scanning on the base request, and report any
* Scanner issues that are identified.
*/
public interface IScannerCheck
{
/**
* The Scanner invokes this method for each base request / response that is
* passively scanned. <b>Note:</b> Extensions should not only analyze the
* HTTP messages provided during passive scanning, and should not make any
* new HTTP requests of their own.
*
* @param baseRequestResponse The base HTTP request / response that should
* be passively scanned.
* @return A list of
* <code>IScanIssue</code> objects, or
* <code>null</code> if no issues are identified.
*/
List<IScanIssue> doPassiveScan(IHttpRequestResponse baseRequestResponse);
/**
* The Scanner invokes this method for each insertion point that is actively
* scanned. Extensions may issue HTTP requests as required to carry out
* active scanning, and should use the
* <code>IScannerInsertionPoint</code> object provided to build scan
* requests for particular payloads. <b>Note:</b> Extensions are responsible
* for ensuring that attack payloads are suitably encoded within requests
* (for example, by URL-encoding relevant metacharacters in the URL query
* string). Encoding is not automatically carried out by the
* <code>IScannerInsertionPoint</code>, because this would prevent Scanner
* checks from testing for certain input filter bypasses. Extensions should
* query the
* <code>IScannerInsertionPoint</code> to determine its type, and apply any
* encoding that may be appropriate.
*
* @param baseRequestResponse The base HTTP request / response that should
* be actively scanned.
* @param insertionPoint An
* <code>IScannerInsertionPoint</code> object that can be queried to obtain
* details of the insertion point being tested, and can be used to build
* scan requests for particular payloads.
* @return A list of
* <code>IScanIssue</code> objects, or
* <code>null</code> if no issues are identified.
*/
List<IScanIssue> doActiveScan(
IHttpRequestResponse baseRequestResponse,
IScannerInsertionPoint insertionPoint);
/**
* The Scanner invokes this method when the custom Scanner check has
* reported multiple issues for the same URL path. This can arise either
* because there are multiple distinct vulnerabilities, or because the same
* (or a similar) request has been scanned more than once. The custom check
* should determine whether the issues are duplicates. In most cases, where
* a check uses distinct issue names or descriptions for distinct issues,
* the consolidation process will simply be a matter of comparing these
* features for the two issues.
*
* @param existingIssue An issue that was previously reported by this
* Scanner check.
* @param newIssue An issue at the same URL path that has been newly
* reported by this Scanner check.
* @return An indication of which issue(s) should be reported in the main
* Scanner results. The method should return
* <code>-1</code> to report the existing issue only,
* <code>0</code> to report both issues, and
* <code>1</code> to report the new issue only.
*/
int consolidateDuplicateIssues(
IScanIssue existingIssue,
IScanIssue newIssue);
}
| 1,906 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IProxyListener.java
|
package burp;
/*
* @(#)IProxyListener.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerProxyListener()</code> to register a
* Proxy listener. The listener will be notified of requests and responses being
* processed by the Proxy tool. Extensions can perform custom analysis or
* modification of these messages, and control in-UI message interception, by
* registering a proxy listener.
*/
public interface IProxyListener
{
/**
* This method is invoked when an HTTP message is being processed by the
* Proxy.
*
* @param messageIsRequest Indicates whether the HTTP message is a request
* or a response.
* @param message An
* <code>IInterceptedProxyMessage</code> object that extensions can use to
* query and update details of the message, and control whether the message
* should be intercepted and displayed to the user for manual review or
* modification.
*/
void processProxyMessage(
boolean messageIsRequest,
IInterceptedProxyMessage message);
}
| 1,907 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IContextMenuFactory.java
|
package burp;
/*
* @(#)IContextMenuFactory.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import javax.swing.*;
import java.util.List;
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerContextMenuFactory()</code> to register
* a factory for custom context menu items.
*/
public interface IContextMenuFactory
{
/**
* This method will be called by Burp when the user invokes a context menu
* anywhere within Burp. The factory can then provide any custom context
* menu items that should be displayed in the context menu, based on the
* details of the menu invocation.
*
* @param invocation An object that implements the
* <code>IMessageEditorTabFactory</code> interface, which the extension can
* query to obtain details of the context menu invocation.
* @return A list of custom menu items (which may include sub-menus,
* checkbox menu items, etc.) that should be displayed. Extensions may
* return
* <code>null</code> from this method, to indicate that no menu items are
* required.
*/
List<JMenuItem> createMenuItems(IContextMenuInvocation invocation);
}
| 1,908 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IScopeChangeListener.java
|
package burp;
/*
* @(#)IScopeChangeListener.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerScopeChangeListener()</code> to register
* a scope change listener. The listener will be notified whenever a change
* occurs to Burp's suite-wide target scope.
*/
public interface IScopeChangeListener
{
/**
* This method is invoked whenever a change occurs to Burp's suite-wide
* target scope.
*/
void scopeChanged();
}
| 1,909 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IInterceptedProxyMessage.java
|
package burp;
/*
* @(#)IInterceptedProxyMessage.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.net.InetAddress;
/**
* This interface is used to represent an HTTP message that has been intercepted
* by Burp Proxy. Extensions can register an
* <code>IProxyListener</code> to receive details of proxy messages using this
* interface. *
*/
public interface IInterceptedProxyMessage
{
/**
* This action causes Burp Proxy to follow the current interception rules to
* determine the appropriate action to take for the message.
*/
static final int ACTION_FOLLOW_RULES = 0;
/**
* This action causes Burp Proxy to present the message to the user for
* manual review or modification.
*/
static final int ACTION_DO_INTERCEPT = 1;
/**
* This action causes Burp Proxy to forward the message to the remote server
* or client, without presenting it to the user.
*/
static final int ACTION_DONT_INTERCEPT = 2;
/**
* This action causes Burp Proxy to drop the message.
*/
static final int ACTION_DROP = 3;
/**
* This action causes Burp Proxy to follow the current interception rules to
* determine the appropriate action to take for the message, and then make a
* second call to processProxyMessage.
*/
static final int ACTION_FOLLOW_RULES_AND_REHOOK = 0x10;
/**
* This action causes Burp Proxy to present the message to the user for
* manual review or modification, and then make a second call to
* processProxyMessage.
*/
static final int ACTION_DO_INTERCEPT_AND_REHOOK = 0x11;
/**
* This action causes Burp Proxy to skip user interception, and then make a
* second call to processProxyMessage.
*/
static final int ACTION_DONT_INTERCEPT_AND_REHOOK = 0x12;
/**
* This method retrieves a unique reference number for this
* request/response.
*
* @return An identifier that is unique to a single request/response pair.
* Extensions can use this to correlate details of requests and responses
* and perform processing on the response message accordingly.
*/
int getMessageReference();
/**
* This method retrieves details of the intercepted message.
*
* @return An <code>IHttpRequestResponse</code> object containing details of
* the intercepted message.
*/
IHttpRequestResponse getMessageInfo();
/**
* This method retrieves the currently defined interception action. The
* default action is
* <code>ACTION_FOLLOW_RULES</code>. If multiple proxy listeners are
* registered, then other listeners may already have modified the
* interception action before it reaches the current listener. This method
* can be used to determine whether this has occurred.
*
* @return The currently defined interception action. Possible values are
* defined within this interface.
*/
int getInterceptAction();
/**
* This method is used to update the interception action.
*
* @param interceptAction The new interception action. Possible values are
* defined within this interface.
*/
void setInterceptAction(int interceptAction);
/**
* This method retrieves the name of the Burp Proxy listener that is
* processing the intercepted message.
*
* @return The name of the Burp Proxy listener that is processing the
* intercepted message. The format is the same as that shown in the Proxy
* Listeners UI - for example, "127.0.0.1:8080".
*/
String getListenerInterface();
/**
* This method retrieves the client IP address from which the request for
* the intercepted message was received.
*
* @return The client IP address from which the request for the intercepted
* message was received.
*/
InetAddress getClientIpAddress();
}
| 1,910 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IBurpExtenderCallbacks.java
|
package burp;
/*
* @(#)IBurpExtenderCallbacks.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.awt.*;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
/**
* This interface is used by Burp Suite to pass to extensions a set of callback
* methods that can be used by extensions to perform various actions within
* Burp.
*
* When an extension is loaded, Burp invokes its
* <code>registerExtenderCallbacks()</code> method and passes an instance of the
* <code>IBurpExtenderCallbacks</code> interface. The extension may then invoke
* the methods of this interface as required in order to extend Burp's
* functionality.
*/
public interface IBurpExtenderCallbacks
{
/**
* Flag used to identify Burp Suite as a whole.
*/
static final int TOOL_SUITE = 0x00000001;
/**
* Flag used to identify the Burp Target tool.
*/
static final int TOOL_TARGET = 0x00000002;
/**
* Flag used to identify the Burp Proxy tool.
*/
static final int TOOL_PROXY = 0x00000004;
/**
* Flag used to identify the Burp Spider tool.
*/
static final int TOOL_SPIDER = 0x00000008;
/**
* Flag used to identify the Burp Scanner tool.
*/
static final int TOOL_SCANNER = 0x00000010;
/**
* Flag used to identify the Burp Intruder tool.
*/
static final int TOOL_INTRUDER = 0x00000020;
/**
* Flag used to identify the Burp Repeater tool.
*/
static final int TOOL_REPEATER = 0x00000040;
/**
* Flag used to identify the Burp Sequencer tool.
*/
static final int TOOL_SEQUENCER = 0x00000080;
/**
* Flag used to identify the Burp Decoder tool.
*/
static final int TOOL_DECODER = 0x00000100;
/**
* Flag used to identify the Burp Comparer tool.
*/
static final int TOOL_COMPARER = 0x00000200;
/**
* Flag used to identify the Burp Extender tool.
*/
static final int TOOL_EXTENDER = 0x00000400;
/**
* This method is used to set the display name for the current extension,
* which will be displayed within the user interface for the Extender tool.
*
* @param name The extension name.
*/
void setExtensionName(String name);
/**
* This method is used to obtain an
* <code>IExtensionHelpers</code> object, which can be used by the extension
* to perform numerous useful tasks.
*
* @return An object containing numerous helper methods, for tasks such as
* building and analyzing HTTP requests.
*/
IExtensionHelpers getHelpers();
/**
* This method is used to obtain the current extension's standard output
* stream. Extensions should write all output to this stream, allowing the
* Burp user to configure how that output is handled from within the UI.
*
* @return The extension's standard output stream.
*/
OutputStream getStdout();
/**
* This method is used to obtain the current extension's standard error
* stream. Extensions should write all error messages to this stream,
* allowing the Burp user to configure how that output is handled from
* within the UI.
*
* @return The extension's standard error stream.
*/
OutputStream getStderr();
/**
* This method is used to register a listener which will be notified of
* changes to the extension's state. <b>Note:</b> Any extensions that start
* background threads or open system resources (such as files or database
* connections) should register a listener and terminate threads / close
* resources when the extension is unloaded.
*
* @param listener An object created by the extension that implements the
* <code>IExtensionStateListener</code> interface.
*/
void registerExtensionStateListener(IExtensionStateListener listener);
/**
* This method is used to register a listener which will be notified of
* requests and responses made by any Burp tool. Extensions can perform
* custom analysis or modification of these messages by registering an HTTP
* listener.
*
* @param listener An object created by the extension that implements the
* <code>IHttpListener</code> interface.
*/
void registerHttpListener(IHttpListener listener);
/**
* This method is used to register a listener which will be notified of
* requests and responses being processed by the Proxy tool. Extensions can
* perform custom analysis or modification of these messages, and control
* in-UI message interception, by registering a proxy listener.
*
* @param listener An object created by the extension that implements the
* <code>IProxyListener</code> interface.
*/
void registerProxyListener(IProxyListener listener);
/**
* This method is used to register a listener which will be notified of new
* issues that are reported by the Scanner tool. Extensions can perform
* custom analysis or logging of Scanner issues by registering a Scanner
* listener.
*
* @param listener An object created by the extension that implements the
* <code>IScannerListener</code> interface.
*/
void registerScannerListener(IScannerListener listener);
/**
* This method is used to register a listener which will be notified of
* changes to Burp's suite-wide target scope.
*
* @param listener An object created by the extension that implements the
* <code>IScopeChangeListener</code> interface.
*/
void registerScopeChangeListener(IScopeChangeListener listener);
/**
* This method is used to register a factory for custom context menu items.
* When the user invokes a context menu anywhere within Burp, the factory
* will be passed details of the invocation event, and asked to provide any
* custom context menu items that should be shown.
*
* @param factory An object created by the extension that implements the
* <code>IContextMenuFactory</code> interface.
*/
void registerContextMenuFactory(IContextMenuFactory factory);
/**
* This method is used to register a factory for custom message editor tabs.
* For each message editor that already exists, or is subsequently created,
* within Burp, the factory will be asked to provide a new instance of an
* <code>IMessageEditorTab</code> object, which can provide custom rendering
* or editing of HTTP messages.
*
* @param factory An object created by the extension that implements the
* <code>IMessageEditorTabFactory</code> interface.
*/
void registerMessageEditorTabFactory(IMessageEditorTabFactory factory);
/**
* This method is used to register a provider of Scanner insertion points.
* For each base request that is actively scanned, Burp will ask the
* provider to provide any custom scanner insertion points that are
* appropriate for the request.
*
* @param provider An object created by the extension that implements the
* <code>IScannerInsertionPointProvider</code> interface.
*/
void registerScannerInsertionPointProvider(
IScannerInsertionPointProvider provider);
/**
* This method is used to register a custom Scanner check. When performing
* scanning, Burp will ask the check to perform active or passive scanning
* on the base request, and report any Scanner issues that are identified.
*
* @param check An object created by the extension that implements the
* <code>IScannerCheck</code> interface.
*/
void registerScannerCheck(IScannerCheck check);
/**
* This method is used to register a factory for Intruder payloads. Each
* registered factory will be available within the Intruder UI for the user
* to select as the payload source for an attack. When this is selected, the
* factory will be asked to provide a new instance of an
* <code>IIntruderPayloadGenerator</code> object, which will be used to
* generate payloads for the attack.
*
* @param factory An object created by the extension that implements the
* <code>IIntruderPayloadGeneratorFactory</code> interface.
*/
void registerIntruderPayloadGeneratorFactory(
IIntruderPayloadGeneratorFactory factory);
/**
* This method is used to register a custom Intruder payload processor. Each
* registered processor will be available within the Intruder UI for the
* user to select as the action for a payload processing rule.
*
* @param processor An object created by the extension that implements the
* <code>IIntruderPayloadProcessor</code> interface.
*/
void registerIntruderPayloadProcessor(IIntruderPayloadProcessor processor);
/**
* This method is used to register a custom session handling action. Each
* registered action will be available within the session handling rule UI
* for the user to select as a rule action. Users can choose to invoke an
* action directly in its own right, or following execution of a macro.
*
* @param action An object created by the extension that implements the
* <code>ISessionHandlingAction</code> interface.
*/
void registerSessionHandlingAction(ISessionHandlingAction action);
/**
* This method is used to unload the extension from Burp Suite.
*/
void unloadExtension();
/**
* This method is used to add a custom tab to the main Burp Suite window.
*
* @param tab An object created by the extension that implements the
* <code>ITab</code> interface.
*/
void addSuiteTab(ITab tab);
/**
* This method is used to remove a previously-added tab from the main Burp
* Suite window.
*
* @param tab An object created by the extension that implements the
* <code>ITab</code> interface.
*/
void removeSuiteTab(ITab tab);
/**
* This method is used to customize UI components in line with Burp's UI
* style, including font size, colors, table line spacing, etc.
*
* @param component The UI component to be customized.
*/
void customizeUiComponent(Component component);
/**
* This method is used to create a new instance of Burp's HTTP message
* editor, for the extension to use in its own UI.
*
* @param controller An object created by the extension that implements the
* <code>IMessageEditorController</code> interface. This parameter is
* optional and may be <code>null</code>. If it is provided, then the
* message editor will query the controller when required to obtain details
* about the currently displayed message, including the
* <code>IHttpService</code> for the message, and the associated request or
* response message. If a controller is not provided, then the message
* editor will not support context menu actions, such as sending requests to
* other Burp tools.
* @param editable Indicates whether the editor created should be editable,
* or used only for message viewing.
* @return An object that implements the <code>IMessageEditor</code>
* interface, and which the extension can use in its own UI.
*/
IMessageEditor createMessageEditor(IMessageEditorController controller,
boolean editable);
/**
* This method returns the command line arguments that were passed to Burp
* on startup.
*
* @return The command line arguments that were passed to Burp on startup.
*/
String[] getCommandLineArguments();
/**
* This method is used to save configuration settings for the extension in a
* persistent way that survives reloads of the extension and of Burp Suite.
* Saved settings can be retrieved using the method
* <code>loadExtensionSetting()</code>.
*
* @param name The name of the setting.
* @param value The value of the setting. If this value is <code>null</code>
* then any existing setting with the specified name will be removed.
*/
void saveExtensionSetting(String name, String value);
/**
* This method is used to load configuration settings for the extension that
* were saved using the method
* <code>saveExtensionSetting()</code>.
*
* @param name The name of the setting.
* @return The value of the setting, or <code>null</code> if no value is
* set.
*/
String loadExtensionSetting(String name);
/**
* This method is used to create a new instance of Burp's plain text editor,
* for the extension to use in its own UI.
*
* @return An object that implements the <code>ITextEditor</code> interface,
* and which the extension can use in its own UI.
*/
ITextEditor createTextEditor();
/**
* This method can be used to send an HTTP request to the Burp Repeater
* tool. The request will be displayed in the user interface, but will not
* be issued until the user initiates this action.
*
* @param host The hostname of the remote HTTP server.
* @param port The port of the remote HTTP server.
* @param useHttps Flags whether the protocol is HTTPS or HTTP.
* @param request The full HTTP request.
* @param tabCaption An optional caption which will appear on the Repeater
* tab containing the request. If this value is <code>null</code> then a
* default tab index will be displayed.
*/
void sendToRepeater(
String host,
int port,
boolean useHttps,
byte[] request,
String tabCaption);
/**
* This method can be used to send an HTTP request to the Burp Intruder
* tool. The request will be displayed in the user interface, and markers
* for attack payloads will be placed into default locations within the
* request.
*
* @param host The hostname of the remote HTTP server.
* @param port The port of the remote HTTP server.
* @param useHttps Flags whether the protocol is HTTPS or HTTP.
* @param request The full HTTP request.
*/
void sendToIntruder(
String host,
int port,
boolean useHttps,
byte[] request);
/**
* This method can be used to send an HTTP request to the Burp Intruder
* tool. The request will be displayed in the user interface, and markers
* for attack payloads will be placed into the specified locations within
* the request.
*
* @param host The hostname of the remote HTTP server.
* @param port The port of the remote HTTP server.
* @param useHttps Flags whether the protocol is HTTPS or HTTP.
* @param request The full HTTP request.
* @param payloadPositionOffsets A list of index pairs representing the
* payload positions to be used. Each item in the list must be an int[2]
* array containing the start and end offsets for the payload position.
*/
void sendToIntruder(
String host,
int port,
boolean useHttps,
byte[] request,
List<int[]> payloadPositionOffsets);
/**
* This method can be used to send a seed URL to the Burp Spider tool. If
* the URL is not within the current Spider scope, the user will be asked if
* they wish to add the URL to the scope. If the Spider is not currently
* running, it will be started. The seed URL will be requested, and the
* Spider will process the application's response in the normal way.
*
* @param url The new seed URL to begin spidering from.
*/
void sendToSpider(
java.net.URL url);
/**
* This method can be used to send an HTTP request to the Burp Scanner tool
* to perform an active vulnerability scan. If the request is not within the
* current active scanning scope, the user will be asked if they wish to
* proceed with the scan.
*
* @param host The hostname of the remote HTTP server.
* @param port The port of the remote HTTP server.
* @param useHttps Flags whether the protocol is HTTPS or HTTP.
* @param request The full HTTP request.
* @return The resulting scan queue item.
*/
IScanQueueItem doActiveScan(
String host,
int port,
boolean useHttps,
byte[] request);
/**
* This method can be used to send an HTTP request to the Burp Scanner tool
* to perform an active vulnerability scan, based on a custom list of
* insertion points that are to be scanned. If the request is not within the
* current active scanning scope, the user will be asked if they wish to
* proceed with the scan.
*
* @param host The hostname of the remote HTTP server.
* @param port The port of the remote HTTP server.
* @param useHttps Flags whether the protocol is HTTPS or HTTP.
* @param request The full HTTP request.
* @param insertionPointOffsets A list of index pairs representing the
* positions of the insertion points that should be scanned. Each item in
* the list must be an int[2] array containing the start and end offsets for
* the insertion point.
* @return The resulting scan queue item.
*/
IScanQueueItem doActiveScan(
String host,
int port,
boolean useHttps,
byte[] request,
List<int[]> insertionPointOffsets);
/**
* This method can be used to send an HTTP request to the Burp Scanner tool
* to perform a passive vulnerability scan.
*
* @param host The hostname of the remote HTTP server.
* @param port The port of the remote HTTP server.
* @param useHttps Flags whether the protocol is HTTPS or HTTP.
* @param request The full HTTP request.
* @param response The full HTTP response.
*/
void doPassiveScan(
String host,
int port,
boolean useHttps,
byte[] request,
byte[] response);
/**
* This method can be used to issue HTTP requests and retrieve their
* responses.
*
* @param httpService The HTTP service to which the request should be sent.
* @param request The full HTTP request.
* @return An object that implements the <code>IHttpRequestResponse</code>
* interface, and which the extension can query to obtain the details of the
* response.
*/
IHttpRequestResponse makeHttpRequest(IHttpService httpService,
byte[] request);
/**
* This method can be used to issue HTTP requests and retrieve their
* responses.
*
* @param host The hostname of the remote HTTP server.
* @param port The port of the remote HTTP server.
* @param useHttps Flags whether the protocol is HTTPS or HTTP.
* @param request The full HTTP request.
* @return The full response retrieved from the remote server.
*/
byte[] makeHttpRequest(
String host,
int port,
boolean useHttps,
byte[] request);
/**
* This method can be used to query whether a specified URL is within the
* current Suite-wide scope.
*
* @param url The URL to query.
* @return Returns <code>true</code> if the URL is within the current
* Suite-wide scope.
*/
boolean isInScope(java.net.URL url);
/**
* This method can be used to include the specified URL in the Suite-wide
* scope.
*
* @param url The URL to include in the Suite-wide scope.
*/
void includeInScope(java.net.URL url);
/**
* This method can be used to exclude the specified URL from the Suite-wide
* scope.
*
* @param url The URL to exclude from the Suite-wide scope.
*/
void excludeFromScope(java.net.URL url);
/**
* This method can be used to display a specified message in the Burp Suite
* alerts tab.
*
* @param message The alert message to display.
*/
void issueAlert(String message);
/**
* This method returns details of all items in the Proxy history.
*
* @return The contents of the Proxy history.
*/
IHttpRequestResponse[] getProxyHistory();
/**
* This method returns details of items in the site map.
*
* @param urlPrefix This parameter can be used to specify a URL prefix, in
* order to extract a specific subset of the site map. The method performs a
* simple case-sensitive text match, returning all site map items whose URL
* begins with the specified prefix. If this parameter is null, the entire
* site map is returned.
*
* @return Details of items in the site map.
*/
IHttpRequestResponse[] getSiteMap(String urlPrefix);
/**
* This method returns all of the current scan issues for URLs matching the
* specified literal prefix.
*
* @param urlPrefix This parameter can be used to specify a URL prefix, in
* order to extract a specific subset of scan issues. The method performs a
* simple case-sensitive text match, returning all scan issues whose URL
* begins with the specified prefix. If this parameter is null, all issues
* are returned.
* @return Details of the scan issues.
*/
IScanIssue[] getScanIssues(String urlPrefix);
/**
* This method is used to generate a report for the specified Scanner
* issues. The report format can be specified. For all other reporting
* options, the default settings that appear in the reporting UI wizard are
* used.
*
* @param format The format to be used in the report. Accepted values are
* HTML and XML.
* @param issues The Scanner issues to be reported.
* @param file The file to which the report will be saved.
*/
void generateScanReport(String format, IScanIssue[] issues, java.io.File file);
/**
* This method is used to retrieve the contents of Burp's session handling
* cookie jar. Extensions that provide an
* <code>ISessionHandlingAction</code> can query and update the cookie jar
* in order to handle unusual session handling mechanisms.
*
* @return A list of <code>ICookie</code> objects representing the contents
* of Burp's session handling cookie jar.
*/
List<ICookie> getCookieJarContents();
/**
* This method is used to update the contents of Burp's session handling
* cookie jar. Extensions that provide an
* <code>ISessionHandlingAction</code> can query and update the cookie jar
* in order to handle unusual session handling mechanisms.
*
* @param cookie An <code>ICookie</code> object containing details of the
* cookie to be updated. If the cookie jar already contains a cookie that
* matches the specified domain and name, then that cookie will be updated
* with the new value and expiration, unless the new value is
* <code>null</code>, in which case the cookie will be removed. If the
* cookie jar does not already contain a cookie that matches the specified
* domain and name, then the cookie will be added.
*/
void updateCookieJar(ICookie cookie);
/**
* This method can be used to add an item to Burp's site map with the
* specified request/response details. This will overwrite the details of
* any existing matching item in the site map.
*
* @param item Details of the item to be added to the site map
*/
void addToSiteMap(IHttpRequestResponse item);
/**
* This method can be used to restore Burp's state from a specified saved
* state file. This method blocks until the restore operation is completed,
* and must not be called from the event dispatch thread.
*
* @param file The file containing Burp's saved state.
*/
void restoreState(java.io.File file);
/**
* This method can be used to save Burp's state to a specified file. This
* method blocks until the save operation is completed, and must not be
* called from the event dispatch thread.
*
* @param file The file to save Burp's state in.
*/
void saveState(java.io.File file);
/**
* This method causes Burp to save all of its current configuration as a Map
* of name/value Strings.
*
* @return A Map of name/value Strings reflecting Burp's current
* configuration.
*/
Map<String, String> saveConfig();
/**
* This method causes Burp to load a new configuration from the Map of
* name/value Strings provided. Any settings not specified in the Map will
* be restored to their default values. To selectively update only some
* settings and leave the rest unchanged, you should first call
* <code>saveConfig()</code> to obtain Burp's current configuration, modify
* the relevant items in the Map, and then call
* <code>loadConfig()</code> with the same Map.
*
* @param config A map of name/value Strings to use as Burp's new
* configuration.
*/
void loadConfig(Map<String, String> config);
/**
* This method sets the master interception mode for Burp Proxy.
*
* @param enabled Indicates whether interception of Proxy messages should be
* enabled.
*/
void setProxyInterceptionEnabled(boolean enabled);
/**
* This method retrieves information about the version of Burp in which the
* extension is running. It can be used by extensions to dynamically adjust
* their behavior depending on the functionality and APIs supported by the
* current version.
*
* @return An array of Strings comprised of: the product name (e.g. Burp
* Suite Professional), the major version (e.g. 1.5), the minor version
* (e.g. 03)
*/
String[] getBurpVersion();
/**
* This method can be used to shut down Burp programmatically, with an
* optional prompt to the user. If the method returns, the user canceled the
* shutdown prompt.
*
* @param promptUser Indicates whether to prompt the user to confirm the
* shutdown.
*/
void exitSuite(boolean promptUser);
/**
* This method is used to create a temporary file on disk containing the
* provided data. Extensions can use temporary files for long-term storage
* of runtime data, avoiding the need to retain that data in memory.
*
* @param buffer The data to be saved to a temporary file.
* @return An object that implements the <code>ITempFile</code> interface.
*/
ITempFile saveToTempFile(byte[] buffer);
/**
* This method is used to save the request and response of an
* <code>IHttpRequestResponse</code> object to temporary files, so that they
* are no longer held in memory. Extensions can used this method to convert
* <code>IHttpRequestResponse</code> objects into a form suitable for
* long-term storage.
*
* @param httpRequestResponse The <code>IHttpRequestResponse</code> object
* whose request and response messages are to be saved to temporary files.
* @return An object that implements the
* <code>IHttpRequestResponsePersisted</code> interface.
*/
IHttpRequestResponsePersisted saveBuffersToTempFiles(
IHttpRequestResponse httpRequestResponse);
/**
* This method is used to apply markers to an HTTP request or response, at
* offsets into the message that are relevant for some particular purpose.
* Markers are used in various situations, such as specifying Intruder
* payload positions, Scanner insertion points, and highlights in Scanner
* issues.
*
* @param httpRequestResponse The <code>IHttpRequestResponse</code> object
* to which the markers should be applied.
* @param requestMarkers A list of index pairs representing the offsets of
* markers to be applied to the request message. Each item in the list must
* be an int[2] array containing the start and end offsets for the marker.
* The markers in the list should be in sequence and not overlapping. This
* parameter is optional and may be <code>null</code> if no request markers
* are required.
* @param responseMarkers A list of index pairs representing the offsets of
* markers to be applied to the response message. Each item in the list must
* be an int[2] array containing the start and end offsets for the marker.
* The markers in the list should be in sequence and not overlapping. This
* parameter is optional and may be <code>null</code> if no response markers
* are required.
* @return An object that implements the
* <code>IHttpRequestResponseWithMarkers</code> interface.
*/
IHttpRequestResponseWithMarkers applyMarkers(
IHttpRequestResponse httpRequestResponse,
List<int[]> requestMarkers,
List<int[]> responseMarkers);
/**
* This method is used to obtain the descriptive name for the Burp tool
* identified by the tool flag provided.
*
* @param toolFlag A flag identifying a Burp tool ( <code>TOOL_PROXY</code>,
* <code>TOOL_SCANNER</code>, etc.). Tool flags are defined within this
* interface.
* @return The descriptive name for the specified tool.
*/
String getToolName(int toolFlag);
/**
* This method is used to register a new Scanner issue. <b>Note:</b>
* Wherever possible, extensions should implement custom Scanner checks
* using
* <code>IScannerCheck</code> and report issues via those checks, so as to
* integrate with Burp's user-driven workflow, and ensure proper
* consolidation of duplicate reported issues. This method is only designed
* for tasks outside of the normal testing workflow, such as importing
* results from other scanning tools.
*
* @param issue An object created by the extension that implements the
* <code>IScanIssue</code> interface.
*/
void addScanIssue(IScanIssue issue);
/**
* This method parses the specified request and returns details of each
* request parameter.
*
* @param request The request to be parsed.
* @return An array of: <code>String[] { name, value, type }</code>
* containing details of the parameters contained within the request.
* @deprecated Use <code>IExtensionHelpers.analyzeRequest()</code> instead.
*/
@Deprecated
String[][] getParameters(byte[] request);
/**
* This method parses the specified request and returns details of each HTTP
* header.
*
* @param message The request to be parsed.
* @return An array of HTTP headers.
* @deprecated Use <code>IExtensionHelpers.analyzeRequest()</code> or
* <code>IExtensionHelpers.analyzeResponse()</code> instead.
*/
@Deprecated
String[] getHeaders(byte[] message);
/**
* This method can be used to register a new menu item which will appear on
* the various context menus that are used throughout Burp Suite to handle
* user-driven actions.
*
* @param menuItemCaption The caption to be displayed on the menu item.
* @param menuItemHandler The handler to be invoked when the user clicks on
* the menu item.
* @deprecated Use <code>registerContextMenuFactory()</code> instead.
*/
@Deprecated
void registerMenuItem(
String menuItemCaption,
IMenuItemHandler menuItemHandler);
}
| 1,911 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/ITab.java
|
package burp;
/*
* @(#)ITab.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.awt.*;
/**
* This interface is used to provide Burp with details of a custom tab that will
* be added to Burp's UI, using a method such as
* <code>IBurpExtenderCallbacks.addSuiteTab()</code>.
*/
public interface ITab
{
/**
* Burp uses this method to obtain the caption that should appear on the
* custom tab when it is displayed.
*
* @return The caption that should appear on the custom tab when it is
* displayed.
*/
String getTabCaption();
/**
* Burp uses this method to obtain the component that should be used as the
* contents of the custom tab when it is displayed.
*
* @return The component that should be used as the contents of the custom
* tab when it is displayed.
*/
Component getUiComponent();
}
| 1,912 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IHttpRequestResponseWithMarkers.java
|
package burp;
/*
* @(#)IHttpRequestResponseWithMarkers.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.util.List;
/**
* This interface is used for an
* <code>IHttpRequestResponse</code> object that has had markers applied.
* Extensions can create instances of this interface using
* <code>IBurpExtenderCallbacks.applyMarkers()</code>, or provide their own
* implementation. Markers are used in various situations, such as specifying
* Intruder payload positions, Scanner insertion points, and highlights in
* Scanner issues.
*/
public interface IHttpRequestResponseWithMarkers extends IHttpRequestResponse
{
/**
* This method returns the details of the request markers.
*
* @return A list of index pairs representing the offsets of markers for the
* request message. Each item in the list is an int[2] array containing the
* start and end offsets for the marker. The method may return
* <code>null</code> if no request markers are defined.
*/
List<int[]> getRequestMarkers();
/**
* This method returns the details of the response markers.
*
* @return A list of index pairs representing the offsets of markers for the
* response message. Each item in the list is an int[2] array containing the
* start and end offsets for the marker. The method may return
* <code>null</code> if no response markers are defined.
*/
List<int[]> getResponseMarkers();
}
| 1,913 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IMessageEditorController.java
|
package burp;
/*
* @(#)IMessageEditorController.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* This interface is used by an
* <code>IMessageEditor</code> to obtain details about the currently displayed
* message. Extensions that create instances of Burp's HTTP message editor can
* optionally provide an implementation of
* <code>IMessageEditorController</code>, which the editor will invoke when it
* requires further information about the current message (for example, to send
* it to another Burp tool). Extensions that provide custom editor tabs via an
* <code>IMessageEditorTabFactory</code> will receive a reference to an
* <code>IMessageEditorController</code> object for each tab instance they
* generate, which the tab can invoke if it requires further information about
* the current message.
*/
public interface IMessageEditorController
{
/**
* This method is used to retrieve the HTTP service for the current message.
*
* @return The HTTP service for the current message.
*/
IHttpService getHttpService();
/**
* This method is used to retrieve the HTTP request associated with the
* current message (which may itself be a response).
*
* @return The HTTP request associated with the current message.
*/
byte[] getRequest();
/**
* This method is used to retrieve the HTTP response associated with the
* current message (which may itself be a request).
*
* @return The HTTP response associated with the current message.
*/
byte[] getResponse();
}
| 1,914 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IIntruderAttack.java
|
package burp;
/*
* @(#)IIntruderAttack.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* This interface is used to hold details about an Intruder attack.
*/
public interface IIntruderAttack
{
/**
* This method is used to retrieve the HTTP service for the attack.
*
* @return The HTTP service for the attack.
*/
IHttpService getHttpService();
/**
* This method is used to retrieve the request template for the attack.
*
* @return The request template for the attack.
*/
byte[] getRequestTemplate();
}
| 1,915 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IExtensionStateListener.java
|
package burp;
/*
* @(#)IExtensionStateListener.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerExtensionStateListener()</code> to
* register an extension state listener. The listener will be notified of
* changes to the extension's state. <b>Note:</b> Any extensions that start
* background threads or open system resources (such as files or database
* connections) should register a listener and terminate threads / close
* resources when the extension is unloaded.
*/
public interface IExtensionStateListener
{
/**
* This method is called when the extension is unloaded.
*/
void extensionUnloaded();
}
| 1,916 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IHttpRequestResponsePersisted.java
|
package burp;
/*
* @(#)IHttpRequestResponsePersisted.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* This interface is used for an
* <code>IHttpRequestResponse</code> object whose request and response messages
* have been saved to temporary files using
* <code>IBurpExtenderCallbacks.saveBuffersToTempFiles()</code>.
*/
public interface IHttpRequestResponsePersisted extends IHttpRequestResponse
{
/**
* This method is used to permanently delete the saved temporary files. It
* will no longer be possible to retrieve the request or response for this
* item.
*/
void deleteTempFiles();
}
| 1,917 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IHttpListener.java
|
package burp;
/*
* @(#)IHttpListener.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerHttpListener()</code> to register an
* HTTP listener. The listener will be notified of requests and responses made
* by any Burp tool. Extensions can perform custom analysis or modification of
* these messages by registering an HTTP listener.
*/
public interface IHttpListener
{
/**
* This method is invoked when an HTTP request is about to be issued, and
* when an HTTP response has been received.
*
* @param toolFlag A flag indicating the Burp tool that issued the request.
* Burp tool flags are defined in the
* <code>IBurpExtenderCallbacks</code> interface.
* @param messageIsRequest Flags whether the method is being invoked for a
* request or response.
* @param messageInfo Details of the request / response to be processed.
* Extensions can call the setter methods on this object to update the
* current message and so modify Burp's behavior.
*/
void processHttpMessage(int toolFlag,
boolean messageIsRequest,
IHttpRequestResponse messageInfo);
}
| 1,918 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IIntruderPayloadGeneratorFactory.java
|
package burp;
/*
* @(#)IIntruderPayloadGeneratorFactory.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerIntruderPayloadGeneratorFactory()</code>
* to register a factory for custom Intruder payloads.
*/
public interface IIntruderPayloadGeneratorFactory
{
/**
* This method is used by Burp to obtain the name of the payload generator.
* This will be displayed as an option within the Intruder UI when the user
* selects to use extension-generated payloads.
*
* @return The name of the payload generator.
*/
String getGeneratorName();
/**
* This method is used by Burp when the user starts an Intruder attack that
* uses this payload generator.
*
* @param attack An
* <code>IIntruderAttack</code> object that can be queried to obtain details
* about the attack in which the payload generator will be used.
* @return A new instance of
* <code>IIntruderPayloadGenerator</code> that will be used to generate
* payloads for the attack.
*/
IIntruderPayloadGenerator createNewInstance(IIntruderAttack attack);
}
| 1,919 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IMenuItemHandler.java
|
package burp;
/*
* @(#)IMenuItemHandler.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerMenuItem()</code> to register a custom
* context menu item.
*
* @deprecated Use
* <code>IContextMenuFactory</code> instead.
*/
@Deprecated
public interface IMenuItemHandler
{
/**
* This method is invoked by Burp Suite when the user clicks on a custom
* menu item which the extension has registered with Burp.
*
* @param menuItemCaption The caption of the menu item which was clicked.
* This parameter enables extensions to provide a single implementation
* which handles multiple different menu items.
* @param messageInfo Details of the HTTP message(s) for which the context
* menu was displayed.
*/
void menuItemClicked(
String menuItemCaption,
IHttpRequestResponse[] messageInfo);
}
| 1,920 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IScanQueueItem.java
|
package burp;
/*
* @(#)IScanQueueItem.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* This interface is used to retrieve details of items in the Burp Scanner
* active scan queue. Extensions can obtain references to scan queue items by
* calling
* <code>IBurpExtenderCallbacks.doActiveScan()</code>.
*/
public interface IScanQueueItem
{
/**
* This method returns a description of the status of the scan queue item.
*
* @return A description of the status of the scan queue item.
*/
String getStatus();
/**
* This method returns an indication of the percentage completed for the
* scan queue item.
*
* @return An indication of the percentage completed for the scan queue
* item.
*/
byte getPercentageComplete();
/**
* This method returns the number of requests that have been made for the
* scan queue item.
*
* @return The number of requests that have been made for the scan queue
* item.
*/
int getNumRequests();
/**
* This method returns the number of network errors that have occurred for
* the scan queue item.
*
* @return The number of network errors that have occurred for the scan
* queue item.
*/
int getNumErrors();
/**
* This method returns the number of attack insertion points being used for
* the scan queue item.
*
* @return The number of attack insertion points being used for the scan
* queue item.
*/
int getNumInsertionPoints();
/**
* This method allows the scan queue item to be canceled.
*/
void cancel();
/**
* This method returns details of the issues generated for the scan queue
* item. <b>Note:</b> different items within the scan queue may contain
* duplicated versions of the same issues - for example, if the same request
* has been scanned multiple times. Duplicated issues are consolidated in
* the main view of scan results. Extensions can register an
* <code>IScannerListener</code> to get details only of unique, newly
* discovered Scanner issues post-consolidation.
*
* @return Details of the issues generated for the scan queue item.
*/
IScanIssue[] getIssues();
}
| 1,921 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IMessageEditor.java
|
package burp;
/*
* @(#)IMessageEditor.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.awt.*;
/**
* This interface is used to provide extensions with an instance of Burp's HTTP
* message editor, for the extension to use in its own UI. Extensions should
* call
* <code>IBurpExtenderCallbacks.createMessageEditor()</code> to obtain an
* instance of this interface.
*/
public interface IMessageEditor
{
/**
* This method returns the UI component of the editor, for extensions to add
* to their own UI.
*
* @return The UI component of the editor.
*/
Component getComponent();
/**
* This method is used to display an HTTP message in the editor.
*
* @param message The HTTP message to be displayed.
* @param isRequest Flags whether the message is an HTTP request or
* response.
*/
void setMessage(byte[] message, boolean isRequest);
/**
* This method is used to retrieve the currently displayed message, which
* may have been modified by the user.
*
* @return The currently displayed HTTP message.
*/
byte[] getMessage();
/**
* This method is used to determine whether the current message has been
* modified by the user.
*
* @return An indication of whether the current message has been modified by
* the user since it was first displayed.
*/
boolean isMessageModified();
/**
* This method returns the data that is currently selected by the user.
*
* @return The data that is currently selected by the user, or
* <code>null</code> if no selection is made.
*/
byte[] getSelectedData();
}
| 1,922 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IScannerInsertionPointProvider.java
|
package burp;
/*
* @(#)IScannerInsertionPointProvider.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.util.List;
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerScannerInsertionPointProvider()</code>
* to register a factory for custom Scanner insertion points.
*/
public interface IScannerInsertionPointProvider
{
/**
* When a request is actively scanned, the Scanner will invoke this method,
* and the provider should provide a list of custom insertion points that
* will be used in the scan. <b>Note:</b> these insertion points are used in
* addition to those that are derived from Burp Scanner's configuration, and
* those provided by any other Burp extensions.
*
* @param baseRequestResponse The base request that will be actively
* scanned.
* @return A list of
* <code>IScannerInsertionPoint</code> objects that should be used in the
* scanning, or
* <code>null</code> if no custom insertion points are applicable for this
* request.
*/
List<IScannerInsertionPoint> getInsertionPoints(
IHttpRequestResponse baseRequestResponse);
}
| 1,923 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IScanIssue.java
|
package burp;
/*
* @(#)IScanIssue.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* This interface is used to retrieve details of Scanner issues. Extensions can
* obtain details of issues by registering an
* <code>IScannerListener</code> or by calling
* <code>IBurpExtenderCallbacks.getScanIssues()</code>. Extensions can also add
* custom Scanner issues by registering an
* <code>IScannerCheck</code> or calling
* <code>IBurpExtenderCallbacks.addScanIssue()</code>, and providing their own
* implementations of this interface
*/
public interface IScanIssue
{
/**
* This method returns the URL for which the issue was generated.
*
* @return The URL for which the issue was generated.
*/
java.net.URL getUrl();
/**
* This method returns the name of the issue type.
*
* @return The name of the issue type (e.g. "SQL injection").
*/
String getIssueName();
/**
* This method returns a numeric identifier of the issue type. See the Burp
* Scanner help documentation for a listing of all the issue types.
*
* @return A numeric identifier of the issue type.
*/
int getIssueType();
/**
* This method returns the issue severity level.
*
* @return The issue severity level. Expected values are "High", "Medium",
* "Low", "Information" or "False positive".
*
*/
String getSeverity();
/**
* This method returns the issue confidence level.
*
* @return The issue confidence level. Expected values are "Certain", "Firm"
* or "Tentative".
*/
String getConfidence();
/**
* This method returns a background description for this type of issue.
*
* @return A background description for this type of issue, or
* <code>null</code> if none applies.
*/
String getIssueBackground();
/**
* This method returns a background description of the remediation for this
* type of issue.
*
* @return A background description of the remediation for this type of
* issue, or
* <code>null</code> if none applies.
*/
String getRemediationBackground();
/**
* This method returns detailed information about this specific instance of
* the issue.
*
* @return Detailed information about this specific instance of the issue,
* or
* <code>null</code> if none applies.
*/
String getIssueDetail();
/**
* This method returns detailed information about the remediation for this
* specific instance of the issue.
*
* @return Detailed information about the remediation for this specific
* instance of the issue, or
* <code>null</code> if none applies.
*/
String getRemediationDetail();
/**
* This method returns the HTTP messages on the basis of which the issue was
* generated.
*
* @return The HTTP messages on the basis of which the issue was generated.
* <b>Note:</b> The items in this array should be instances of
* <code>IHttpRequestResponseWithMarkers</code> if applicable, so that
* details of the relevant portions of the request and response messages are
* available.
*/
IHttpRequestResponse[] getHttpMessages();
/**
* This method returns the HTTP service for which the issue was generated.
*
* @return The HTTP service for which the issue was generated.
*/
IHttpService getHttpService();
}
| 1,924 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/ISessionHandlingAction.java
|
package burp;
/*
* @(#)ISessionHandlingAction.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerSessionHandlingAction()</code> to
* register a custom session handling action. Each registered action will be
* available within the session handling rule UI for the user to select as a
* rule action. Users can choose to invoke an action directly in its own right,
* or following execution of a macro.
*/
public interface ISessionHandlingAction
{
/**
* This method is used by Burp to obtain the name of the session handling
* action. This will be displayed as an option within the session handling
* rule editor when the user selects to execute an extension-provided
* action.
*
* @return The name of the action.
*/
String getActionName();
/**
* This method is invoked when the session handling action should be
* executed. This may happen as an action in its own right, or as a
* sub-action following execution of a macro.
*
* @param currentRequest The base request that is currently being processed.
* The action can query this object to obtain details about the base
* request. It can issue additional requests of its own if necessary, and
* can use the setter methods on this object to update the base request.
* @param macroItems If the action is invoked following execution of a
* macro, this parameter contains the result of executing the macro.
* Otherwise, it is
* <code>null</code>. Actions can use the details of the macro items to
* perform custom analysis of the macro to derive values of non-standard
* session handling tokens, etc.
*/
void performAction(
IHttpRequestResponse currentRequest,
IHttpRequestResponse[] macroItems);
}
| 1,925 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IIntruderPayloadProcessor.java
|
package burp;
/*
* @(#)IIntruderPayloadProcessor.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerIntruderPayloadProcessor()</code> to
* register a custom Intruder payload processor.
*/
public interface IIntruderPayloadProcessor
{
/**
* This method is used by Burp to obtain the name of the payload processor.
* This will be displayed as an option within the Intruder UI when the user
* selects to use an extension-provided payload processor.
*
* @return The name of the payload processor.
*/
String getProcessorName();
/**
* This method is invoked by Burp each time the processor should be applied
* to an Intruder payload.
*
* @param currentPayload The value of the payload to be processed.
* @param originalPayload The value of the original payload prior to
* processing by any already-applied processing rules.
* @param baseValue The base value of the payload position, which will be
* replaced with the current payload.
* @return The value of the processed payload. This may be
* <code>null</code> to indicate that the current payload should be skipped,
* and the attack will move directly to the next payload.
*/
byte[] processPayload(
byte[] currentPayload,
byte[] originalPayload,
byte[] baseValue);
}
| 1,926 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IHttpService.java
|
package burp;
/*
* @(#)IHttpService.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* This interface is used to provide details about an HTTP service, to which
* HTTP requests can be sent.
*/
public interface IHttpService
{
/**
* This method returns the hostname or IP address for the service.
*
* @return The hostname or IP address for the service.
*/
String getHost();
/**
* This method returns the port number for the service.
*
* @return The port number for the service.
*/
int getPort();
/**
* This method returns the protocol for the service.
*
* @return The protocol for the service. Expected values are "http" or
* "https".
*/
String getProtocol();
}
| 1,927 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/ICookie.java
|
package burp;
/*
* @(#)ICookie.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.util.Date;
/**
* This interface is used to hold details about an HTTP cookie.
*/
public interface ICookie
{
/**
* This method is used to retrieve the domain for which the cookie is in
* scope.
*
* @return The domain for which the cookie is in scope. <b>Note:</b> For
* cookies that have been analyzed from responses (by calling
* <code>IExtensionHelpers.analyzeResponse()</code> and then
* <code>IResponseInfo.getCookies()</code>, the domain will be
* <code>null</code> if the response did not explicitly set a domain
* attribute for the cookie.
*/
String getDomain();
/**
* This method is used to retrieve the expiration time for the cookie.
*
* @return The expiration time for the cookie, or
* <code>null</code> if none is set (i.e., for non-persistent session
* cookies).
*/
Date getExpiration();
/**
* This method is used to retrieve the name of the cookie.
*
* @return The name of the cookie.
*/
String getName();
/**
* This method is used to retrieve the value of the cookie.
* @return The value of the cookie.
*/
String getValue();
}
| 1,928 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IBurpExtender.java
|
package burp;
/*
* @(#)IBurpExtender.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* All extensions must implement this interface.
*
* Implementations must be called BurpExtender, in the package burp, must be
* declared public, and must provide a default (public, no-argument)
* constructor.
*/
public interface IBurpExtender
{
/**
* This method is invoked when the extension is loaded. It registers an
* instance of the
* <code>IBurpExtenderCallbacks</code> interface, providing methods that may
* be invoked by the extension to perform various actions.
*
* @param callbacks An
* <code>IBurpExtenderCallbacks</code> object.
*/
void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks);
}
| 1,929 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IRequestInfo.java
|
package burp;
/*
* @(#)IRequestInfo.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.net.URL;
import java.util.List;
/**
* This interface is used to retrieve key details about an HTTP request.
* Extensions can obtain an
* <code>IRequestInfo</code> object for a given request by calling
* <code>IExtensionHelpers.analyzeRequest()</code>.
*/
public interface IRequestInfo
{
/**
* Used to indicate that there is no content.
*/
static final byte CONTENT_TYPE_NONE = 0;
/**
* Used to indicate URL-encoded content.
*/
static final byte CONTENT_TYPE_URL_ENCODED = 1;
/**
* Used to indicate multi-part content.
*/
static final byte CONTENT_TYPE_MULTIPART = 2;
/**
* Used to indicate XML content.
*/
static final byte CONTENT_TYPE_XML = 3;
/**
* Used to indicate JSON content.
*/
static final byte CONTENT_TYPE_JSON = 4;
/**
* Used to indicate AMF content.
*/
static final byte CONTENT_TYPE_AMF = 5;
/**
* Used to indicate unknown content.
*/
static final byte CONTENT_TYPE_UNKNOWN = -1;
/**
* This method is used to obtain the HTTP method used in the request.
*
* @return The HTTP method used in the request.
*/
String getMethod();
/**
* This method is used to obtain the URL in the request.
*
* @return The URL in the request.
*/
URL getUrl();
/**
* This method is used to obtain the HTTP headers contained in the request.
*
* @return The HTTP headers contained in the request.
*/
List<String> getHeaders();
/**
* This method is used to obtain the parameters contained in the request.
*
* @return The parameters contained in the request.
*/
List<IParameter> getParameters();
/**
* This method is used to obtain the offset within the request where the
* message body begins.
*
* @return The offset within the request where the message body begins.
*/
int getBodyOffset();
/**
* This method is used to obtain the content type of the message body.
*
* @return An indication of the content type of the message body. Available
* types are defined within this interface.
*/
byte getContentType();
}
| 1,930 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/ITempFile.java
|
package burp;
/*
* @(#)ITempFile.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* This interface is used to hold details of a temporary file that has been
* created via a call to
* <code>IBurpExtenderCallbacks.saveToTempFile()</code>.
*
*/
public interface ITempFile
{
/**
* This method is used to retrieve the contents of the buffer that was saved
* in the temporary file.
*
* @return The contents of the buffer that was saved in the temporary file.
*/
byte[] getBuffer();
/**
* This method is used to permanently delete the temporary file when it is
* no longer required.
*/
void delete();
}
| 1,931 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IScannerInsertionPoint.java
|
package burp;
/*
* @(#)IScannerInsertionPoint.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* This interface is used to define an insertion point for use by active Scanner
* checks. Extensions can obtain instances of this interface by registering an
* <code>IScannerCheck</code>, or can create instances for use by Burp's own
* scan checks by registering an
* <code>IScannerInsertionPointProvider</code>.
*/
public interface IScannerInsertionPoint
{
/**
* Used to indicate where the payload is inserted into the value of a URL
* parameter.
*/
static final byte INS_PARAM_URL = 0x00;
/**
* Used to indicate where the payload is inserted into the value of a body
* parameter.
*/
static final byte INS_PARAM_BODY = 0x01;
/**
* Used to indicate where the payload is inserted into the value of an HTTP
* cookie.
*/
static final byte INS_PARAM_COOKIE = 0x02;
/**
* Used to indicate where the payload is inserted into the value of an item
* of data within an XML data structure.
*/
static final byte INS_PARAM_XML = 0x03;
/**
* Used to indicate where the payload is inserted into the value of a tag
* attribute within an XML structure.
*/
static final byte INS_PARAM_XML_ATTR = 0x04;
/**
* Used to indicate where the payload is inserted into the value of a
* parameter attribute within a multi-part message body (such as the name of
* an uploaded file).
*/
static final byte INS_PARAM_MULTIPART_ATTR = 0x05;
/**
* Used to indicate where the payload is inserted into the value of an item
* of data within a JSON structure.
*/
static final byte INS_PARAM_JSON = 0x06;
/**
* Used to indicate where the payload is inserted into the value of an AMF
* parameter.
*/
static final byte INS_PARAM_AMF = 0x07;
/**
* Used to indicate where the payload is inserted into the value of an HTTP
* request header.
*/
static final byte INS_HEADER = 0x20;
/**
* Used to indicate where the payload is inserted into a REST parameter
* within the URL file path.
*/
static final byte INS_URL_REST = 0x21;
/**
* Used to indicate where the payload is inserted into the name of an added
* URL parameter.
*/
static final byte INS_PARAM_NAME_URL = 0x22;
/**
* Used to indicate where the payload is inserted into the name of an added
* body parameter.
*/
static final byte INS_PARAM_NAME_BODY = 0x23;
/**
* Used to indicate where the payload is inserted at a location manually
* configured by the user.
*/
static final byte INS_USER_PROVIDED = 0x40;
/**
* Used to indicate where the insertion point is provided by an
* extension-registered
* <code>IScannerInsertionPointProvider</code>.
*/
static final byte INS_EXTENSION_PROVIDED = 0x41;
/**
* Used to indicate where the payload is inserted at an unknown location
* within the request.
*/
static final byte INS_UNKNOWN = 0x7f;
/**
* This method returns the name of the insertion point.
*
* @return The name of the insertion point (for example, a description of a
* particular request parameter).
*/
String getInsertionPointName();
/**
* This method returns the base value for this insertion point.
*
* @return the base value that appears in this insertion point in the base
* request being scanned, or
* <code>null</code> if there is no value in the base request that
* corresponds to this insertion point.
*/
String getBaseValue();
/**
* This method is used to build a request with the specified payload placed
* into the insertion point. Any necessary adjustments to the Content-Length
* header will be made by the Scanner itself when the request is issued, and
* there is no requirement for the insertion point to do this. <b>Note:</b>
* Burp's built-in scan checks do not apply any payload encoding (such as
* URL-encoding) when dealing with an extension-provided insertion point.
* Custom insertion points are responsible for performing any data encoding
* that is necessary given the nature and location of the insertion point.
*
* @param payload The payload that should be placed into the insertion
* point.
* @return The resulting request.
*/
byte[] buildRequest(byte[] payload);
/**
* This method is used to determine the offsets of the payload value within
* the request, when it is placed into the insertion point. Scan checks may
* invoke this method when reporting issues, so as to highlight the relevant
* part of the request within the UI.
*
* @param payload The payload that should be placed into the insertion
* point.
* @return An int[2] array containing the start and end offsets of the
* payload within the request, or null if this is not applicable (for
* example, where the insertion point places a payload into a serialized
* data structure, the raw payload may not literally appear anywhere within
* the resulting request).
*/
int[] getPayloadOffsets(byte[] payload);
/**
* This method returns the type of the insertion point.
*
* @return The type of the insertion point. Available types are defined in
* this interface.
*/
byte getInsertionPointType();
}
| 1,932 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IContextMenuInvocation.java
|
package burp;
/*
* @(#)IContextMenuInvocation.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.awt.event.InputEvent;
/**
* This interface is used when Burp calls into an extension-provided
* <code>IContextMenuFactory</code> with details of a context menu invocation.
* The custom context menu factory can query this interface to obtain details of
* the invocation event, in order to determine what menu items should be
* displayed.
*/
public interface IContextMenuInvocation
{
/**
* Used to indicate that the context menu is being invoked in a request
* editor.
*/
static final byte CONTEXT_MESSAGE_EDITOR_REQUEST = 0;
/**
* Used to indicate that the context menu is being invoked in a response
* editor.
*/
static final byte CONTEXT_MESSAGE_EDITOR_RESPONSE = 1;
/**
* Used to indicate that the context menu is being invoked in a non-editable
* request viewer.
*/
static final byte CONTEXT_MESSAGE_VIEWER_REQUEST = 2;
/**
* Used to indicate that the context menu is being invoked in a non-editable
* response viewer.
*/
static final byte CONTEXT_MESSAGE_VIEWER_RESPONSE = 3;
/**
* Used to indicate that the context menu is being invoked in the Target
* site map tree.
*/
static final byte CONTEXT_TARGET_SITE_MAP_TREE = 4;
/**
* Used to indicate that the context menu is being invoked in the Target
* site map table.
*/
static final byte CONTEXT_TARGET_SITE_MAP_TABLE = 5;
/**
* Used to indicate that the context menu is being invoked in the Proxy
* history.
*/
static final byte CONTEXT_PROXY_HISTORY = 6;
/**
* Used to indicate that the context menu is being invoked in the Scanner
* results.
*/
static final byte CONTEXT_SCANNER_RESULTS = 7;
/**
* Used to indicate that the context menu is being invoked in the Intruder
* payload positions editor.
*/
static final byte CONTEXT_INTRUDER_PAYLOAD_POSITIONS = 8;
/**
* Used to indicate that the context menu is being invoked in an Intruder
* attack results.
*/
static final byte CONTEXT_INTRUDER_ATTACK_RESULTS = 9;
/**
* Used to indicate that the context menu is being invoked in a search
* results window.
*/
static final byte CONTEXT_SEARCH_RESULTS = 10;
/**
* This method can be used to retrieve the native Java input event that was
* the trigger for the context menu invocation.
*
* @return The <code>InputEvent</code> that was the trigger for the context
* menu invocation.
*/
InputEvent getInputEvent();
/**
* This method can be used to retrieve the Burp tool within which the
* context menu was invoked.
*
* @return A flag indicating the Burp tool within which the context menu was
* invoked. Burp tool flags are defined in the
* <code>IBurpExtenderCallbacks</code> interface.
*/
int getToolFlag();
/**
* This method can be used to retrieve the context within which the menu was
* invoked.
*
* @return An index indicating the context within which the menu was
* invoked. The indices used are defined within this interface.
*/
byte getInvocationContext();
/**
* This method can be used to retrieve the bounds of the user's selection
* into the current message, if applicable.
*
* @return An int[2] array containing the start and end offsets of the
* user's selection in the current message. If the user has not made any
* selection in the current message, both offsets indicate the position of
* the caret within the editor. If the menu is not being invoked from a
* message editor, the method returns <code>null</code>.
*/
int[] getSelectionBounds();
/**
* This method can be used to retrieve details of the HTTP requests /
* responses that were shown or selected by the user when the context menu
* was invoked.
*
* <b>Note:</b> For performance reasons, the objects returned from this
* method are tied to the originating context of the messages within the
* Burp UI. For example, if a context menu is invoked on the Proxy intercept
* panel, then the
* <code>IHttpRequestResponse</code> returned by this method will reflect
* the current contents of the interception panel, and this will change when
* the current message has been forwarded or dropped. If your extension
* needs to store details of the message for which the context menu has been
* invoked, then you should query those details from the
* <code>IHttpRequestResponse</code> at the time of invocation, or you
* should use
* <code>IBurpExtenderCallbacks.saveBuffersToTempFiles()</code> to create a
* persistent read-only copy of the
* <code>IHttpRequestResponse</code>.
*
* @return An array of <code>IHttpRequestResponse</code> objects
* representing the items that were shown or selected by the user when the
* context menu was invoked. This method returns <code>null</code> if no
* messages are applicable to the invocation.
*/
IHttpRequestResponse[] getSelectedMessages();
/**
* This method can be used to retrieve details of the Scanner issues that
* were selected by the user when the context menu was invoked.
*
* @return An array of <code>IScanIssue</code> objects representing the
* issues that were selected by the user when the context menu was invoked.
* This method returns <code>null</code> if no Scanner issues are applicable
* to the invocation.
*/
IScanIssue[] getSelectedIssues();
}
| 1,933 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IExtensionHelpers.java
|
package burp;
/*
* @(#)IExtensionHelpers.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.net.URL;
import java.util.List;
/**
* This interface contains a number of helper methods, which extensions can use
* to assist with various common tasks that arise for Burp extensions.
*
* Extensions can call
* <code>IBurpExtenderCallbacks.getHelpers</code> to obtain an instance of this
* interface.
*/
public interface IExtensionHelpers
{
/**
* This method can be used to analyze an HTTP request, and obtain various
* key details about it.
*
* @param request An
* <code>IHttpRequestResponse</code> object containing the request to be
* analyzed.
* @return An
* <code>IRequestInfo</code> object that can be queried to obtain details
* about the request.
*/
IRequestInfo analyzeRequest(IHttpRequestResponse request);
/**
* This method can be used to analyze an HTTP request, and obtain various
* key details about it.
*
* @param httpService The HTTP service associated with the request. This is
* optional and may be
* <code>null</code>, in which case the resulting
* <code>IRequestInfo</code> object will not include the full request URL.
* @param request The request to be analyzed.
* @return An
* <code>IRequestInfo</code> object that can be queried to obtain details
* about the request.
*/
IRequestInfo analyzeRequest(IHttpService httpService, byte[] request);
/**
* This method can be used to analyze an HTTP request, and obtain various
* key details about it. The resulting
* <code>IRequestInfo</code> object will not include the full request URL.
* To obtain the full URL, use one of the other overloaded
* <code>analyzeRequest()</code> methods.
*
* @param request The request to be analyzed.
* @return An
* <code>IRequestInfo</code> object that can be queried to obtain details
* about the request.
*/
IRequestInfo analyzeRequest(byte[] request);
/**
* This method can be used to analyze an HTTP response, and obtain various
* key details about it.
*
* @param response The response to be analyzed.
* @return An
* <code>IResponseInfo</code> object that can be queried to obtain details
* about the response.
*/
IResponseInfo analyzeResponse(byte[] response);
/**
* This method can be used to retrieve details of a specified parameter
* within an HTTP request. <b>Note:</b> Use
* <code>analyzeRequest()</code> to obtain details of all parameters within
* the request.
*
* @param request The request to be inspected for the specified parameter.
* @param parameterName The name of the parameter to retrieve.
* @return An
* <code>IParameter</code> object that can be queried to obtain details
* about the parameter, or
* <code>null</code> if the parameter was not found.
*/
IParameter getRequestParameter(byte[] request, String parameterName);
/**
* This method can be used to URL-decode the specified data.
*
* @param data The data to be decoded.
* @return The decoded data.
*/
String urlDecode(String data);
/**
* This method can be used to URL-encode the specified data. Any characters
* that do not need to be encoded within HTTP requests are not encoded.
*
* @param data The data to be encoded.
* @return The encoded data.
*/
String urlEncode(String data);
/**
* This method can be used to URL-decode the specified data.
*
* @param data The data to be decoded.
* @return The decoded data.
*/
byte[] urlDecode(byte[] data);
/**
* This method can be used to URL-encode the specified data. Any characters
* that do not need to be encoded within HTTP requests are not encoded.
*
* @param data The data to be encoded.
* @return The encoded data.
*/
byte[] urlEncode(byte[] data);
/**
* This method can be used to Base64-decode the specified data.
*
* @param data The data to be decoded.
* @return The decoded data.
*/
byte[] base64Decode(String data);
/**
* This method can be used to Base64-decode the specified data.
*
* @param data The data to be decoded.
* @return The decoded data.
*/
byte[] base64Decode(byte[] data);
/**
* This method can be used to Base64-encode the specified data.
*
* @param data The data to be encoded.
* @return The encoded data.
*/
String base64Encode(String data);
/**
* This method can be used to Base64-encode the specified data.
*
* @param data The data to be encoded.
* @return The encoded data.
*/
String base64Encode(byte[] data);
/**
* This method can be used to convert data from String form into an array of
* bytes. The conversion does not reflect any particular character set, and
* a character with the hex representation 0xWXYZ will always be converted
* into a byte with the representation 0xYZ. It performs the opposite
* conversion to the method
* <code>bytesToString()</code>, and byte-based data that is converted to a
* String and back again using these two methods is guaranteed to retain its
* integrity (which may not be the case with conversions that reflect a
* given character set).
*
* @param data The data to be converted.
* @return The converted data.
*/
byte[] stringToBytes(String data);
/**
* This method can be used to convert data from an array of bytes into
* String form. The conversion does not reflect any particular character
* set, and a byte with the representation 0xYZ will always be converted
* into a character with the hex representation 0x00YZ. It performs the
* opposite conversion to the method
* <code>stringToBytes()</code>, and byte-based data that is converted to a
* String and back again using these two methods is guaranteed to retain its
* integrity (which may not be the case with conversions that reflect a
* given character set).
*
* @param data The data to be converted.
* @return The converted data.
*/
String bytesToString(byte[] data);
/**
* This method searches a piece of data for the first occurrence of a
* specified pattern. It works on byte-based data in a way that is similar
* to the way the native Java method
* <code>String.indexOf()</code> works on String-based data.
*
* @param data The data to be searched.
* @param pattern The pattern to be searched for.
* @param caseSensitive Flags whether or not the search is case-sensitive.
* @param from The offset within
* <code>data</code> where the search should begin.
* @param to The offset within
* <code>data</code> where the search should end.
* @return The offset of the first occurrence of the pattern within the
* specified bounds, or -1 if no match is found.
*/
int indexOf(byte[] data,
byte[] pattern,
boolean caseSensitive,
int from,
int to);
/**
* This method builds an HTTP message containing the specified headers and
* message body. If applicable, the Content-Length header will be added or
* updated, based on the length of the body.
*
* @param headers A list of headers to include in the message.
* @param body The body of the message, of
* <code>null</code> if the message has an empty body.
* @return The resulting full HTTP message.
*/
byte[] buildHttpMessage(List<String> headers, byte[] body);
/**
* This method creates a GET request to the specified URL. The headers used
* in the request are determined by the Request headers settings as
* configured in Burp Spider's options.
*
* @param url The URL to which the request should be made.
* @return A request to the specified URL.
*/
byte[] buildHttpRequest(URL url);
/**
* This method adds a new parameter to an HTTP request, and if appropriate
* updates the Content-Length header.
*
* @param request The request to which the parameter should be added.
* @param parameter An
* <code>IParameter</code> object containing details of the parameter to be
* added. Supported parameter types are:
* <code>PARAM_URL</code>,
* <code>PARAM_BODY</code> and
* <code>PARAM_COOKIE</code>.
* @return A new HTTP request with the new parameter added.
*/
byte[] addParameter(byte[] request, IParameter parameter);
/**
* This method removes a parameter from an HTTP request, and if appropriate
* updates the Content-Length header.
*
* @param request The request from which the parameter should be removed.
* @param parameter An
* <code>IParameter</code> object containing details of the parameter to be
* removed. Supported parameter types are:
* <code>PARAM_URL</code>,
* <code>PARAM_BODY</code> and
* <code>PARAM_COOKIE</code>.
* @return A new HTTP request with the parameter removed.
*/
byte[] removeParameter(byte[] request, IParameter parameter);
/**
* This method updates the value of a parameter within an HTTP request, and
* if appropriate updates the Content-Length header. <b>Note:</b> This
* method can only be used to update the value of an existing parameter of a
* specified type. If you need to change the type of an existing parameter,
* you should first call
* <code>removeParameter()</code> to remove the parameter with the old type,
* and then call
* <code>addParameter()</code> to add a parameter with the new type.
*
* @param request The request containing the parameter to be updated.
* @param parameter An
* <code>IParameter</code> object containing details of the parameter to be
* updated. Supported parameter types are:
* <code>PARAM_URL</code>,
* <code>PARAM_BODY</code> and
* <code>PARAM_COOKIE</code>.
* @return A new HTTP request with the parameter updated.
*/
byte[] updateParameter(byte[] request, IParameter parameter);
/**
* This method can be used to toggle a request's method between GET and
* POST. Parameters are relocated between the URL query string and message
* body as required, and the Content-Length header is created or removed as
* applicable.
*
* @param request The HTTP request whose method should be toggled.
* @return A new HTTP request using the toggled method.
*/
byte[] toggleRequestMethod(byte[] request);
/**
* This method constructs an
* <code>IHttpService</code> object based on the details provided.
*
* @param host The HTTP service host.
* @param port The HTTP service port.
* @param protocol The HTTP service protocol.
* @return An
* <code>IHttpService</code> object based on the details provided.
*/
IHttpService buildHttpService(String host, int port, String protocol);
/**
* This method constructs an
* <code>IHttpService</code> object based on the details provided.
*
* @param host The HTTP service host.
* @param port The HTTP service port.
* @param useHttps Flags whether the HTTP service protocol is HTTPS or HTTP.
* @return An
* <code>IHttpService</code> object based on the details provided.
*/
IHttpService buildHttpService(String host, int port, boolean useHttps);
/**
* This method constructs an
* <code>IParameter</code> object based on the details provided.
*
* @param name The parameter name.
* @param value The parameter value.
* @param type The parameter type, as defined in the
* <code>IParameter</code> interface.
* @return An
* <code>IParameter</code> object based on the details provided.
*/
IParameter buildParameter(String name, String value, byte type);
/**
* This method constructs an
* <code>IScannerInsertionPoint</code> object based on the details provided.
* It can be used to quickly create a simple insertion point based on a
* fixed payload location within a base request.
*
* @param insertionPointName The name of the insertion point.
* @param baseRequest The request from which to build scan requests.
* @param from The offset of the start of the payload location.
* @param to The offset of the end of the payload location.
* @return An
* <code>IScannerInsertionPoint</code> object based on the details provided.
*/
IScannerInsertionPoint makeScannerInsertionPoint(
String insertionPointName,
byte[] baseRequest,
int from,
int to);
}
| 1,934 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/ITextEditor.java
|
package burp;
/*
* @(#)ITextEditor.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.awt.*;
/**
* This interface is used to provide extensions with an instance of Burp's raw
* text editor, for the extension to use in its own UI. Extensions should call
* <code>IBurpExtenderCallbacks.createTextEditor()</code> to obtain an instance
* of this interface.
*/
public interface ITextEditor
{
/**
* This method returns the UI component of the editor, for extensions to add
* to their own UI.
*
* @return The UI component of the editor.
*/
Component getComponent();
/**
* This method is used to control whether the editor is currently editable.
* This status can be toggled on and off as required.
*
* @param editable Indicates whether the editor should be currently
* editable.
*/
void setEditable(boolean editable);
/**
* This method is used to update the currently displayed text in the editor.
*
* @param text The text to be displayed.
*/
void setText(byte[] text);
/**
* This method is used to retrieve the currently displayed text.
*
* @return The currently displayed text.
*/
byte[] getText();
/**
* This method is used to determine whether the user has modified the
* contents of the editor.
*
* @return An indication of whether the user has modified the contents of
* the editor since the last call to
* <code>setText()</code>.
*/
boolean isTextModified();
/**
* This method is used to obtain the currently selected text.
*
* @return The currently selected text, or
* <code>null</code> if the user has not made any selection.
*/
byte[] getSelectedText();
/**
* This method can be used to retrieve the bounds of the user's selection
* into the displayed text, if applicable.
*
* @return An int[2] array containing the start and end offsets of the
* user's selection within the displayed text. If the user has not made any
* selection in the current message, both offsets indicate the position of
* the caret within the editor.
*/
int[] getSelectionBounds();
/**
* This method is used to update the search expression that is shown in the
* search bar below the editor. The editor will automatically highlight any
* regions of the displayed text that match the search expression.
*
* @param expression The search expression.
*/
void setSearchExpression(String expression);
}
| 1,935 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IIntruderPayloadGenerator.java
|
package burp;
/*
* @(#)IIntruderPayloadGenerator.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* This interface is used for custom Intruder payload generators. Extensions
* that have registered an
* <code>IIntruderPayloadGeneratorFactory</code> must return a new instance of
* this interface when required as part of a new Intruder attack.
*/
public interface IIntruderPayloadGenerator
{
/**
* This method is used by Burp to determine whether the payload generator is
* able to provide any further payloads.
*
* @return Extensions should return
* <code>false</code> when all the available payloads have been used up,
* otherwise
* <code>true</code>.
*/
boolean hasMorePayloads();
/**
* This method is used by Burp to obtain the value of the next payload.
*
* @param baseValue The base value of the current payload position. This
* value may be
* <code>null</code> if the concept of a base value is not applicable (e.g.
* in a battering ram attack).
* @return The next payload to use in the attack.
*/
byte[] getNextPayload(byte[] baseValue);
/**
* This method is used by Burp to reset the state of the payload generator
* so that the next call to
* <code>getNextPayload()</code> returns the first payload again. This
* method will be invoked when an attack uses the same payload generator for
* more than one payload position, for example in a sniper attack.
*/
void reset();
}
| 1,936 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IHttpRequestResponse.java
|
package burp;
/*
* @(#)IHttpRequestResponse.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* This interface is used to retrieve and update details about HTTP messages.
*
* <b>Note:</b> The setter methods generally can only be used before the message
* has been processed, and not in read-only contexts. The getter methods
* relating to response details can only be used after the request has been
* issued.
*/
public interface IHttpRequestResponse
{
/**
* This method is used to retrieve the request message.
*
* @return The request message.
*/
byte[] getRequest();
/**
* This method is used to update the request message.
*
* @param message The new request message.
*/
void setRequest(byte[] message);
/**
* This method is used to retrieve the response message.
*
* @return The response message.
*/
byte[] getResponse();
/**
* This method is used to update the response message.
*
* @param message The new response message.
*/
void setResponse(byte[] message);
/**
* This method is used to retrieve the user-annotated comment for this item,
* if applicable.
*
* @return The user-annotated comment for this item, or null if none is set.
*/
String getComment();
/**
* This method is used to update the user-annotated comment for this item.
*
* @param comment The comment to be assigned to this item.
*/
void setComment(String comment);
/**
* This method is used to retrieve the user-annotated highlight for this
* item, if applicable.
*
* @return The user-annotated highlight for this item, or null if none is
* set.
*/
String getHighlight();
/**
* This method is used to update the user-annotated highlight for this item.
*
* @param color The highlight color to be assigned to this item. Accepted
* values are: red, orange, yellow, green, cyan, blue, pink, magenta, gray,
* or a null String to clear any existing highlight.
*/
void setHighlight(String color);
/**
* This method is used to retrieve the HTTP service for this request /
* response.
*
* @return An
* <code>IHttpService</code> object containing details of the HTTP service.
*/
IHttpService getHttpService();
/**
* This method is used to update the HTTP service for this request /
* response.
*
* @param httpService An
* <code>IHttpService</code> object containing details of the new HTTP
* service.
*/
void setHttpService(IHttpService httpService);
}
| 1,937 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IParameter.java
|
package burp;
/*
* @(#)IParameter.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* This interface is used to hold details about an HTTP request parameter.
*/
public interface IParameter
{
/**
* Used to indicate a parameter within the URL query string.
*/
static final byte PARAM_URL = 0;
/**
* Used to indicate a parameter within the message body.
*/
static final byte PARAM_BODY = 1;
/**
* Used to indicate an HTTP cookie.
*/
static final byte PARAM_COOKIE = 2;
/**
* Used to indicate an item of data within an XML structure.
*/
static final byte PARAM_XML = 3;
/**
* Used to indicate the value of a tag attribute within an XML structure.
*/
static final byte PARAM_XML_ATTR = 4;
/**
* Used to indicate the value of a parameter attribute within a multi-part
* message body (such as the name of an uploaded file).
*/
static final byte PARAM_MULTIPART_ATTR = 5;
/**
* Used to indicate an item of data within a JSON structure.
*/
static final byte PARAM_JSON = 6;
/**
* This method is used to retrieve the parameter type.
*
* @return The parameter type. The available types are defined within this
* interface.
*/
byte getType();
/**
* This method is used to retrieve the parameter name.
*
* @return The parameter name.
*/
String getName();
/**
* This method is used to retrieve the parameter value.
*
* @return The parameter value.
*/
String getValue();
/**
* This method is used to retrieve the start offset of the parameter name
* within the HTTP request.
*
* @return The start offset of the parameter name within the HTTP request,
* or -1 if the parameter is not associated with a specific request.
*/
int getNameStart();
/**
* This method is used to retrieve the end offset of the parameter name
* within the HTTP request.
*
* @return The end offset of the parameter name within the HTTP request, or
* -1 if the parameter is not associated with a specific request.
*/
int getNameEnd();
/**
* This method is used to retrieve the start offset of the parameter value
* within the HTTP request.
*
* @return The start offset of the parameter value within the HTTP request,
* or -1 if the parameter is not associated with a specific request.
*/
int getValueStart();
/**
* This method is used to retrieve the end offset of the parameter value
* within the HTTP request.
*
* @return The end offset of the parameter value within the HTTP request, or
* -1 if the parameter is not associated with a specific request.
*/
int getValueEnd();
}
| 1,938 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IScannerListener.java
|
package burp;
/*
* @(#)IScannerListener.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
/**
* Extensions can implement this interface and then call
* <code>IBurpExtenderCallbacks.registerScannerListener()</code> to register a
* Scanner listener. The listener will be notified of new issues that are
* reported by the Scanner tool. Extensions can perform custom analysis or
* logging of Scanner issues by registering a Scanner listener.
*/
public interface IScannerListener
{
/**
* This method is invoked when a new issue is added to Burp Scanner's
* results.
*
* @param issue An
* <code>IScanIssue</code> object that the extension can query to obtain
* details about the new issue.
*/
void newScanIssue(IScanIssue issue);
}
| 1,939 |
0 |
Create_ds/msl/examples/burp-extender/src/main/java
|
Create_ds/msl/examples/burp-extender/src/main/java/burp/IMessageEditorTab.java
|
package burp;
/*
* @(#)IMessageEditorTab.java
*
* Copyright PortSwigger Ltd. All rights reserved.
*
* This code may be used to extend the functionality of Burp Suite Free Edition
* and Burp Suite Professional, provided that this usage does not violate the
* license terms for those products.
*/
import java.awt.*;
/**
* Extensions that register an
* <code>IMessageEditorTabFactory</code> must return instances of this
* interface, which Burp will use to create custom tabs within its HTTP message
* editors.
*/
public interface IMessageEditorTab
{
/**
* This method returns the caption that should appear on the custom tab when
* it is displayed. <b>Note:</b> Burp invokes this method once when the tab
* is first generated, and the same caption will be used every time the tab
* is displayed.
*
* @return The caption that should appear on the custom tab when it is
* displayed.
*/
String getTabCaption();
/**
* This method returns the component that should be used as the contents of
* the custom tab when it is displayed. <b>Note:</b> Burp invokes this
* method once when the tab is first generated, and the same component will
* be used every time the tab is displayed.
*
* @return The component that should be used as the contents of the custom
* tab when it is displayed.
*/
Component getUiComponent();
/**
* The hosting editor will invoke this method before it displays a new HTTP
* message, so that the custom tab can indicate whether it should be enabled
* for that message.
*
* @param content The message that is about to be displayed.
* @param isRequest Indicates whether the message is a request or a
* response.
* @return The method should return
* <code>true</code> if the custom tab is able to handle the specified
* message, and so will be displayed within the editor. Otherwise, the tab
* will be hidden while this message is displayed.
*/
boolean isEnabled(byte[] content, boolean isRequest);
/**
* The hosting editor will invoke this method to display a new message or to
* clear the existing message. This method will only be called with a new
* message if the tab has already returned
* <code>true</code> to a call to
* <code>isEnabled()</code> with the same message details.
*
* @param content The message that is to be displayed, or
* <code>null</code> if the tab should clear its contents and disable any
* editable controls.
* @param isRequest Indicates whether the message is a request or a
* response.
*/
void setMessage(byte[] content, boolean isRequest);
/**
* This method returns the currently displayed message.
*
* @return The currently displayed message.
*/
byte[] getMessage();
/**
* This method is used to determine whether the currently displayed message
* has been modified by the user. The hosting editor will always call
* <code>getMessage()</code> before calling this method, so any pending
* edits should be completed within
* <code>getMessage()</code>.
*
* @return The method should return
* <code>true</code> if the user has modified the current message since it
* was first displayed.
*/
boolean isModified();
/**
* This method is used to retrieve the data that is currently selected by
* the user.
*
* @return The data that is currently selected by the user. This may be
* <code>null</code> if no selection is currently made.
*/
byte[] getSelectedData();
}
| 1,940 |
0 |
Create_ds/msl/examples/simple/src/main/java
|
Create_ds/msl/examples/simple/src/main/java/server/SimpleConstants.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 server;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
/**
* <p>Server constants.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleConstants {
/** Default server port. */
public static final int DEFAULT_PORT = 8080;
/** MSL control timeout in milliseconds. */
public static final int TIMEOUT_MS = 120 * 1000;
/** Server entity ID. */
public static final String SERVER_ID = "SimpleMslServer";
/** Server 2048-bit RSA public key. */
public static final String RSA_PUBKEY_B64 =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4feorj/FWQi8AhbvjK3G" +
"L31ct6N+Ad/3FwqNsa4vAsfPmilLRx0DWhkxRycetmQEAa+1THyNCzobIduQE3UY" +
"8NtdOiy1S3BtHDoiSNEITFPAs0l2OAZ2ZUv0KIr9sLWAznlXMclLOBXtLOQMCs2e" +
"Ey4MO1m9uLywwc2SuAfoZe+wjEIauyoQK/M5miA0fbaEn4H+3m5aiP3Lb1X5Ss4b" +
"4tuu0ENsO/ebgMx2ltZ4b9dkzA65DM6XxEC60jK1AW+/wvFb4+iPQqrA7mdiZWsp" +
"zqMRTaAUDHKJo2LFBc6N0/wuTsXczHx6TYz5b2hrI6N+O7EEuxirAaU+xU7XEqv2" +
"dQIDAQAB";
/** Server 2048-bit RSA private key. */
public static final String RSA_PRIVKEY_B64 =
"MIIEowIBAAKCAQEA4feorj/FWQi8AhbvjK3GL31ct6N+Ad/3FwqNsa4vAsfPmilL" +
"Rx0DWhkxRycetmQEAa+1THyNCzobIduQE3UY8NtdOiy1S3BtHDoiSNEITFPAs0l2" +
"OAZ2ZUv0KIr9sLWAznlXMclLOBXtLOQMCs2eEy4MO1m9uLywwc2SuAfoZe+wjEIa" +
"uyoQK/M5miA0fbaEn4H+3m5aiP3Lb1X5Ss4b4tuu0ENsO/ebgMx2ltZ4b9dkzA65" +
"DM6XxEC60jK1AW+/wvFb4+iPQqrA7mdiZWspzqMRTaAUDHKJo2LFBc6N0/wuTsXc" +
"zHx6TYz5b2hrI6N+O7EEuxirAaU+xU7XEqv2dQIDAQABAoIBAQCh/pEv8knBbXCT" +
"Muwi90VYMFAy2oNwRqZ2Hzu7gHr1TFd5VldAMP2BLwRT1SjAau0wZE3d+oCG5u4i" +
"lKwyNsVdjnXESd7iqUOfc9G2UBzZ00UXgve8bG2eaxgrpJEAiO5Bl126NGu3VojE" +
"oOw9JnFHoMBmIAzSDnvNRFoFkq25vQYAG45l9ZeNJv8mJaJG5+DNr6xbAE5PmROc" +
"qyDL7RrfSqLxALhgZzLjVAP99fBGpOw2dCGKbQRzkUY0bojO19G3UUtf3HCI005i" +
"kYHuAPdvu4+AteOvKdnDeMcT1pDxiNZKO+kXumIGYaKul2k6t9UpsRvCSmrthFZx" +
"t8izGEehAoGBAPJ7YiK6W6NrgVyW5PaDtDRTrwZb/1G/K+jvCzHhV8/X5KfmjsaA" +
"kT5m2WS1/rMwJoyc45GmTyyy6reGqLs5zAdUVicRKjZZaQnj00QXHRlmAEiDtx2T" +
"b0cagryVf79Ma5FgyOMmqHjS5Pob7RvI4UyzVhR/pYmOrqxWGZgmRlxNAoGBAO6Q" +
"lfXvbL9JKZ3HXIVbrXS5QToACnQf19QH05LPJG4jni7ycoTZFOiFmJodP5ca+Gug" +
"TLlPaeVu52dlbXM1k32tV+0ui6vn0ErE8ZsXTjbZ/KInx4munWrLP8w3Ju8MHPPl" +
"sEgmeggL0xBtt5BFRKus0SWwImZ9rIzxFXdbanbJAoGAOrP4LCQlr0iFht7ZC30T" +
"EV/5DXcUNrwrazcD5M2DLsQ7jRJaGmBhyVOo6aLNyJ+tlXkd9tLmdBHUlR26l6kE" +
"Zfna6ZZUO9glf8lyChf2aYGyK9wHZtecpwAaCoG+7ZcYq5dcyvE+9BFKcep02rcl" +
"JCZ+fnPwpX6vdvVZOOZ7PjkCgYAGMv2imWkjA1ywe+i8kmhMey/luPCMmfM60EVA" +
"MF/K+OP4ZlZxe06eyDHx90aav5mq+kxkGFsxGhOrTSht8Pt3LZT2VdpNSkXQW5PH" +
"qvBeXoXBFPWLb10p1ERBI0HAvnjWIabWCSHsqZn/eEpn1lT1fRUmPJB4R1W/h9g9" +
"9MMseQKBgBVp+6dU2Rdf1jzwzDH3IRDIVgWeqLlQucbVr/Fipjooioq6nxH2oHUB" +
"2Qmq7FjYLKfKdaIRRoJhgeUhjVOVdjyIKVhLlBYpztr48jrMD5e4ykvKdAV2tlNv" +
"B/b+6sSJkqh7Qm6CMO29m+dE2PJBZCzviTkBMOzyme71phGsh//C";
/** Email/Password set. */
public static final String[][] EMAIL_PASSWORDS = {
{ "kirito", "asuna" },
{ "chie", "shuhei" },
{ "hideki", "chi" },
};
/** Server administrator. */
public static final String ADMIN_USERNAME = "kirito";
/** User profiles. */
public static final Map<String,JSONObject> PROFILES = new HashMap<String,JSONObject>();
static {
final String KEY_NAME = "name";
final String KEY_SEX = "sex";
final String KEY_AGE = "age";
final String KEY_EYES = "eyes";
final String KEY_HAIR = "hair";
final String KEY_HEIGHT = "height";
final String KEY_WEIGHT = "weight";
final JSONObject kirito = new JSONObject();
kirito.put(KEY_NAME, "Kazuto Kirigaya");
kirito.put(KEY_SEX, "male");
kirito.put(KEY_AGE, 14);
kirito.put(KEY_EYES, "brown");
kirito.put(KEY_HAIR, "black");
kirito.put(KEY_HEIGHT, 172);
kirito.put(KEY_WEIGHT, 59);
PROFILES.put("kirito", kirito);
final JSONObject chie = new JSONObject();
chie.put(KEY_NAME, "Chie Karita");
chie.put(KEY_SEX, "female");
chie.put(KEY_EYES, "brown");
chie.put(KEY_HAIR, "brown");
PROFILES.put("chie", chie);
final JSONObject hideki = new JSONObject();
hideki.put(KEY_NAME, "Hideki Motosuwa");
hideki.put(KEY_SEX, "male");
hideki.put(KEY_AGE, 19);
hideki.put(KEY_EYES, "brown");
hideki.put(KEY_HAIR, "black");
PROFILES.put("hideki", hideki);
}
/**
* Query data: user, key, value.
*
* If the first value is not null, only the listed user has permission to
* access the data value.
*/
public static final String[][] QUERY_DATA = {
{ null, "cat", "neko" },
{ "chie", "alien", "uchujin" },
{ "kirito", "sword", "tsurugi" },
{ null, "dog", "inu" },
{ null, "bird", "tori" },
{ null, "turtle", "kame" },
{ null, "fish", "sakana" },
{ "chie", "bathhouse", "notenburo" },
{ "hideki", "computer", "persocom" },
};
}
| 1,941 |
0 |
Create_ds/msl/examples/simple/src/main/java
|
Create_ds/msl/examples/simple/src/main/java/server/SimpleServlet.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 server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.json.JSONObject;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.SymmetricCryptoContext;
import com.netflix.msl.entityauth.RsaStore;
import com.netflix.msl.msg.ConsoleFilterStreamFactory;
import com.netflix.msl.msg.ErrorHeader;
import com.netflix.msl.msg.MessageContext;
import com.netflix.msl.msg.MessageInputStream;
import com.netflix.msl.msg.MslControl;
import com.netflix.msl.msg.MslControl.MslChannel;
import com.netflix.msl.userauth.EmailPasswordStore;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
import server.entityauth.SimpleRsaStore;
import server.msg.SimpleReceiveMessageContext;
import server.msg.SimpleRequest;
import server.msg.SimpleRespondMessageContext;
import server.userauth.SimpleEmailPasswordStore;
import server.userauth.SimpleUser;
import server.util.SimpleMslContext;
/**
* <p>An example Java MSL servlet that listens for requests from the example
* JavaScript MSL client. Once any authorized client issues a quit operation,
* this servlet will no longer process additional requests and will instead
* return HTTP status code {@code 401}. The server must be restarted to re-
* enable the servlet.</p>
*
* <p>This class is thread-safe.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = -4593207843035538485L;
/** Line separator. */
private static final String NEWLINE = System.lineSeparator();
/** Service token key set ID. */
private static final String ST_KEYSET_ID = "serviceTokenKeySetId";
/** Service token encryption key. */
private static final byte[] ST_ENCRYPTION_KEY = new byte[] {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
};
/** Service token HMAC key. */
private static final byte[] ST_HMAC_KEY = new byte[] {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
};
/** "Quit" state. */
private static boolean QUIT = false;
// Add BouncyCastle provider.
static {
Security.addProvider(new BouncyCastleProvider());
}
/**
* <p>Create a new servlet instance and initialize its static, immutable
* state.</p>
*/
public SimpleServlet() {
// Create the RSA key store.
final RsaStore rsaStore;
try {
final byte[] privKeyEncoded = Base64.decode(SimpleConstants.RSA_PRIVKEY_B64);
final PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyEncoded);
final KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");
final PrivateKey privKey = rsaKeyFactory.generatePrivate(privKeySpec);
rsaStore = new SimpleRsaStore(SimpleConstants.SERVER_ID, null, privKey);
} catch (final NoSuchAlgorithmException e) {
throw new RuntimeException("RSA algorithm not found.", e);
} catch (final InvalidKeySpecException e) {
throw new RuntimeException("Invalid RSA private key.", e);
}
// Create the email/password store.
final Map<String,String> emailPasswords = new HashMap<String,String>();
for (final String[] emailPassword : SimpleConstants.EMAIL_PASSWORDS)
emailPasswords.put(emailPassword[0], emailPassword[1]);
final EmailPasswordStore emailPasswordStore = new SimpleEmailPasswordStore(emailPasswords);
// Set up the MSL context.
this.ctx = new SimpleMslContext(SimpleConstants.SERVER_ID, rsaStore, emailPasswordStore);
// Create the MSL control.
//
// Since this is an example process all requests on the calling thread.
this.ctrl = new MslControl(0);
ctrl.setFilterFactory(new ConsoleFilterStreamFactory());
// Use one crypto context for all service tokens.
final SecretKey encryptionKey = new SecretKeySpec(ST_ENCRYPTION_KEY, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(ST_HMAC_KEY, JcaAlgorithm.HMAC_SHA256);
final ICryptoContext stCryptoContext = new SymmetricCryptoContext(this.ctx, ST_KEYSET_ID, encryptionKey, hmacKey, null);
cryptoContexts.put("", stCryptoContext);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
// Allow requests from anywhere.
resp.setHeader("Access-Control-Allow-Origin", "*");
// If "quit" then return HTTP status code 401.
if (QUIT) {
System.out.println("Returning 401.");
resp.sendError(HttpServletResponse.SC_GONE, "MSL servlet terminated.");
return;
}
// Set up the receive MSL message context.
final MessageContext rcvMsgCtx = new SimpleReceiveMessageContext(cryptoContexts);
// Receive a request.
final InputStream in = req.getInputStream();
final OutputStream out = resp.getOutputStream();
final MessageInputStream request;
final Future<MessageInputStream> requestFuture = ctrl.receive(ctx, rcvMsgCtx, in, out, SimpleConstants.TIMEOUT_MS);
try {
request = requestFuture.get();
if (request == null)
return;
} catch (final ExecutionException e) {
e.printStackTrace(System.err);
return;
} catch (final InterruptedException e) {
System.err.println("MslControl.receive() interrupted.");
return;
}
// We should not receive error headers but check just in case.
final ErrorHeader error = request.getErrorHeader();
if (error != null) {
System.err.println("Unexpectedly received error message: [" + error.getErrorCode() + "][" + error.getInternalCode() + "][" + error.getErrorMessage() + "]");
return;
}
// Process request.
final SimpleRequest simpleRequest;
SimpleRespondMessageContext responseMsgCtx;
try {
// Parse request.
final String identity = request.getIdentity();
final SimpleUser user = (SimpleUser)request.getUser();
simpleRequest = SimpleRequest.parse(identity, user, request, cryptoContexts);
// Output the request.
final String requestJson = simpleRequest.toJSONString();
final JSONObject requestJo = new JSONObject(requestJson);
System.out.println(NEWLINE + "REQUEST" + NEWLINE +
"======" + NEWLINE +
requestJo.toString(4) + NEWLINE +
"======");
// Execute.
responseMsgCtx = simpleRequest.execute();
// If the request type was quit then remember it.
if (SimpleRequest.Type.QUIT.equals(simpleRequest.getType()))
QUIT = true;
} catch (final Exception e) {
e.printStackTrace(System.err);
// FIXME: Remove encryption requirement.
// Encryption is required to avoid accidentally leaking
// information in the error message.
responseMsgCtx = new SimpleRespondMessageContext(true, e.getMessage());
}
// Send response. We don't need the MslChannel because we are not
// opening a persistent channel.
final Future<MslChannel> channelFuture = ctrl.respond(ctx, responseMsgCtx, in, out, request, SimpleConstants.TIMEOUT_MS);
try {
channelFuture.get();
} catch (final ExecutionException e) {
e.printStackTrace(System.err);
return;
} catch (final InterruptedException e) {
System.err.println("MslControl.receive() interrupted.");
return;
}
// Output the response.
System.out.println(NEWLINE + "RESPONSE" + NEWLINE +
"========" + NEWLINE +
responseMsgCtx.getData() + NEWLINE +
"========");
}
/** MSL context. */
private final MslContext ctx;
/** MSL control. */
private final MslControl ctrl;
/** Service token crypto contexts. */
private final Map<String,ICryptoContext> cryptoContexts = new HashMap<String,ICryptoContext>();
}
| 1,942 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/util/SimpleMslContext.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 server.util;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import server.userauth.SimpleTokenFactory;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.SymmetricCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.entityauth.RsaAuthenticationData;
import com.netflix.msl.entityauth.RsaAuthenticationFactory;
import com.netflix.msl.entityauth.RsaStore;
import com.netflix.msl.entityauth.UnauthenticatedAuthenticationFactory;
import com.netflix.msl.io.DefaultMslEncoderFactory;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.keyx.AsymmetricWrappedExchange;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.msg.MessageCapabilities;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.userauth.EmailPasswordAuthenticationFactory;
import com.netflix.msl.userauth.EmailPasswordStore;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslStore;
import com.netflix.msl.util.NullMslStore;
/**
* <p>The example server MSL context.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleMslContext extends MslContext {
/** MSL encryption key. */
private static final byte[] MSL_ENCRYPTION_KEY = {
(byte)0x1d, (byte)0x58, (byte)0xf3, (byte)0xb8, (byte)0xf7, (byte)0x47, (byte)0xd1, (byte)0x6a,
(byte)0xb1, (byte)0x93, (byte)0xc4, (byte)0xc0, (byte)0xa6, (byte)0x24, (byte)0xea, (byte)0xcf,
};
/** MSL HMAC key. */
private static final byte[] MSL_HMAC_KEY = {
(byte)0xd7, (byte)0xae, (byte)0xbf, (byte)0xd5, (byte)0x87, (byte)0x9b, (byte)0xb0, (byte)0xe0,
(byte)0xad, (byte)0x01, (byte)0x6a, (byte)0x4c, (byte)0xf3, (byte)0xcb, (byte)0x39, (byte)0x82,
(byte)0xf5, (byte)0xba, (byte)0x26, (byte)0x0d, (byte)0xa5, (byte)0x20, (byte)0x24, (byte)0x5b,
(byte)0xb4, (byte)0x22, (byte)0x75, (byte)0xbd, (byte)0x79, (byte)0x47, (byte)0x37, (byte)0x0c,
};
/** MSL wrapping key. */
private static final byte[] MSL_WRAPPING_KEY = {
(byte)0x83, (byte)0xb6, (byte)0x9a, (byte)0x15, (byte)0x80, (byte)0xd3, (byte)0x23, (byte)0xa2,
(byte)0xe7, (byte)0x9d, (byte)0xd9, (byte)0xb2, (byte)0x26, (byte)0x26, (byte)0xb3, (byte)0xf6,
};
/**
* Key exchange factory comparator.
*/
private static class KeyExchangeFactoryComparator implements Comparator<KeyExchangeFactory> {
/** Scheme priorities. Lower values are higher priority. */
private final Map<KeyExchangeScheme,Integer> schemePriorities = new HashMap<KeyExchangeScheme,Integer>();
/**
* Create a new key exchange factory comparator.
*/
public KeyExchangeFactoryComparator() {
schemePriorities.put(KeyExchangeScheme.JWK_LADDER, 0);
schemePriorities.put(KeyExchangeScheme.JWE_LADDER, 1);
schemePriorities.put(KeyExchangeScheme.DIFFIE_HELLMAN, 2);
schemePriorities.put(KeyExchangeScheme.SYMMETRIC_WRAPPED, 3);
schemePriorities.put(KeyExchangeScheme.ASYMMETRIC_WRAPPED, 4);
}
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(final KeyExchangeFactory a, final KeyExchangeFactory b) {
final KeyExchangeScheme schemeA = a.getScheme();
final KeyExchangeScheme schemeB = b.getScheme();
final Integer priorityA = schemePriorities.get(schemeA);
final Integer priorityB = schemePriorities.get(schemeB);
return priorityA.compareTo(priorityB);
}
}
/**
* <p>Create a new simple MSL context.</p>
*
* @param serverId local server entity identity.
* @param rsaStore local server entity RSA store.
* @param emailPasswords user email/password store.
*/
public SimpleMslContext(final String serverId, final RsaStore rsaStore, final EmailPasswordStore emailPasswordStore) {
// Message capabilities.
final Set<CompressionAlgorithm> compressionAlgos = new HashSet<CompressionAlgorithm>(Arrays.asList(CompressionAlgorithm.GZIP, CompressionAlgorithm.LZW));
final List<String> languages = Arrays.asList("en-US");
final Set<MslEncoderFormat> encoderFormats = new HashSet<MslEncoderFormat>(Arrays.asList(MslEncoderFormat.JSON));
this.messageCaps = new MessageCapabilities(compressionAlgos, languages, encoderFormats);
// MSL crypto context.
final SecretKey encryptionKey = new SecretKeySpec(MSL_ENCRYPTION_KEY, "AES");
final SecretKey hmacKey = new SecretKeySpec(MSL_HMAC_KEY, "HmacSHA256");
final SecretKey wrappingKey = new SecretKeySpec(MSL_WRAPPING_KEY, "AES");
this.mslCryptoContext = new SymmetricCryptoContext(this, serverId, encryptionKey, hmacKey, wrappingKey);
// Create authentication utils.
final AuthenticationUtils authutils = new SimpleAuthenticationUtils(serverId);
// Entity authentication.
//
// Use the local entity identity for the key pair ID.
this.entityAuthData = new RsaAuthenticationData(serverId, serverId);
// Entity authentication factories.
this.entityAuthFactories = new HashSet<EntityAuthenticationFactory>();
this.entityAuthFactories.add(new RsaAuthenticationFactory(serverId, rsaStore, authutils));
this.entityAuthFactories.add(new UnauthenticatedAuthenticationFactory(authutils));
// User authentication factories.
this.userAuthFactory = new EmailPasswordAuthenticationFactory(emailPasswordStore, authutils);
// Key exchange factories.
this.keyxFactories = new TreeSet<KeyExchangeFactory>(new KeyExchangeFactoryComparator());
this.keyxFactories.add(new AsymmetricWrappedExchange(authutils));
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getTime()
*/
@Override
public long getTime() {
return System.currentTimeMillis();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getRandom()
*/
@Override
public Random getRandom() {
return new SecureRandom();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#isPeerToPeer()
*/
@Override
public boolean isPeerToPeer() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMessageCapabilities()
*/
@Override
public MessageCapabilities getMessageCapabilities() {
return messageCaps;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getEntityAuthenticationData(com.netflix.msl.util.MslContext.ReauthCode)
*/
@Override
public EntityAuthenticationData getEntityAuthenticationData(final ReauthCode reauthCode) {
return entityAuthData;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslCryptoContext()
*/
@Override
public ICryptoContext getMslCryptoContext() throws MslCryptoException {
return mslCryptoContext;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#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) {
for (final EntityAuthenticationFactory factory : entityAuthFactories) {
if (factory.getScheme().equals(scheme))
return factory;
}
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) {
if (userAuthFactory.getScheme().equals(scheme))
return userAuthFactory;
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getTokenFactory()
*/
@Override
public TokenFactory getTokenFactory() {
return tokenFactory;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getKeyExchangeScheme(java.lang.String)
*/
@Override
public KeyExchangeScheme getKeyExchangeScheme(final String name) {
return KeyExchangeScheme.getScheme(name);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getKeyExchangeFactory(com.netflix.msl.keyx.KeyExchangeScheme)
*/
@Override
public KeyExchangeFactory getKeyExchangeFactory(final KeyExchangeScheme scheme) {
for (final KeyExchangeFactory factory : keyxFactories) {
if (factory.getScheme().equals(scheme))
return factory;
}
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getKeyExchangeFactories()
*/
@Override
public SortedSet<KeyExchangeFactory> getKeyExchangeFactories() {
return keyxFactories;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslStore()
*/
@Override
public MslStore getMslStore() {
return store;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslEncoderFactory()
*/
@Override
public MslEncoderFactory getMslEncoderFactory() {
return encoderFactory;
}
private final MessageCapabilities messageCaps;
private final EntityAuthenticationData entityAuthData;
private final ICryptoContext mslCryptoContext;
private final Set<EntityAuthenticationFactory> entityAuthFactories;
private final UserAuthenticationFactory userAuthFactory;
private final TokenFactory tokenFactory = new SimpleTokenFactory();
private final SortedSet<KeyExchangeFactory> keyxFactories;
private final MslStore store = new NullMslStore();
private final MslEncoderFactory encoderFactory = new DefaultMslEncoderFactory();;
}
| 1,943 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/util/SimpleAuthenticationUtils.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 server.util;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.AuthenticationUtils;
/**
* <p>Restrict clients to unauthenticated entity authentication and the local
* server to RSA entity authentication. Restrict key exchange to asymmetric
* wrapped key exchange.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleAuthenticationUtils implements AuthenticationUtils {
/**
* <p>Create a new authentication utils instance for the specified server
* identity.</p>
*
* @param serverId local server entity identity.
*/
public SimpleAuthenticationUtils(final String serverId) {
this.serverId = serverId;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isEntityRevoked(java.lang.String)
*/
@Override
public boolean isEntityRevoked(final String identity) {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.entityauth.EntityAuthenticationScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final EntityAuthenticationScheme scheme) {
return (serverId.equals(identity) && EntityAuthenticationScheme.RSA.equals(scheme)) ||
EntityAuthenticationScheme.NONE.equals(scheme);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.userauth.UserAuthenticationScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final UserAuthenticationScheme scheme) {
return (!serverId.equals(identity) && UserAuthenticationScheme.EMAIL_PASSWORD.equals(scheme));
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.tokens.MslUser, com.netflix.msl.userauth.UserAuthenticationScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final MslUser user, final UserAuthenticationScheme scheme) {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.keyx.KeyExchangeScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final KeyExchangeScheme scheme) {
return KeyExchangeScheme.ASYMMETRIC_WRAPPED.equals(scheme);
}
/** Local server entity identity. */
private final String serverId;
}
| 1,944 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleQueryRequest.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 server.msg;
import org.json.JSONException;
import org.json.JSONObject;
import server.SimpleConstants;
import server.userauth.SimpleUser;
/**
* <p>Query for a data value. Some data values require a user identity for
* access.</p>
*
* <p>The request data object is defined as:
* {@code
* data = {
* "#mandatory" : [ "key" ],
* "key" : "string"
* }} where:
* <ul>
* <li>{@code key} is the data key identifying the value.</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleQueryRequest extends SimpleRequest {
/** JSON key key. */
private static final String KEY_KEY = "key";
/**
* <p>Create a new query request.</p>
*
* @param identity requesting entity identity.
* @param user requesting user. May be null.
* @param data the request data.
* @throws SimpleRequestParseException if there is an error parsing the
* request data.
*/
public SimpleQueryRequest(final String identity, final SimpleUser user, final JSONObject data) throws SimpleRequestParseException {
super(Type.QUERY, identity, user);
try {
key = data.getString(KEY_KEY);
} catch (final JSONException e) {
throw new SimpleRequestParseException("Error parsing query request: " + data.toString() + ".", e);
}
}
/**
* @return the data key.
*/
public String getKey() {
return key;
}
/* (non-Javadoc)
* @see server.msg.SimpleRequest#getData()
*/
@Override
public JSONObject getData() {
final JSONObject jo = new JSONObject();
jo.put(KEY_KEY, key);
return jo;
}
/* (non-Javadoc)
* @see server.msg.SimpleRequest#execute()
*/
@Override
public SimpleRespondMessageContext execute() throws SimpleRequestUserException, SimpleRequestExecutionException {
// Pull requesting user.
final SimpleUser user = getUser();
final String username = (user != null) ? user.toString() : null;
// Identify the requested data.
for (final String[] data : SimpleConstants.QUERY_DATA) {
if (data[1].equals(key)) {
final String response;
if (data[0] != null && !data[0].equals(username))
throw new SimpleRequestUserException("Error: access restricted to user " + data[0] + ".");
else
response = data[2];
return new SimpleRespondMessageContext(true, response);
}
}
// Data key not found.
throw new SimpleRequestExecutionException("Error: no data found for key " + key + ".");
}
/** Data key. */
private final String key;
}
| 1,945 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleProfileRequest.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 server.msg;
import org.json.JSONObject;
import server.SimpleConstants;
import server.userauth.SimpleUser;
/**
* <p>Request to return a user profile.</p>
*
* <p>The request data object is defined as an empty JSON object.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleProfileRequest extends SimpleRequest {
/**
* <p>Create a new user profile request.</p>
*
* @param identity requesting entity identity.
* @param user requesting user.
* @param data the request data.
* @throws SimpleRequestUserException if the user is null.
*/
public SimpleProfileRequest(final String identity, final SimpleUser user, final JSONObject data) throws SimpleRequestUserException {
super(Type.USER_PROFILE, identity, user);
if (user == null)
throw new SimpleRequestUserException("A user is required for the user profile request.");
}
/* (non-Javadoc)
* @see server.msg.SimpleRequest#getData()
*/
@Override
public JSONObject getData() {
return new JSONObject();
}
@Override
public SimpleRespondMessageContext execute() {
final String response;
// The request must come from a user.
final SimpleUser user = getUser();
if (user == null) {
response = "Error: log in to access your user profile.";
}
// Grab the profile.
else {
final String username = user.toString();
final JSONObject profile = SimpleConstants.PROFILES.get(username);
if (profile == null) {
response = "Error: no profile found for " + username + ".";
} else {
response = profile.toString(4);
}
}
// Return the response.
return new SimpleRespondMessageContext(true, response);
}
}
| 1,946 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleRequestExecutionException.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*/
package server.msg;
/**
* <p>Thrown if an error occurs while executing a request.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleRequestExecutionException extends Exception {
private static final long serialVersionUID = 1415595607318787406L;
/**
* @param message the exception message.
*/
public SimpleRequestExecutionException(final String message) {
super(message);
}
/**
* @param message the exception message.
* @param cause the exception cause.
*/
public SimpleRequestExecutionException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 1,947 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleRespondMessageContext.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 server.msg;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
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.MslException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.msg.MessageContext;
import com.netflix.msl.msg.MessageDebugContext;
import com.netflix.msl.msg.MessageOutputStream;
import com.netflix.msl.msg.MessageServiceTokenBuilder;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* <p>Example server message context for sending response messages.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleRespondMessageContext implements MessageContext {
/**
* <p>Service token container.</p>
*/
public static class Token {
/**
* <p>Define a new service token for inclusion in the response message.
* If the service token should be entity- or user-bound but cannot be,
* the maximum binding possible is used but the service token is
* included in the response.</p>
*
* @param name service token name.
* @param data service token application data.
* @param entityBound true if the service token should be entity-bound.
* @param userBound true if the service token should be user-bound.
*/
public Token(final String name, final String data, final boolean entityBound, final boolean userBound) {
this.name = name;
this.data = data;
this.entityBound = entityBound;
this.userBound = userBound;
}
/** Service token name. */
public final String name;
/** Service token application data. */
public final String data;
/** Service token should be entity-bound. */
public final boolean entityBound;
/** Service token should be user-bound. */
public final boolean userBound;
}
/**
* <p>Create a new response message context with the specified
* properties.</p>
*
* @param encrypted true if the response data must be encrypted.
* @param data application response data.
*/
public SimpleRespondMessageContext(final boolean encrypted, final String data) {
this.encrypted = encrypted;
this.data = data;
this.tokens = Collections.emptySet();
this.cryptoContexts = Collections.emptyMap();
}
/**
* <p>Create a new response message context with the specified
* properties.</p>
*
* @param encrypted true if the response data must be encrypted.
* @param data application response data.
* @param tokens application service tokens.
* @param cryptoContexts application service token crypto contexts.
*/
public SimpleRespondMessageContext(final boolean encrypted, final String data, final Set<Token> tokens, final Map<String,ICryptoContext> cryptoContexts) {
this.encrypted = encrypted;
this.data = data;
this.tokens = tokens;
this.cryptoContexts = Collections.unmodifiableMap(cryptoContexts);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getCryptoContexts()
*/
@Override
public Map<String, ICryptoContext> getCryptoContexts() {
return cryptoContexts;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getRemoteEntityIdentity()
*/
@Override
public String getRemoteEntityIdentity() {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return encrypted;
}
/* (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;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isRequestingTokens()
*/
@Override
public boolean isRequestingTokens() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUserId()
*/
@Override
public String getUserId() {
return null;
}
/* (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 null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUser()
*/
@Override
public MslUser getUser() {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getKeyRequestData()
*/
@Override
public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException {
return null;
}
/* (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 MslEncodingException, MslCryptoException, MslException {
if (handshake)
return;
for (final Token token : tokens) {
final String name = token.name;
final byte[] data = token.data.getBytes(MslConstants.DEFAULT_CHARSET);
if (token.userBound && builder.isPrimaryUserIdTokenAvailable())
builder.addUserBoundPrimaryServiceToken(name, data, true, CompressionAlgorithm.GZIP);
else if (token.entityBound && builder.isPrimaryMasterTokenAvailable())
builder.addMasterBoundPrimaryServiceToken(name, data, true, CompressionAlgorithm.GZIP);
else
builder.addUnboundPrimaryServiceToken(name, data, true, CompressionAlgorithm.GZIP);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#write(com.netflix.msl.msg.MessageOutputStream)
*/
@Override
public void write(final MessageOutputStream output) throws IOException {
output.write(data.getBytes(MslConstants.DEFAULT_CHARSET));
output.close();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getDebugContext()
*/
@Override
public MessageDebugContext getDebugContext() {
return null;
}
/**
* @return the application response data.
*/
public String getData() {
return data;
}
/** Service token crypto contexts. */
private final Map<String,ICryptoContext> cryptoContexts;
/** True if the response data must be encrypted. */
private final boolean encrypted;
/** Response data. */
private final String data;
/** Service tokens. */
private final Set<Token> tokens;
}
| 1,948 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleRequestParseException.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 server.msg;
/**
* <p>Thrown if there is an error parsing the simple request.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleRequestParseException extends Exception {
private static final long serialVersionUID = -1012872190734096705L;
/**
* @param message the exception message.
*/
public SimpleRequestParseException(final String message) {
super(message);
}
/**
* @param message the exception message.
* @param cause the exception cause.
*/
public SimpleRequestParseException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 1,949 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleLogRequest.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 server.msg;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import com.netflix.msl.MslConstants;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.tokens.ServiceToken;
import server.msg.SimpleRespondMessageContext.Token;
import server.userauth.SimpleUser;
/**
* <p>Request to log a message.</p>
*
* <p>The request data object is defined as:
* {@code
* data = {
* "#mandatory" : [ "timestamp", "severity", "message" ],
* "timestamp" : "number",
* "severity" : enum(ERROR|WARN|INFO),
* "message" : "string",
* }} where:
* <ul>
* <li>{@code timestamp} is the log message time in seconds since the UNIX epoch.</li>
* <li>{@code severity} is the log message severity.</li>
* <li>{@code message} is the log message text.</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleLogRequest extends SimpleRequest {
/** JSON key timestamp. */
private static final String KEY_TIMESTAMP = "timestamp";
/** JSON key severity. */
private static final String KEY_SEVERITY = "severity";
/** JSON key message. */
private static final String KEY_MESSAGE = "message";
/** Log message severity. */
public enum Severity {
ERROR,
WARN,
INFO
}
/** Log data service token name. */
public static final String SERVICETOKEN_LOGDATA_NAME = "server.logdata";
/**
* <p>Create a new log request.</p>
*
* @param identity requesting entity identity.
* @param user requesting user. May be null.
* @param data the request data object.
* @param tokens service tokens.
* @param cryptoContext service token crypto contexts.
* @throws SimpleRequestParseException if there is an error parsing the
* request data.
*/
public SimpleLogRequest(final String identity, final SimpleUser user, final JSONObject data, final Set<ServiceToken> tokens, final Map<String,ICryptoContext> cryptoContexts) throws SimpleRequestParseException {
super(Type.LOG, identity, user);
final String severityString;
try {
timestamp = data.getLong(KEY_TIMESTAMP);
severityString = data.getString(KEY_SEVERITY);
message = data.getString(KEY_MESSAGE);
} catch (final JSONException e) {
throw new SimpleRequestParseException("Error parsing log request.", e);
}
try {
severity = Severity.valueOf(severityString);
} catch (final IllegalArgumentException e) {
throw new SimpleRequestParseException("Unknown severity " + severityString + ".", e);
}
String logdata = null;
for (final ServiceToken token : tokens) {
if (!token.isDecrypted())
continue;
if (SERVICETOKEN_LOGDATA_NAME.equals(token.getName())) {
logdata = new String(token.getData(), MslConstants.DEFAULT_CHARSET);
break;
}
}
this.logdata = logdata;
this.cryptoContexts = Collections.unmodifiableMap(cryptoContexts);
}
/**
* <p>Returns the log message timestamp in seconds since the UNIX epoch.</p>
*
* @return the log message timestamp.
*/
public long getTimestamp() {
return timestamp;
}
/**
* @return the log message severity.
*/
public Severity getSeverity() {
return severity;
}
/**
* @return the log message.
*/
public String getMessage() {
return message;
}
/* (non-Javadoc)
* @see server.msg.SimpleRequest#getData()
*/
@Override
public JSONObject getData() {
final JSONObject jo = new JSONObject();
jo.put(KEY_TIMESTAMP, timestamp);
jo.put(KEY_SEVERITY, severity.name());
jo.put(KEY_MESSAGE, message);
return jo;
}
/* (non-Javadoc)
* @see server.msg.SimpleRequest#execute()
*/
@Override
public SimpleRespondMessageContext execute() {
final String newMessage = "Log " + getUser() + "@" + getIdentity() + ": " +
new Date(timestamp) + " [" + severity.name() + "] " + message;
final String allMessages = (logdata != null)
? logdata + System.lineSeparator() + newMessage
: newMessage;
System.out.println(newMessage);
final Set<Token> tokens = new HashSet<Token>();
tokens.add(new Token(SERVICETOKEN_LOGDATA_NAME, allMessages, true, true));
return new SimpleRespondMessageContext(false, allMessages, tokens, cryptoContexts);
}
/** Timestamp in seconds since the UNIX epoch. */
private final long timestamp;
/** Severity. */
private final Severity severity;
/** Message. */
private final String message;
/** Previous log data. */
private final String logdata;
/** Service token crypto contexts. */
private final Map<String,ICryptoContext> cryptoContexts;
}
| 1,950 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleRequestUnknownException.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 server.msg;
/**
* <p>Thrown if the simple request type cannot be determined.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleRequestUnknownException extends Exception {
private static final long serialVersionUID = -4265148562867961991L;
/**
* @param message the exception message.
*/
public SimpleRequestUnknownException(final String message) {
super(message);
}
/**
* @param message the exception message.
* @param cause the exception cause.
*/
public SimpleRequestUnknownException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 1,951 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleRequestUserException.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 server.msg;
/**
* <p>Thrown if the simple request requires a user or requires different
* user.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleRequestUserException extends Exception {
private static final long serialVersionUID = 2954307349351180684L;
/**
* @param message the exception message.
*/
public SimpleRequestUserException(final String message) {
super(message);
}
/**
* @param message the exception message.
* @param cause the exception cause.
*/
public SimpleRequestUserException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 1,952 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleEchoRequest.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 server.msg;
import org.json.JSONException;
import org.json.JSONObject;
import server.userauth.SimpleUser;
/**
* <p>Request to echo the request message. The requesting entity identity and
* user (if any) is also echoed.</p>
*
* <p>The request data object is defined as:
* {@code
* data = {
* "#mandatory" : [ "message" ],
* "message" : "string"
* }} where:
* <ul>
* <li>{@code message} is the message to echo.</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleEchoRequest extends SimpleRequest {
/** JSON key message. */
private static final String KEY_MESSAGE = "message";
/**
* <p>Create a new echo request.</p>
*
* @param identity requesting entity identity.
* @param user requesting user. May be null.
* @param data the request data object.
* @throws SimpleRequestParseException if there is an error parsing the
* request data.
*/
public SimpleEchoRequest(final String identity, final SimpleUser user, final JSONObject data) throws SimpleRequestParseException {
super(Type.ECHO, identity, user);
try {
message = data.getString(KEY_MESSAGE);
} catch (final JSONException e) {
throw new SimpleRequestParseException("Error parsing echo request.", e);
}
}
/* (non-Javadoc)
* @see server.msg.SimpleRequest#getData()
*/
@Override
public JSONObject getData() {
final JSONObject jo = new JSONObject();
jo.put(KEY_MESSAGE, message);
return jo;
}
/* (non-Javadoc)
* @see server.msg.SimpleRequest#execute()
*/
@Override
public SimpleRespondMessageContext execute() {
final SimpleUser user = getUser();
final String username = (user != null) ? user.toString() : null;
final String data = username + "@" + getIdentity() + ": " + message;
return new SimpleRespondMessageContext(true, data);
}
/** Message to echo. */
private final String message;
}
| 1,953 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleQuitRequest.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 server.msg;
import org.json.JSONObject;
import server.SimpleConstants;
import server.userauth.SimpleUser;
/**
* <p>Request to terminate the server. Only the server administrator is
* permitted to execute this request.</p>
*
* <p>The request data object is defined as an empty JSON object.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleQuitRequest extends SimpleRequest {
/**
* <p>Create a new quit request.</p>
*
* @param identity requesting entity identity.
* @param user requesting user. May be null.
* @param data
*/
public SimpleQuitRequest(final String identity, final SimpleUser user, final JSONObject data) {
super(Type.QUIT, identity, user);
}
/* (non-Javadoc)
* @see server.msg.SimpleRequest#getData()
*/
@Override
public JSONObject getData() {
return new JSONObject();
}
/* (non-Javadoc)
* @see server.msg.SimpleRequest#execute()
*/
@Override
public SimpleRespondMessageContext execute() throws SimpleRequestUserException {
final String response;
// The request must come from the administrator.
final SimpleUser user = getUser();
if (user == null || !SimpleConstants.ADMIN_USERNAME.equals(user.getUserId())) {
throw new SimpleRequestUserException("Error: only the administrator may terminate the server.");
} else {
response = "Terminating server.";
}
// Return the response.
return new SimpleRespondMessageContext(true, response);
}
}
| 1,954 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleRequest.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 server.msg;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString;
import com.netflix.msl.MslConstants;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.msg.MessageHeader;
import com.netflix.msl.msg.MessageInputStream;
import com.netflix.msl.tokens.ServiceToken;
import server.userauth.SimpleUser;
/**
* <p>Example request type and parser.</p>
*
* <p>Requests are represented as JSON as follows:
* {@code {
* request = {
* "#mandatory" : [ "type", "data" ],
* "type" : "string",
* "data" : "object",
* }
* }} where:
* <ul>
* <li>{@code type} is the request type.</li>
* <li>{@code data} is the request data.</li>
* </ul></p>
*
* @author Wesley Miaw <[email protected]>
*/
public abstract class SimpleRequest implements JSONString {
/** JSON key type. */
private static final String KEY_TYPE = "type";
/** JSON key data. */
private static final String KEY_DATA = "data";
/** Request type. */
public enum Type {
/** Echo request data. */
ECHO,
/** Query for data. */
QUERY,
/** Provide log data. */
LOG,
/** Return user profile. */
USER_PROFILE,
/** Terminate server execution. */
QUIT,
}
/**
* <p>Parse a request from the provided input stream. The requesting entity
* identity must be provided. The requesting user may be null.</p>
*
* @param identity request entity identity.
* @param user request user. May be null.
* @param request request data.
* @param cryptoContexts service token crypto contexts.
* @return the parsed request.
* @throws IOException if there is an error reading from the input stream.
* @throws SimpleRequestUnknownException if the request cannot be
* identified.
* @throws SimpleRequestParseException if the request data fails to parse
* successfully.
* @throws SimpleRequestUserException if the request type requires a user
* but there is none provided.
*/
public static SimpleRequest parse(final String identity, final SimpleUser user, final MessageInputStream request, final Map<String,ICryptoContext> cryptoContexts) throws SimpleRequestUnknownException, SimpleRequestParseException, SimpleRequestUserException, IOException {
// Read request JSON.
final StringBuilder jsonBuilder = new StringBuilder();
final Reader r = new InputStreamReader(request, MslConstants.DEFAULT_CHARSET);
try {
while (true) {
final char[] buffer = new char[4096];
final int count = r.read(buffer);
if (count < 0)
break;
jsonBuilder.append(buffer, 0, count);
}
} finally {
try { r.close(); } catch(final IOException e) {}
}
final JSONObject json = new JSONObject(jsonBuilder.toString());
// Parse request.
final String typeString;
final JSONObject data;
try {
typeString = json.getString(KEY_TYPE);
data = json.getJSONObject(KEY_DATA);
} catch (final JSONException e) {
throw new SimpleRequestParseException("Error parsing request outer structure: " + json.toString(), e);
}
// Determine type.
final Type type;
try {
type = Type.valueOf(typeString);
} catch (final IllegalArgumentException e) {
throw new SimpleRequestUnknownException("Unknown request type " + typeString + ".");
}
// Return request.
switch (type) {
case ECHO:
return new SimpleEchoRequest(identity, user, data);
case QUERY:
return new SimpleQueryRequest(identity, user, data);
case LOG:
final MessageHeader header = request.getMessageHeader();
final Set<ServiceToken> tokens = header.getServiceTokens();
return new SimpleLogRequest(identity, user, data, tokens, cryptoContexts);
case USER_PROFILE:
return new SimpleProfileRequest(identity, user, data);
case QUIT:
return new SimpleQuitRequest(identity, user, data);
default:
throw new SimpleRequestUnknownException("Request type " + type + " has no request class.");
}
}
/**
* <p>Create a simple request with the provided data.</p>
*
* @param type request type.
* @param identity request entity identity.
* @param user request user. May be null.
*/
protected SimpleRequest(final Type type, final String identity, final SimpleUser user) {
this.type = type;
this.identity = identity;
this.user = user;
}
/**
* @return the request type.
*/
public Type getType() {
return type;
}
/**
* @return the request entity identity.
*/
public String getIdentity() {
return identity;
}
/**
* @return the request user. May be null.
*/
public SimpleUser getUser() {
return user;
}
/**
* @return the request data object.
*/
public abstract JSONObject getData();
/**
* <p>Executes the operation and returns the response.
*
* @return the response.
* @throws SimpleRequestUserException if the request type requires a user
* but there is none provided.
* @throws SimpleRequestExecutionException if there is an error executing
* the request.
*/
public abstract SimpleRespondMessageContext execute() throws SimpleRequestUserException, SimpleRequestExecutionException;
/* (non-Javadoc)
* @see org.json.JSONString#toJSONString()
*/
@Override
public String toJSONString() {
final JSONObject jo = new JSONObject();
jo.put(KEY_TYPE, type.name());
jo.put(KEY_DATA, getData());
return jo.toString();
}
/** Request type. */
private final Type type;
/** Request entity identity. */
private final String identity;
/** Request user. */
private final SimpleUser user;
}
| 1,955 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/msg/SimpleReceiveMessageContext.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 server.msg;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.msg.MessageContext;
import com.netflix.msl.msg.MessageDebugContext;
import com.netflix.msl.msg.MessageOutputStream;
import com.netflix.msl.msg.MessageServiceTokenBuilder;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* <p>Example server message context for receiving messages.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleReceiveMessageContext implements MessageContext {
/**
* <p>Create a new receive message context.</p>
*
* @param cryptoContexts service token crypto contexts.
*/
public SimpleReceiveMessageContext(final Map<String,ICryptoContext> cryptoContexts) {
this.cryptoContexts = Collections.unmodifiableMap(cryptoContexts);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getCryptoContexts()
*/
@Override
public Map<String, ICryptoContext> getCryptoContexts() {
return cryptoContexts;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getRemoteEntityIdentity()
*/
@Override
public String getRemoteEntityIdentity() {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isRequestingTokens()
*/
@Override
public boolean isRequestingTokens() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUserId()
*/
@Override
public String getUserId() {
return null;
}
/* (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 null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUser()
*/
@Override
public MslUser getUser() {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getKeyRequestData()
*/
@Override
public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException {
return null;
}
/* (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) {
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#write(com.netflix.msl.msg.MessageOutputStream)
*/
@Override
public void write(final MessageOutputStream output) throws IOException {
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getDebugContext()
*/
@Override
public MessageDebugContext getDebugContext() {
return null;
}
/** Service token crypto contexts. */
private final Map<String,ICryptoContext> cryptoContexts;
}
| 1,956 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/userauth/SimpleEmailPasswordStore.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 server.userauth;
import java.util.HashMap;
import java.util.Map;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.EmailPasswordStore;
/**
* <p>Example user email/password store.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleEmailPasswordStore implements EmailPasswordStore {
/**
* <p>Create a new email/password store that will authenticate the provided
* users.</p>
*
* @param emailPasswords map of email addresses onto passwords.
*/
public SimpleEmailPasswordStore(final Map<String,String> emailPasswords) {
this.emailPasswords.putAll(emailPasswords);
}
/* (non-Javadoc)
* @see com.netflix.msl.userauth.EmailPasswordStore#isUser(java.lang.String, java.lang.String)
*/
@Override
public MslUser isUser(final String email, final String password) {
final String expectedPassword = emailPasswords.get(email);
if (expectedPassword == null || !expectedPassword.equals(password))
return null;
return new SimpleUser(email);
}
/** Email/password database. */
private final Map<String,String> emailPasswords = new HashMap<String,String>();
}
| 1,957 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/userauth/SimpleUser.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 server.userauth;
import com.netflix.msl.tokens.MslUser;
/**
* <p>A MSL user that is just the user ID.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleUser implements MslUser {
/**
* <p>Create a new MSL user with the given user ID.</p>
*
* @param userId the user ID.
*/
public SimpleUser(final String userId) {
this.userId = userId;
}
/**
* @return the user ID.
*/
public String getUserId() {
return userId;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.MslUser#getEncoded()
*/
@Override
public String getEncoded() {
return userId;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return userId;
}
/** User string representation. */
private final String userId;
}
| 1,958 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/userauth/SimpleTokenFactory.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 server.userauth;
import java.sql.Date;
import java.util.concurrent.ConcurrentHashMap;
import javax.crypto.SecretKey;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslUserIdTokenException;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderUtils;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslUtils;
/**
* <p>A memory-backed token factory.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleTokenFactory implements TokenFactory {
/** Renewal window start offset in milliseconds. */
private static final int RENEWAL_OFFSET = 60000;
/** Expiration offset in milliseconds. */
private static final int EXPIRATION_OFFSET = 120000;
/** Non-replayable ID acceptance window. */
private static final long NON_REPLAYABLE_ID_WINDOW = 65536;
/**
* Return true if the provided master token is the newest master token
* as far as we know.
*
* @param masterToken the master token.
* @return true if this is the newest master token.
* @throws MslMasterTokenException if the master token is not decrypted.
*/
private boolean isNewestMasterToken(final MasterToken masterToken) throws MslMasterTokenException {
if (!masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
// Return true if we have no sequence number records or if the master
// token sequence number is the most recently issued one.
final Long newestSeqNo = mtSequenceNumbers.get(masterToken.getIdentity());
return (newestSeqNo == null || newestSeqNo.longValue() == masterToken.getSequenceNumber());
}
/* (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) {
// No support for revoked master tokens.
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) throws MslException {
if (!masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
if (nonReplayableId < 0 || nonReplayableId > MslConstants.MAX_LONG_VALUE)
throw new MslException(MslError.NONREPLAYABLE_ID_OUT_OF_RANGE, "nonReplayableId " + nonReplayableId);
// Accept if there is no non-replayable ID.
final String key = masterToken.getIdentity() + ":" + masterToken.getSerialNumber();
final Long largestNonReplayableId = nonReplayableIds.putIfAbsent(key, nonReplayableId);
if (largestNonReplayableId == null) {
return null;
}
// Reject if the non-replayable ID is equal or just a few messages
// behind. The sender can recover by incrementing.
final long catchupWindow = MslConstants.MAX_MESSAGES / 2;
if (nonReplayableId <= largestNonReplayableId &&
nonReplayableId > largestNonReplayableId - catchupWindow)
{
return MslError.MESSAGE_REPLAYED;
}
// Reject if the non-replayable ID is larger by more than the
// acceptance window. The sender cannot recover quickly.
if (nonReplayableId - NON_REPLAYABLE_ID_WINDOW > largestNonReplayableId)
return MslError.MESSAGE_REPLAYED_UNRECOVERABLE;
// If the non-replayable ID is smaller reject it if it is outside the
// wrap-around window. The sender cannot recover quickly.
if (nonReplayableId < largestNonReplayableId) {
final long cutoff = largestNonReplayableId - MslConstants.MAX_LONG_VALUE + NON_REPLAYABLE_ID_WINDOW;
if (nonReplayableId >= cutoff)
return MslError.MESSAGE_REPLAYED_UNRECOVERABLE;
}
// Accept the non-replayable ID.
//
// This is not perfect, since it's possible a smaller value will
// overwrite a larger value, but it's good enough for the example.
nonReplayableIds.put(key, nonReplayableId);
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#createMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.entityauth.EntityAuthenticationData, javax.crypto.SecretKey, javax.crypto.SecretKey, com.netflix.msl.io.MslObject)
*/
@Override
public MasterToken createMasterToken(final MslContext ctx, final EntityAuthenticationData entityAuthData, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException {
final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET);
final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET);
final long sequenceNumber = 0;
final long serialNumber = MslUtils.getRandomLong(ctx);
final String identity = entityAuthData.getIdentity();
final MasterToken masterToken = new MasterToken(ctx, renewalWindow, expiration, sequenceNumber, serialNumber, issuerData, identity, encryptionKey, hmacKey);
// Remember the sequence number.
//
// This is not perfect, since it's possible a smaller value will
// overwrite a larger value, but it's good enough for the example.
mtSequenceNumbers.put(identity, sequenceNumber);
// Return the new master token.
return masterToken;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#isMasterTokenRenewable(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslError isMasterTokenRenewable(final MslContext ctx, final MasterToken masterToken) throws MslMasterTokenException {
if (!isNewestMasterToken(masterToken))
return MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC;
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#renewMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, javax.crypto.SecretKey, javax.crypto.SecretKey, com.netflix.msl.io.MslObject)
*/
@Override
public MasterToken renewMasterToken(final MslContext ctx, final MasterToken masterToken, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException, MslMasterTokenException {
if (!isNewestMasterToken(masterToken))
throw new MslMasterTokenException(MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC, masterToken);
// Renew master token.
final MslObject mtIssuerData = masterToken.getIssuerData();
final MslObject mergedIssuerData;
try {
mergedIssuerData = MslEncoderUtils.merge(mtIssuerData, issuerData);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MASTERTOKEN_ISSUERDATA_ENCODE_ERROR, "mt issuerdata " + mtIssuerData + "; issuerdata " + issuerData, e);
}
final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET);
final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET);
final long oldSequenceNumber = masterToken.getSequenceNumber();
final long sequenceNumber = (oldSequenceNumber == MslConstants.MAX_LONG_VALUE) ? 0 : oldSequenceNumber + 1;
final long serialNumber = masterToken.getSerialNumber();
final String identity = masterToken.getIdentity();
final MasterToken newMasterToken = new MasterToken(ctx, renewalWindow, expiration, sequenceNumber, serialNumber, mergedIssuerData, identity, encryptionKey, hmacKey);
// Remember the sequence number.
//
// This is not perfect, since it's possible a smaller value will
// overwrite a larger value, but it's good enough for the example.
mtSequenceNumbers.put(identity, sequenceNumber);
// Return the new master token.
return newMasterToken;
}
/* (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) {
// No support for revoked user ID tokens.
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#createUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MslUser, com.netflix.msl.tokens.MasterToken)
*/
@Override
public UserIdToken createUserIdToken(final MslContext ctx, final MslUser user, final MasterToken masterToken) throws MslEncodingException, MslCryptoException {
final MslObject issuerData = null;
final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET);
final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET);
final long serialNumber = MslUtils.getRandomLong(ctx);
return new UserIdToken(ctx, renewalWindow, expiration, masterToken, serialNumber, issuerData, user);
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#renewUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.UserIdToken, com.netflix.msl.tokens.MasterToken)
*/
@Override
public UserIdToken renewUserIdToken(final MslContext ctx, final UserIdToken userIdToken, final MasterToken masterToken) throws MslEncodingException, MslCryptoException, MslUserIdTokenException {
if (!userIdToken.isDecrypted())
throw new MslUserIdTokenException(MslError.USERIDTOKEN_NOT_DECRYPTED, userIdToken).setMasterToken(masterToken);
final MslObject issuerData = null;
final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET);
final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET);
final long serialNumber = userIdToken.getSerialNumber();
final MslUser user = userIdToken.getUser();
return new UserIdToken(ctx, renewalWindow, expiration, masterToken, serialNumber, issuerData, user);
}
/* (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) {
return new SimpleUser(userdata);
}
/** Map of entity identities onto sequence numbers. */
private final ConcurrentHashMap<String,Long> mtSequenceNumbers = new ConcurrentHashMap<String,Long>();
/** Map of entity identities and serial numbers onto non-replayable IDs. */
private final ConcurrentHashMap<String,Long> nonReplayableIds = new ConcurrentHashMap<String,Long>();
}
| 1,959 |
0 |
Create_ds/msl/examples/simple/src/main/java/server
|
Create_ds/msl/examples/simple/src/main/java/server/entityauth/SimpleRsaStore.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package server.entityauth;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import com.netflix.msl.entityauth.RsaStore;
/**
* <p>An example RSA key store.</p>
*
* @author Wesley Miaw <[email protected]>
*/
public class SimpleRsaStore implements RsaStore {
/**
* <p>Create a new RSA store that will return the provided public and/or
* private keys for the specified server entity identity. A public key must
* be provided to authenticate remote entities. A private key must be
* provided to authenticate local entities.</p>
*
* @param serverId server entity identity.
* @param publicKey server RSA public key. May be null.
* @param privateKey server RSA private key. May be null.
*/
public SimpleRsaStore(final String serverId, final PublicKey publicKey, final PrivateKey privateKey) {
this.serverId = serverId;
this.publicKey = publicKey;
this.privateKey = privateKey;
}
@Override
public Set<String> getIdentities() {
return new HashSet<String>(Arrays.asList(serverId));
}
@Override
public PublicKey getPublicKey(final String identity) {
if (serverId.equals(identity))
return publicKey;
return null;
}
@Override
public PrivateKey getPrivateKey(final String identity) {
if (serverId.equals(identity))
return privateKey;
return null;
}
/** Server entity identity. */
private final String serverId;
/** Server RSA public key. */
private final PublicKey publicKey;
/** Server RSA private key. */
private final PrivateKey privateKey;
};
| 1,960 |
0 |
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli
|
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server/ServerMslConfig.java
|
/**
* Copyright (c) 2014-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.server;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.MslConfig;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
import mslcli.server.util.ServerAuthenticationUtils;
/**
* <p>
* The configuration class for MSl server, created per given server entity identity.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public final class ServerMslConfig extends MslConfig {
/**
* Constructor.
*
* @param appCtx application context.
* @param args command line arguments
* @throws ConfigurationException if some configuration parameters required for initialization are missing, invalid, or mutually inconsistent
* @throws IllegalCmdArgumentException if some command line parameters required for initialization are missing, invalid, or mutually inconsistent
*/
public ServerMslConfig(final AppContext appCtx, final CmdArguments args)
throws ConfigurationException, IllegalCmdArgumentException
{
super(appCtx, args, new ServerAuthenticationUtils(args.getEntityId(), appCtx));
}
}
| 1,961 |
0 |
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli
|
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server/SimpleMslServer.java
|
/**
* Copyright (c) 2014-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.crypto.SecretKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.netflix.msl.MslException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.SymmetricCryptoContext;
import com.netflix.msl.msg.ConsoleFilterStreamFactory;
import com.netflix.msl.msg.ErrorHeader;
import com.netflix.msl.msg.MessageContext;
import com.netflix.msl.msg.MessageInputStream;
import com.netflix.msl.msg.MslControl;
import com.netflix.msl.msg.MslControl.MslChannel;
import com.netflix.msl.util.MslContext;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.Pair;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.ConfigurationRuntimeException;
import mslcli.common.util.MslProperties;
import mslcli.common.util.SharedUtil;
import mslcli.server.msg.ServerReceiveMessageContext;
import mslcli.server.msg.ServerRespondMessageContext;
import mslcli.server.msg.ServerRespondMessageContext.Token;
import mslcli.server.util.ServerMslContext;
/**
* <p>
* An example Java MSL server that listens for requests from the example MSL client.
* This class is thread-safe.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class SimpleMslServer {
/** timeout for reading request and producing response */
private static final int TIMEOUT_MS = 120 * 1000;
// Add BouncyCastle provider.
static {
Security.addProvider(new BouncyCastleProvider());
}
/**
* Create a new server instance and initialize its state.
*
* @param prop MslProperties from the configuration file
* @param args command line arguments
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public SimpleMslServer(final MslProperties prop, final CmdArguments args) throws ConfigurationException, IllegalCmdArgumentException {
if (prop == null) {
throw new IllegalArgumentException("NULL MslProperties");
}
this.appCtx = AppContext.getInstance(prop);
// Create the MSL control.
this.mslCtrl = appCtx.getMslControl();
if (args.isVerbose()) {
mslCtrl.setFilterFactory(new ConsoleFilterStreamFactory());
}
this.mslCtx = new ServerMslContext(appCtx, new ServerMslConfig(appCtx, args));
// Use one crypto context for all service tokens.
final String stKeySetId = prop.getServiceTokenKeySetId(args.getEntityId());
final Pair<SecretKey,SecretKey> keys = appCtx.getServiceTokenKeys(stKeySetId);
final ICryptoContext stCryptoContext = new SymmetricCryptoContext(this.mslCtx, stKeySetId, keys.x, keys.y, null);
cryptoContexts.put("", stCryptoContext);
}
/**
* Process incoming MSL request and produce MSL response.
*
* @param in input stream for reading request
* @param out output stream for writing response
* @throws ConfigurationException
* @throws IOException
* @throws MslException
*/
public void processRequest(final InputStream in, final OutputStream out) throws ConfigurationException, IOException, MslException {
if (in == null) {
throw new IllegalArgumentException("NULL Input Stream");
}
if (out == null) {
throw new IllegalArgumentException("NULL Output Stream");
}
// Set up the receive MSL message context.
final MessageContext rcvMsgCtx = new ServerReceiveMessageContext(cryptoContexts);
// Receive a request.
final MessageInputStream requestInputStream;
final Future<MessageInputStream> requestFuture = mslCtrl.receive(mslCtx, rcvMsgCtx, in, out, TIMEOUT_MS);
try {
requestInputStream = requestFuture.get();
} catch (final ExecutionException e) {
final Throwable thr = SharedUtil.getRootCause(e);
if (thr instanceof MslException) {
throw (MslException)thr;
} else if (thr instanceof ConfigurationException) {
throw (ConfigurationException)thr;
} else if (thr instanceof ConfigurationRuntimeException) {
throw (ConfigurationException)thr.getCause();
} else {
throw new IOException("ExecutionException", e);
}
} catch (final InterruptedException e) {
throw new IOException("InterruptedException", e);
}
if (requestInputStream == null) {
appCtx.info("NULL Input Stream");
return;
}
// We should not receive error headers but check just in case.
final ErrorHeader error = requestInputStream.getErrorHeader();
if (error != null) {
throw new IOException("Unexpectedly received error message: [" + error.getErrorCode() + "][" + error.getInternalCode() + "][" + error.getErrorMessage() + "]");
}
// Process request.
final byte[] request = SharedUtil.readIntoArray(requestInputStream);
// Set up the respond MSL message context. Echo back the initial request.
final Set<Token> tokens = new HashSet<Token>();
tokens.addAll(Arrays.asList(
new Token("st_name1", "st_data1", true, true),
new Token("st_name2", "st_data2", true, true)
));
final MessageContext responseMsgCtx = new ServerRespondMessageContext(true, request /*echo request*/, tokens, cryptoContexts);
// Send response. We don't need the MslChannel because we are not
// opening a persistent channel.
final Future<MslChannel> channelFuture = mslCtrl.respond(mslCtx, responseMsgCtx, in, out, requestInputStream, TIMEOUT_MS);
try {
channelFuture.get();
} catch (final ExecutionException e) {
final Throwable thr = SharedUtil.getRootCause(e);
if (thr instanceof MslException) {
throw (MslException)thr;
} else if (thr instanceof ConfigurationException) {
throw (ConfigurationException)thr;
} else if (thr instanceof ConfigurationRuntimeException) {
throw (ConfigurationException)thr.getCause();
} else {
throw new IOException("ExecutionException", e);
}
} catch (final InterruptedException e) {
throw new IOException("ExecutionException", e);
}
}
/** application context. */
private final AppContext appCtx;
/** MSL context. */
private final MslContext mslCtx;
/** MSL control. */
private final MslControl mslCtrl;
/** Service token crypto contexts. */
private final Map<String,ICryptoContext> cryptoContexts = new HashMap<String,ICryptoContext>();
}
| 1,962 |
0 |
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli
|
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server/SimpleHttpServer.java
|
/**
* Copyright (c) 2014-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Date;
import com.netflix.msl.MslException;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import mslcli.common.CmdArguments;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.ConfigurationRuntimeException;
import mslcli.common.util.MslProperties;
import mslcli.common.util.SharedUtil;
/**
* <p>Simple HTTP Server using com.sun.net.httpserver.* classes built into Oracle's JVM</p>
*
* @author Vadim Spector <[email protected]>
*/
public class SimpleHttpServer {
/**
* HTTP server launcher
* @param args command line arguments
*/
public static void main(final String[] args) {
if (args.length < 1) {
log("Parameters: config_file");
System.exit(1);
}
try {
final CmdArguments cmdArgs = new CmdArguments(args);
final MslProperties prop = MslProperties.getInstance(SharedUtil.loadPropertiesFromFile(cmdArgs.getConfigFilePath()));
final SimpleMslServer mslServer = new SimpleMslServer(prop, cmdArgs);
final HttpServer server = HttpServer.create(new InetSocketAddress(prop.getServerPort()), 0);
server.createContext("/mslcli-server", new MyHandler(mslServer));
server.setExecutor(null); // creates a default executor
log(String.format("waiting for requests on http://localhost:%d/mslcli-server ...", prop.getServerPort()));
server.start();
} catch (final ConfigurationException e) {
log("Server Configuration Error: " + e.getMessage());
System.exit(1);
} catch (final IOException e) {
log("Server Initialization Error: " + e.getMessage());
System.exit(1);
} catch (final Exception e) {
log("Server Internal Error: " + e.getMessage());
SharedUtil.getRootCause(e).printStackTrace(System.err);
System.exit(1);
}
}
/**
* callback class for handling to HTTP requests
*/
static class MyHandler implements HttpHandler {
/**
* @param mslServer MSL server to delegate requests to
*/
MyHandler(final SimpleMslServer mslServer) {
this.mslServer = mslServer;
}
@Override
public void handle(final HttpExchange t) throws IOException {
log("Processing request");
final long t_start = System.currentTimeMillis();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
// Allow requests from anywhere.
t.getResponseHeaders().set("Access-Control-Allow-Origin", "*");
mslServer.processRequest(t.getRequestBody(), out);
} catch (final ConfigurationException e) {
log("Server Configuration Error: " + e.getMessage());
} catch (final ConfigurationRuntimeException e) {
log("Server Configuration Error: " + e.getCause().getMessage());
} catch (final MslException e) {
log(SharedUtil.getMslExceptionInfo(e));
} catch (final IOException e) {
final Throwable thr = SharedUtil.getRootCause(e);
log("IO-ERROR: " + e);
log("ROOT CAUSE:");
thr.printStackTrace(System.err);
} catch (final RuntimeException e) {
log("RT-ERROR: " + e);
log("ROOT CAUSE:");
SharedUtil.getRootCause(e).printStackTrace(System.err);
} finally {
final byte[] response = out.toByteArray();
t.sendResponseHeaders(200, response.length);
final OutputStream os = t.getResponseBody();
os.write(response);
os.flush();
os.close();
}
final long t_total = System.currentTimeMillis() - t_start;
log(String.format("SUCCESS: %1$te/%1$tm/%1$tY %1$tH:%1$tM:%1$tS.%1$tL", new Date()));
log(String.format("Processing Time %d msec", t_total));
}
/** MSL server to delegate requests to */
private final SimpleMslServer mslServer;
}
/**
* @param msg message to log
*/
private static void log(final String msg) {
System.out.println(msg);
}
}
| 1,963 |
0 |
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli
|
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server/SimpleServlet.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.server;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.netflix.msl.MslException;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.MslProperties;
import mslcli.common.util.SharedUtil;
/**
* <p>
* An example Java MSL servlet that listens for requests from the example MSL client.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class SimpleServlet extends HttpServlet {
/** for proper serialization */
private static final long serialVersionUID = -4593207843035538485L;
/** name of the servlet property for the configuration file path */
private static final String CONFIG_FILE_PATH = "mslcli.cfg.file";
/** name of the servlet property for the server entity identity */
private static final String SERVER_ID = "mslcli.cfg.server.id";
/**
* <p>Initialize servlet instance and MSL server.</p>
*/
@Override
public void init(ServletConfig cfg) throws ServletException {
super.init(cfg);
final String configFile = cfg.getInitParameter(CONFIG_FILE_PATH);
if (configFile == null)
throw new ServletException("Missing Servlet Configuration Parameter " + CONFIG_FILE_PATH);
final String serverId = cfg.getInitParameter(SERVER_ID);
if (serverId == null)
throw new ServletException("Missing Servlet Configuration Parameter " + SERVER_ID);
final Properties prop;
try {
prop = SharedUtil.loadPropertiesFromFile(configFile);
} catch (IOException e) {
throw new ServletException("Error Loading Configuration File " + CONFIG_FILE_PATH, e);
}
final MslProperties mslProp = MslProperties.getInstance(prop);
try {
this.mslServer = new SimpleMslServer(mslProp, new CmdArguments(new String[] { CmdArguments.P_CFG, configFile, CmdArguments.P_EID, serverId } ));
} catch (ConfigurationException e) {
throw new ServletException(String.format("Server Configuration %s Validation Error", CONFIG_FILE_PATH), e);
} catch (IllegalCmdArgumentException e) {
throw new ServletException("Server Internal Initialization Error", e);
}
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
// Allow requests from anywhere.
resp.setHeader("Access-Control-Allow-Origin", "*");
try {
mslServer.processRequest(req.getInputStream(), resp.getOutputStream());
} catch (ConfigurationException e) {
log("Server Configuration Error: " + e.getMessage());
throw new IOException("MslException", e);
} catch (MslException e) {
log(SharedUtil.getMslExceptionInfo(e));
throw new IOException("MslException", e);
}
}
/** MSL server. */
private SimpleMslServer mslServer;
}
| 1,964 |
0 |
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server
|
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server/util/ServerMslContext.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.server.util;
import javax.crypto.SecretKey;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.SymmetricCryptoContext;
import com.netflix.msl.tokens.TokenFactory;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.Triplet;
import mslcli.common.util.AppContext;
import mslcli.common.util.CommonMslContext;
import mslcli.common.util.ConfigurationException;
import mslcli.server.ServerMslConfig;
import mslcli.server.tokens.ServerTokenFactory;
/**
* <p>Server MSL context. It represents configurations specific to a given service entity ID.</p>
*
* @author Vadim Spector <[email protected]>
*/
public class ServerMslContext extends CommonMslContext {
/**
* <p>Create a new server MSL context.</p>
*
* @param appCtx application context
* @param mslCfg server MSL configuration.
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public ServerMslContext(final AppContext appCtx, final ServerMslConfig mslCfg) throws ConfigurationException, IllegalCmdArgumentException {
super(appCtx, mslCfg);
// MSL crypto context.
final Triplet<SecretKey,SecretKey,SecretKey> mslKeys = appCtx.getMslKeys();
this.mslCryptoContext = new SymmetricCryptoContext(this, mslCfg.getEntityId(), mslKeys.x, mslKeys.y, mslKeys.z);
// key token factory
this.tokenFactory = new ServerTokenFactory(appCtx);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslCryptoContext()
*/
@Override
public ICryptoContext getMslCryptoContext() throws MslCryptoException {
return mslCryptoContext;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getTokenFactory()
*/
@Override
public TokenFactory getTokenFactory() {
return tokenFactory;
}
/** MSL crypto context */
private final ICryptoContext mslCryptoContext;
/** MSL token factory */
private final TokenFactory tokenFactory;
}
| 1,965 |
0 |
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server
|
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server/util/ServerAuthenticationUtils.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.server.util;
import mslcli.common.util.AppContext;
import mslcli.common.util.CommonAuthenticationUtils;
import mslcli.common.util.ConfigurationException;
/**
* <p>
* Authentication utility telling which entity authentication, user authentication,
* and key exchange schemes are permitted/supported for a given entity.
* So far, the base class functionality is sufficient.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class ServerAuthenticationUtils extends CommonAuthenticationUtils {
/**
* <p>Create a new authentication utils instance for the specified server identity.
* </p>
*
* @param serverId local server entity identity.
* @param appCtx application context
* @throws ConfigurationException if some configuration parameters required for initialization are missing, invalid, or inconsistent
*/
public ServerAuthenticationUtils(final String serverId, final AppContext appCtx) throws ConfigurationException {
super(serverId, appCtx);
}
}
| 1,966 |
0 |
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server
|
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server/msg/ServerRespondMessageContext.java
|
/**
* Copyright (c) 2014-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.server.msg;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
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.MslException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.msg.MessageContext;
import com.netflix.msl.msg.MessageDebugContext;
import com.netflix.msl.msg.MessageOutputStream;
import com.netflix.msl.msg.MessageServiceTokenBuilder;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationData;
import mslcli.common.util.SharedUtil;
/**
* <p>Example server message context for sending response messages.</p>
*
* @author Vadim Spector <[email protected]>
*/
public class ServerRespondMessageContext implements MessageContext {
/**
* <p>Service token container.</p>
*/
public static class Token {
/**
* <p>Define a new service token for inclusion in the response message.
* If the service token should be entity- or user-bound but cannot be,
* the maximum binding possible is used but the service token is
* included in the response.</p>
*
* @param name service token name.
* @param data service token application data.
* @param entityBound true if the service token should be entity-bound.
* @param userBound true if the service token should be user-bound.
*/
public Token(final String name, final String data, final boolean entityBound, final boolean userBound) {
this.name = name;
this.data = data;
this.entityBound = entityBound;
this.userBound = userBound;
}
/** Service token name. */
public final String name;
/** Service token application data. */
public final String data;
/** Service token should be entity-bound. */
public final boolean entityBound;
/** Service token should be user-bound. */
public final boolean userBound;
}
/**
* <p>Create a new response message context with the specified
* properties.</p>
*
* @param encrypted true if the response data must be encrypted.
* @param data application response data.
*/
public ServerRespondMessageContext(final boolean encrypted, final byte[] data) {
this.encrypted = encrypted;
this.data = data;
this.tokens = Collections.emptySet();
this.cryptoContexts = Collections.emptyMap();
}
/**
* <p>Create a new response message context with the specified
* properties.</p>
*
* @param encrypted true if the response data must be encrypted.
* @param data application response data.
* @param tokens application service tokens.
* @param cryptoContexts application service token crypto contexts.
*/
public ServerRespondMessageContext(final boolean encrypted, final byte[] data, final Set<Token> tokens, final Map<String,ICryptoContext> cryptoContexts) {
this.encrypted = encrypted;
this.data = data;
this.tokens = tokens;
this.cryptoContexts = Collections.unmodifiableMap(cryptoContexts);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getCryptoContexts()
*/
@Override
public Map<String, ICryptoContext> getCryptoContexts() {
return cryptoContexts;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getRemoteEntityIdentity()
*/
@Override
public String getRemoteEntityIdentity() {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return encrypted;
}
/* (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;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isRequestingTokens()
*/
@Override
public boolean isRequestingTokens() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUserId()
*/
@Override
public String getUserId() {
return null;
}
/* (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 null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUser()
*/
@Override
public MslUser getUser() {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getKeyRequestData()
*/
@Override
public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException {
return null;
}
/* (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 MslEncodingException, MslCryptoException, MslException {
if (handshake)
return;
for (final Token token : tokens) {
final String name = token.name;
final byte[] data = token.data.getBytes(MslConstants.DEFAULT_CHARSET);
if (token.userBound && builder.isPrimaryUserIdTokenAvailable())
builder.addUserBoundPrimaryServiceToken(name, data, true, CompressionAlgorithm.GZIP);
else if (token.entityBound && builder.isPrimaryMasterTokenAvailable())
builder.addMasterBoundPrimaryServiceToken(name, data, true, CompressionAlgorithm.GZIP);
else
builder.addUnboundPrimaryServiceToken(name, data, true, CompressionAlgorithm.GZIP);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#write(com.netflix.msl.msg.MessageOutputStream)
*/
@Override
public void write(final MessageOutputStream output) throws IOException {
output.write(data);
output.close();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getDebugContext()
*/
@Override
public MessageDebugContext getDebugContext() {
return null;
}
@Override
public String toString() {
return SharedUtil.toString(this);
}
/** Service token crypto contexts. */
private final Map<String,ICryptoContext> cryptoContexts;
/** True if the response data must be encrypted. */
private final boolean encrypted;
/** Response data. */
private final byte[] data;
/** Service tokens. */
private final Set<Token> tokens;
}
| 1,967 |
0 |
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server
|
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server/msg/ServerReceiveMessageContext.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.server.msg;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.msg.MessageContext;
import com.netflix.msl.msg.MessageDebugContext;
import com.netflix.msl.msg.MessageOutputStream;
import com.netflix.msl.msg.MessageServiceTokenBuilder;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationData;
import mslcli.common.util.SharedUtil;
/**
* <p>Example server message context for receiving messages.</p>
*
* @author Vadim Spector <[email protected]>
*/
public class ServerReceiveMessageContext implements MessageContext {
/**
* <p>Create a new receive message context.</p>
*
* @param cryptoContexts service token crypto contexts.
*/
public ServerReceiveMessageContext(final Map<String,ICryptoContext> cryptoContexts) {
this.cryptoContexts = Collections.unmodifiableMap(cryptoContexts);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getCryptoContexts()
*/
@Override
public Map<String, ICryptoContext> getCryptoContexts() {
return cryptoContexts;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getRemoteEntityIdentity()
*/
@Override
public String getRemoteEntityIdentity() {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isRequestingTokens()
*/
@Override
public boolean isRequestingTokens() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUserId()
*/
@Override
public String getUserId() {
return null;
}
/* (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 null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUser()
*/
@Override
public MslUser getUser() {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getKeyRequestData()
*/
@Override
public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException {
return null;
}
/* (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) {
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#write(com.netflix.msl.msg.MessageOutputStream)
*/
@Override
public void write(final MessageOutputStream output) throws IOException {
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getDebugContext()
*/
@Override
public MessageDebugContext getDebugContext() {
return null;
}
@Override
public String toString() {
return SharedUtil.toString(this);
}
/** Service token crypto contexts. */
private final Map<String,ICryptoContext> cryptoContexts;
}
| 1,968 |
0 |
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server
|
Create_ds/msl/examples/mslcli/server/src/main/java/mslcli/server/tokens/ServerTokenFactory.java
|
/**
* Copyright (c) 2014-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.server.tokens;
import java.sql.Date;
import java.util.concurrent.ConcurrentHashMap;
import javax.crypto.SecretKey;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslUserIdTokenException;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderUtils;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslUtils;
import mslcli.common.tokens.SimpleUser;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.SharedUtil;
/**
* <p>A server-side memory-backed token factory.</p>
*
* @author Vadim Spector <[email protected]>
*/
public class ServerTokenFactory implements TokenFactory {
/** Master Token Renewal window start offset in milliseconds. */
private final int renewalOffset;
/** Master Token Expiration offset in milliseconds. */
private final int expirationOffset;
/** Master Token Non-replayable ID acceptance window. */
private final long nonReplayIdWindow;
/** Master Token max number of lost tokens still allowed for renewal */
private final long maxSkipped;
/** User ID Token Renewal window start offset in milliseconds. */
private final int uitRenewalOffset;
/** User ID Expiration offset in milliseconds. */
private final int uitExpirationOffset;
/** app context */
private final AppContext appCtx;
/**
* @param appCtx application context
* @throws ConfigurationException if some required configuration properties are missing or invalid
*/
public ServerTokenFactory(final AppContext appCtx) throws ConfigurationException {
if (appCtx == null) {
throw new IllegalArgumentException("NULL app context");
}
this.appCtx = appCtx;
this.renewalOffset = appCtx.getProperties().getMasterTokenRenewalOffset();
this.expirationOffset = appCtx.getProperties().getMasterTokenExpirationOffset();
this.nonReplayIdWindow = appCtx.getProperties().getMasterTokenNonReplayIdWindow();
this.maxSkipped = appCtx.getProperties().getMasterTokenMaxSkipped();
this.uitRenewalOffset = appCtx.getProperties().getUserIdTokenRenewalOffset();
this.uitExpirationOffset = appCtx.getProperties().getUserIdTokenExpirationOffset();
}
/**
* Returns true if the master token sequence number is within the
* acceptable range for master token renewal.
*
* @param masterToken the master token.
* @return true if the master token sequence number is acceptable.
* @throws MslMasterTokenException if the master token is not decrypted.
*/
private boolean isMasterTokenAcceptable(final MasterToken masterToken) throws MslMasterTokenException {
if (!masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
// Return false if we have no sequence number records
final SeqNumPair seqNumPair = mtSequenceNumbers.get(masterToken.getIdentity());
if (seqNumPair == null)
return false;
// if it's the first MasterToken issued, its serial number must be the one we recorded
if (seqNumPair.oldSeqNum == null) {
return seqNumPair.newSeqNum.longValue() == masterToken.getSequenceNumber();
// if it's not the first master token, it must be either the last issued
// ... or the last used for issuing the last issued, in case all subsequent issued ones were lost on its way to the client
// ... as long as not too many were lost
} else {
return ((seqNumPair.oldSeqNum.longValue() == masterToken.getSequenceNumber()) ||
(seqNumPair.newSeqNum.longValue() == masterToken.getSequenceNumber())) &&
((seqNumPair.newSeqNum.longValue() - seqNumPair.oldSeqNum.longValue()) < maxSkipped);
}
}
/* (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) {
// No support for revoked master tokens.
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) throws MslException {
synchronized (nonReplayableIdsLock) {
if (!masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
if (nonReplayableId < 0 || nonReplayableId > MslConstants.MAX_LONG_VALUE)
throw new MslException(MslError.NONREPLAYABLE_ID_OUT_OF_RANGE, "nonReplayableId " + nonReplayableId);
// Accept if there is no non-replayable ID.
final String key = masterToken.getIdentity() + ":" + masterToken.getSerialNumber();
final Long storedNonReplayableId = nonReplayableIds.putIfAbsent(key, nonReplayableId);
if (storedNonReplayableId == null) {
appCtx.info(String.format("%s: %s: First Non-Replayable ID %d", this, key, nonReplayableId));
return null;
}
// Reject if the non-replayable ID is equal or just a few messages
// behind. The sender can recover by incrementing.
final long catchupWindow = MslConstants.MAX_MESSAGES / 2;
if (nonReplayableId <= storedNonReplayableId &&
nonReplayableId > storedNonReplayableId - catchupWindow)
{
return MslError.MESSAGE_REPLAYED;
}
// Reject if the non-replayable ID is larger by more than the
// acceptance window. The sender cannot recover quickly.
if (nonReplayableId - nonReplayIdWindow > storedNonReplayableId)
return MslError.MESSAGE_REPLAYED_UNRECOVERABLE;
// If the non-replayable ID is smaller reject it if it is outside the
// wrap-around window. The sender cannot recover quickly.
if (nonReplayableId < storedNonReplayableId) {
final long cutoff = storedNonReplayableId - MslConstants.MAX_LONG_VALUE + nonReplayIdWindow;
if (nonReplayableId >= cutoff)
return MslError.MESSAGE_REPLAYED_UNRECOVERABLE;
}
// Accept the non-replayable ID.
//
// This is not perfect, since it's possible a smaller value will
// overwrite a larger value, but it's good enough for the example.
nonReplayableIds.put(key, nonReplayableId);
appCtx.info(String.format("%s: %s: Update Non-Replayable ID %d", this, key, nonReplayableId));
return null;
} // synchronized (nonReplayableIdsLock)
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#createMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.entityauth.EntityAuthenticationData, javax.crypto.SecretKey, javax.crypto.SecretKey, com.netflix.msl.io.MslObject)
*/
@Override
public MasterToken createMasterToken(final MslContext ctx, final EntityAuthenticationData entityAuthData, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException {
final String identity = entityAuthData.getIdentity();
appCtx.info(String.format("%s: Creating MasterToken for %s", this, identity));
final Date renewalWindow = new Date(ctx.getTime() + renewalOffset);
final Date expiration = new Date(ctx.getTime() + expirationOffset);
final long sequenceNumber = 0;
final long serialNumber = MslUtils.getRandomLong(ctx);
final MasterToken masterToken = new MasterToken(ctx, renewalWindow, expiration, sequenceNumber, serialNumber, issuerData, identity, encryptionKey, hmacKey);
// Remember the sequence number.
//
// This is not perfect, since it's possible a smaller value will
// overwrite a larger value, but it's good enough for the example.
mtSequenceNumbers.put(identity, new SeqNumPair(null, sequenceNumber));
// Return the new master token.
return masterToken;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#isMasterTokenRenewable(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslError isMasterTokenRenewable(final MslContext ctx, final MasterToken masterToken) throws MslMasterTokenException {
if (!isMasterTokenAcceptable(masterToken))
return MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC;
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#renewMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, javax.crypto.SecretKey, javax.crypto.SecretKey, com.netflix.msl.io.MslObject)
*/
@Override
public MasterToken renewMasterToken(final MslContext ctx, final MasterToken masterToken, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException, MslMasterTokenException {
appCtx.info(String.format("%s: Renewing %s", this, SharedUtil.getMasterTokenInfo(masterToken)));
if (!isMasterTokenAcceptable(masterToken))
throw new MslMasterTokenException(MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC, masterToken);
// Renew master token.
final MslObject mtIssuerData = masterToken.getIssuerData();
final MslObject mergedIssuerData;
try {
mergedIssuerData = MslEncoderUtils.merge(mtIssuerData, issuerData);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MASTERTOKEN_ISSUERDATA_ENCODE_ERROR, "mt issuerdata " + mtIssuerData + "; issuerdata " + issuerData, e);
}
final Date renewalWindow = new Date(ctx.getTime() + renewalOffset);
final Date expiration = new Date(ctx.getTime() + expirationOffset);
final String identity = masterToken.getIdentity();
final SeqNumPair seqNumPair = mtSequenceNumbers.get(identity);
final long lastSequenceNumber = seqNumPair.newSeqNum;
final long nextSequenceNumber = (lastSequenceNumber == MslConstants.MAX_LONG_VALUE) ? 0 : lastSequenceNumber + 1;
final long serialNumber = masterToken.getSerialNumber();
final MasterToken newMasterToken = new MasterToken(ctx, renewalWindow, expiration, nextSequenceNumber, serialNumber, mergedIssuerData, identity, encryptionKey, hmacKey);
// Remember the sequence number.
//
// This is not perfect, since it's possible a smaller value will
// overwrite a larger value, but it's good enough for the example.
mtSequenceNumbers.put(identity, new SeqNumPair(masterToken.getSequenceNumber(), nextSequenceNumber));
// Return the new master token.
return newMasterToken;
}
/* (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) {
// No support for revoked user ID tokens.
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#createUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MslUser, com.netflix.msl.tokens.MasterToken)
*/
@Override
public UserIdToken createUserIdToken(final MslContext ctx, final MslUser user, final MasterToken masterToken) throws MslEncodingException, MslCryptoException {
appCtx.info(String.format("%s: Creating UserIdToken for user %s", this, ((user != null) ? user.getEncoded() : null)));
final MslObject issuerData = null;
final Date renewalWindow = new Date(ctx.getTime() + uitRenewalOffset);
final Date expiration = new Date(ctx.getTime() + uitExpirationOffset);
final long serialNumber = MslUtils.getRandomLong(ctx);
return new UserIdToken(ctx, renewalWindow, expiration, masterToken, serialNumber, issuerData, user);
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.TokenFactory#renewUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.UserIdToken, com.netflix.msl.tokens.MasterToken)
*/
@Override
public UserIdToken renewUserIdToken(final MslContext ctx, final UserIdToken userIdToken, final MasterToken masterToken) throws MslEncodingException, MslCryptoException, MslUserIdTokenException {
appCtx.info(String.format("%s: Renewing %s", this, SharedUtil.getUserIdTokenInfo(userIdToken)));
if (!userIdToken.isDecrypted())
throw new MslUserIdTokenException(MslError.USERIDTOKEN_NOT_DECRYPTED, userIdToken).setMasterToken(masterToken);
final MslObject issuerData = null;
final Date renewalWindow = new Date(ctx.getTime() + uitRenewalOffset);
final Date expiration = new Date(ctx.getTime() + uitExpirationOffset);
final long serialNumber = userIdToken.getSerialNumber();
final MslUser user = userIdToken.getUser();
return new UserIdToken(ctx, renewalWindow, expiration, masterToken, serialNumber, issuerData, user);
}
/* (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) {
return new SimpleUser(userdata);
}
@Override
public String toString() {
return SharedUtil.toString(this);
}
/** Map of entity identities onto sequence numbers. */
private final ConcurrentHashMap<String,SeqNumPair> mtSequenceNumbers = new ConcurrentHashMap<String,SeqNumPair>();
/** Map of entity identities and serial numbers onto non-replayable IDs. */
private final ConcurrentHashMap<String,Long> nonReplayableIds = new ConcurrentHashMap<String,Long>();
/** lock object to sync access to nonReplayableIds */
private final Object nonReplayableIdsLock = new Object();
/**
* the class to store the latest master token sequence number and the sequence number
* of the master token that was used for renewal.
*/
private static final class SeqNumPair {
/** old sequence number */
private final Long oldSeqNum;
/** new sequence number */
private final Long newSeqNum;
/**
* @param oldSeqNum old sequence number
* @param newSeqNum cwnewold sequence number
*/
SeqNumPair(final Long oldSeqNum, final Long newSeqNum) {
this.oldSeqNum = oldSeqNum;
this.newSeqNum = newSeqNum;
}
}
}
| 1,969 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/Pair.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common;
import mslcli.common.util.SharedUtil;
/**
* <p>Generic Pair class. Some or all values can be null.</p>
*
* @author Vadim Spector <[email protected]>
*/
public final class Pair<X,Y> {
/** first value of type X */
public final X x;
/** second value of type Y */
public final Y y;
/**
* Constructor.
*
* @param x first value of type X
* @param y second value of type Y
*/
public Pair(X x, Y y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return SharedUtil.toString(this);
}
}
| 1,970 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/Triplet.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common;
import mslcli.common.util.SharedUtil;
/**
* <p>Generic data object class for holding 3 values. Values can be null.</p>
*
* @author Vadim Spector <[email protected]>
*/
public final class Triplet<X,Y,Z> {
/** first value of type X */
public final X x;
/** second value of type Y */
public final Y y;
/** third value of type Z */
public final Z z;
/**
* Constructor.
*
* @param x first value of type X
* @param y second value of type Y
* @param z second value of type Z
*/
public Triplet(X x, Y y, Z z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public String toString() {
return SharedUtil.toString(this);
}
}
| 1,971 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/IllegalCmdArgumentRuntimeException.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common;
/**
* <p>Exception for invalid MSL CLI command line arguments.</p>
*
* @author Vadim Spector <[email protected]>
*/
public class IllegalCmdArgumentRuntimeException extends RuntimeException {
/** for proper serialization */
private static final long serialVersionUID = -6754762182112853406L;
/**
* @param cause exception cause
*/
public IllegalCmdArgumentRuntimeException(Throwable cause) {
super(cause);
}
}
| 1,972 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/CmdArguments.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import com.netflix.msl.MslConstants;
import mslcli.common.util.SharedUtil;
/**
* <p>
* MSL CLI command-line arguments parser, validator, and accessor class.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public final class CmdArguments {
// parameters
/** interactive mode */
public static final String P_INT = "-int" ;
/** configuration file */
public static final String P_CFG = "-cfg" ;
/** remote url */
public static final String P_URL = "-url" ;
/** entity id */
public static final String P_EID = "-eid" ;
/** user id */
public static final String P_UID = "-uid" ;
/** user authentication scheme */
public static final String P_UAS = "-uas" ;
/** key exchange type */
public static final String P_KX = "-kx" ;
/** key exchange mechanism */
public static final String P_KXM = "-kxm" ;
/** message encrypted */
public static final String P_ENC = "-enc" ;
/** message integrity protected */
public static final String P_SIG = "-sig" ;
/** message non-replayable */
public static final String P_NREP = "-nrep";
/** input message payload file */
public static final String P_IF = "-if" ;
/** output message payload file */
public static final String P_OF = "-of" ;
/** input message payload text */
public static final String P_MSG = "-msg" ;
/** pre-shared key file path */
public static final String P_PSK = "-psk" ;
/** MGK key file path */
public static final String P_MGK = "-mgk" ;
/** MSL store file path */
public static final String P_MST = "-mst" ;
/** entity authentication scheme */
public static final String P_EAS = "-eas" ;
/** verbose */
public static final String P_V = "-v" ;
/** send message N times */
public static final String P_NSND = "-nsnd";
/** list of supported arguments */
private static final List<String> supportedArguments =
Collections.unmodifiableList(new ArrayList<String>(Arrays.asList(
P_INT,
P_CFG,
P_URL,
P_EID,
P_EAS,
P_KX,
P_KXM,
P_UID,
P_UAS,
P_PSK,
P_MGK,
P_MST,
P_ENC,
P_SIG,
P_NREP,
P_IF,
P_OF,
P_MSG,
P_NSND,
P_V
)));
/** prefix for ad-hock properties that can be set for functionality extensions */
private static final String EXT_PREFIX = "-ext.";
/** separator for ad-hock property names */
private static final String EXT_SEP = ".";
/** order of listing of supported arguments */
private static final Map<String,Integer> supportedArgumentsRank = rankSupportedArguments();
/**
* @return mapping between argument name and its rank
*/
private static Map<String,Integer> rankSupportedArguments() {
final Map<String,Integer> hm = new HashMap<String,Integer>();
int i = 0;
for (String key : supportedArguments) {
hm.put(key, i++);
}
return Collections.unmodifiableMap(hm);
}
/**
* @param key propertry name
* @return property order of preference
*/
private static int getArgRank(final String key) {
return supportedArgumentsRank.containsKey(key) ? supportedArgumentsRank.get(key) : -1;
}
/**
* comparator class for listing arguments in preferable order
*/
private static final class ArgComparator implements Comparator<String> {
@Override
public int compare(String x, String y) {
final int rx = getArgRank(x);
final int ry = getArgRank(y);
if (rx != -1 && ry != -1) {
return (rx - ry);
} else if (rx != -1) {
return -1;
} else if (ry != -1) {
return 1;
} else {
return x.compareTo(y);
}
}
@Override
public boolean equals(Object o) {
return this == o;
}
@Override
public int hashCode() {
throw new UnsupportedOperationException();
}
}
/** arg comparator */
private static final Comparator<String> argComparator = new ArgComparator();
/** underlying representation of arguments */
private final Map<String,String> argMap;
/**
* Ctor.
*
* @param args array of arguments
* @throws IllegalCmdArgumentException
*/
public CmdArguments(final String[] args) throws IllegalCmdArgumentException {
if (args == null) {
throw new IllegalCmdArgumentException("NULL args");
}
this.argMap = new HashMap<String,String>();
String param = null;
String value = null;
for (String s : args) {
// one of the supported parameters or extension (ad hock) parameter
if (supportedArguments.contains(s) || s.startsWith(EXT_PREFIX)) {
// already occured - error
if (argMap.containsKey(s)) {
throw new IllegalCmdArgumentException("Multiple Occurences of " + s);
}
// expected value, not parameter
if (param != null) {
throw new IllegalCmdArgumentException("Missing Value for " + param);
}
// ok, new parameter; previous ones were successfully parsed
param = s;
// looks like partameter, but not one of the supported ones - error
} else if (s.startsWith("-") && (s.length() > 1)) {
throw new IllegalCmdArgumentException("Illegal Option " + s);
// if not a parameter, then must be a value
} else if (param != null) {
value = s.equals("-") ? null : s; // special case "-" for deleting the value
argMap.put(param, value);
param = null;
value = null;
// looks like parameter value, but next parameter is expected
} else {
throw new IllegalCmdArgumentException("Unexpected Value \"" + s + "\"");
}
}
if (param != null) {
throw new IllegalCmdArgumentException("Missing Value for Option \"" + param + "\"");
}
}
/**
* Copy Ctor.
*
* @param other another CmdArguments instance
* @throws IllegalCmdArgumentException
*/
public CmdArguments(final CmdArguments other) throws IllegalCmdArgumentException {
if (other == null) {
throw new IllegalCmdArgumentException("NULL CmdArguments object passed for copying");
}
this.argMap = new HashMap<String,String>();
this.argMap.putAll(other.argMap);
}
/**
* @return all parameters as unmodifiable Map
*/
public String getParameters() {
final Map<String,String> m = new TreeMap<String,String>(argComparator);
m.putAll(argMap);
final StringBuilder sb = new StringBuilder();
for (final Map.Entry<String,String> entry : m.entrySet()) {
sb.append(entry.getKey()).append(' ').append(entry.getValue()).append(' ');
}
return sb.toString();
}
/**
* merge parameters from another CmdArguments instance
* @param other another CmdArguments instance to merge parameters from
* @throws IllegalCmdArgumentException
*/
public void merge(CmdArguments other) throws IllegalCmdArgumentException {
if (other == null) {
throw new IllegalArgumentException("NULL CmdArguments argument");
}
if (other.argMap.containsKey(P_CFG)) {
throw new IllegalCmdArgumentException("Cannot reset Configuration File");
}
if (other.argMap.containsKey(P_INT)) {
throw new IllegalCmdArgumentException("Cannot reset Interactive Mode");
}
if (other.argMap.containsKey(P_PSK)) {
throw new IllegalCmdArgumentException("Cannot add PSK file interactively");
}
if (other.argMap.containsKey(P_MST) && argMap.containsKey(P_MST)) {
throw new IllegalCmdArgumentException("Cannot reset MSL Store File");
}
for (Map.Entry<String,String> entry : other.argMap.entrySet()) {
if (entry.getValue() != null) {
argMap.put(entry.getKey(), entry.getValue());
} else {
argMap.remove(entry.getKey());
}
}
}
/**
* @return interactive mode true/false
*/
public boolean isInteractive() {
return getBoolean(P_INT, false);
}
/**
* @return remote URL - must exist
* @throws IllegalCmdArgumentException
*/
public URL getUrl() throws IllegalCmdArgumentException {
final String url = getRequiredValue(P_URL);
try {
return new URL(url);
} catch (MalformedURLException e) {
throw new IllegalCmdArgumentException("Invalid URL " + url, e);
}
}
/**
* @return configuration file path - must exist and be a regular file
* @throws IllegalCmdArgumentException
*/
public String getConfigFilePath() throws IllegalCmdArgumentException {
final String file = getRequiredValue(P_CFG);
if (SharedUtil.isExistingFile(file)) {
return file;
} else {
throw new IllegalCmdArgumentException("Not a File: " + file);
}
}
/**
* @return file path to read request payload from. Must exist and be a regular file.
* @throws IllegalCmdArgumentException
*/
public String getPayloadInputFile() throws IllegalCmdArgumentException {
final String file = argMap.get(P_IF);
if (file == null) {
return null;
}
if (SharedUtil.isExistingFile(file)) {
return file;
} else {
throw new IllegalCmdArgumentException("Not a File: " + file);
}
}
/**
* @return file path to write response payload to
* @throws IllegalCmdArgumentException
*/
public String getPayloadOutputFile() throws IllegalCmdArgumentException {
final String file = argMap.get(P_OF);
if (file == null) {
return null;
}
if (SharedUtil.isValidNewFile(file)) {
return file;
} else if (SharedUtil.isExistingFile(file)) {
throw new IllegalCmdArgumentException("Cannot Overwrite Existing File: " + file);
} else {
throw new IllegalCmdArgumentException("Invalid File Path: " + file);
}
}
/**
* @return file path to PSK file. If defined, must be a file.
* @throws IllegalCmdArgumentException
*/
public String getPskFile() throws IllegalCmdArgumentException {
final String file = argMap.get(P_PSK);
if (file == null) {
return null;
}
if (SharedUtil.isExistingFile(file)) {
return file;
} else {
throw new IllegalCmdArgumentException("Not a File: " + file);
}
}
/**
* @return file path to MGK file. If defined, must be a file.
* @throws IllegalCmdArgumentException
*/
public String getMgkFile() throws IllegalCmdArgumentException {
final String file = argMap.get(P_MGK);
if (file == null) {
return null;
}
if (SharedUtil.isExistingFile(file)) {
return file;
} else {
throw new IllegalCmdArgumentException("Not a File: " + file);
}
}
/**
* @return file path to PSK file. If defined, must be a file.
* @throws IllegalCmdArgumentException
*/
public String getMslStorePath() throws IllegalCmdArgumentException {
final String file = argMap.get(P_MST);
if (file == null) {
return null;
}
if (SharedUtil.isExistingFile(file) || SharedUtil.isValidNewFile(file)) {
return file;
} else {
throw new IllegalCmdArgumentException("Invalid File Path: " + file);
}
}
/**
* @return payload text message
*/
public byte[] getPayloadMessage() {
final String s = argMap.get(P_MSG);
return (s != null) ? s.getBytes(MslConstants.DEFAULT_CHARSET) : null;
}
/**
* @return entityId - must be initialized
* @throws IllegalCmdArgumentException
*/
public String getEntityId() throws IllegalCmdArgumentException {
return getRequiredValue(P_EID);
}
/**
* @return entityId or null if not initialized
* @throws IllegalCmdArgumentException
*/
public String getOptEntityId() {
return argMap.get(P_EID);
}
/**
* @return whether entity identity key is defined (value can be null)
*/
public boolean hasEntityId() {
return argMap.containsKey(P_EID);
}
/**
* @return userId - can be uninitialized
*/
public String getUserId() {
return argMap.get(P_UID);
}
/**
* @return user authentication scheme - can be uninitialized
*/
public String getUserAuthenticationScheme() {
return argMap.get(P_UAS);
}
/**
* @return whether message needs encryption
*/
public boolean isEncrypted() {
return getBoolean(P_ENC, true);
}
/**
* @return whether message needs integrity protection
*/
public boolean isIntegrityProtected() {
return getBoolean(P_SIG, true);
}
/**
* @return whether message needs to be non-replayable
*/
public boolean isNonReplayable() {
return getBoolean(P_NREP, false);
}
/**
* @return get entity authentication scheme
* @throws IllegalCmdArgumentException if property is not defined
*/
public String getEntityAuthenticationScheme() throws IllegalCmdArgumentException {
return getRequiredValue(P_EAS);
}
/**
* @return key exchange scheme
*/
public String getKeyExchangeScheme() {
return argMap.get(P_KX);
}
/**
* @return key exchange mechanism
*/
public String getKeyExchangeMechanism() {
return argMap.get(P_KXM);
}
/**
* @return verbose mode y/n
*/
public int getNumSends() {
return getInteger(P_NSND, 1);
}
/**
* @return verbose mode y/n
*/
public boolean isVerbose() {
return getBoolean(P_V, false);
}
/**
* @param name name of the boolean property
* @param def default value of the boolean property
* @return property parsed as boolean or default value if it does not exist
*/
private boolean getBoolean(final String name, final boolean def) {
final String s = argMap.get(name);
return (s != null) ? Boolean.parseBoolean(s) : def;
}
/**
* @param name name of the integer property
* @param def default value of the integer property
* @return property parsed as integer or default value if it does not exist
*/
private int getInteger(final String name, final int def) {
final String s = argMap.get(name);
return (s != null) ? Integer.parseInt(s) : def;
}
/**
* @param name name of the mandatory property
* @return property value
* @throws IllegalCmdArgumentException if property is not defined
*/
private String getRequiredValue(final String name) throws IllegalCmdArgumentException {
final String s = argMap.get(name);
if (s != null) {
return s;
} else {
throw new IllegalCmdArgumentException("Missing Required Argument " + name);
}
}
/**
* @param group group of properties. property name prefix is composed as EXT_PREFIX + group.
* @return Map of properties with stripped off preffixes
*/
public Map<String,String> getExtensionProperties(String group) {
group = EXT_PREFIX + group + EXT_SEP;
final Map<String,String> m = new HashMap<String,String>();
for (Map.Entry<String,String> entry : argMap.entrySet()) {
if (entry.getKey().startsWith(group)) {
m.put(entry.getKey().substring(group.length()), entry.getValue());
}
}
return m;
}
@Override
public String toString() {
return SharedUtil.toString(this);
}
}
| 1,973 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/MslConfig.java
|
/**
* Copyright (c) 2014-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import mslcli.common.entityauth.EntityAuthenticationHandle;
import mslcli.common.keyx.KeyExchangeHandle;
import mslcli.common.msg.MessageConfig;
import mslcli.common.userauth.UserAuthenticationHandle;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.MslStoreWrapper;
import mslcli.common.util.SharedUtil;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslStore;
import com.netflix.msl.util.SimpleMslStore;
/**
* <p>
* The common configuration class for MSl client and server.
* Instance of this class is specific to a given entity ID.
* If entity ID changes, new instance of MslConfig must be used.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public abstract class MslConfig {
/**
* Ctor
* @param appCtx application context
* @param args command line arguments
* @param authutils authentication utils
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
protected MslConfig(final AppContext appCtx,
final CmdArguments args,
final AuthenticationUtils authutils)
throws ConfigurationException, IllegalCmdArgumentException
{
// set application context
this.appCtx = appCtx;
// set arguments
this.args = args;
// set entity ID
this.entityId = args.getEntityId();
// set authutils
this.authutils = authutils;
// set MslStore
if (args.getMslStorePath() != null) {
this.mslStorePath = args.getMslStorePath().replace("{eid}", entityId);
} else {
this.mslStorePath = null;
}
this.mslStoreWrapper = new AppMslStoreWrapper(appCtx, entityId, initMslStore(appCtx, mslStorePath));
this.eadMap = new HashMap<String,EntityAuthenticationData>();
}
/**
* @return entity identity
*/
public final String getEntityId() {
return entityId;
}
@Override
public String toString() {
return SharedUtil.toString(this, entityId);
}
/**
* validate current CmdArguments data in respect to entity, user, and key exchange handles
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public void validate() throws IllegalCmdArgumentException {
validateEntityAuthenticationArgs();
validateUserAuthenticationArgs();
validateKeyExchangeArgs();
}
/**
* @return message config parameters
*/
public MessageConfig getMessageConfig() {
// set message mslProperties
final MessageConfig cfg = new MessageConfig();
cfg.isEncrypted = args.isEncrypted();
cfg.isIntegrityProtected = args.isIntegrityProtected();
cfg.isNonReplayable = args.isNonReplayable();
return cfg;
}
/**
* @return user ID
*/
/* ================================== ENTITY AUTHENTICATION APIs ================================================ */
/**
* @return entity authentication data
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public final EntityAuthenticationData getEntityAuthenticationData() throws ConfigurationException, IllegalCmdArgumentException {
String easName = args.getEntityAuthenticationScheme();
if (easName == null || easName.trim().length() == 0)
throw new IllegalCmdArgumentException("Entity Authentication Scheme is not set");
easName = easName.trim();
for(final EntityAuthenticationHandle eah : appCtx.getEntityAuthenticationHandles()) {
if (easName.equals(eah.getScheme().name())) {
synchronized (eadMap) {
EntityAuthenticationData ead = eadMap.get(easName);
if (ead == null) {
eadMap.put(easName, ead = eah.getEntityAuthenticationData(appCtx, args));
appCtx.info(String.format("%s: Generated %s", this, SharedUtil.toString(ead, easName)));
}
return ead;
}
}
}
final List<String> schemes = getEntityAuthenticationSchemeNames();
throw new IllegalCmdArgumentException(String.format("Unsupported Entity Authentication Scheme %s, Supported: %s", easName, schemes));
}
/**
* @return entity authentication factories
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public final Set<EntityAuthenticationFactory> getEntityAuthenticationFactories()
throws ConfigurationException, IllegalCmdArgumentException
{
final Set<EntityAuthenticationFactory> entityAuthFactories = new HashSet<EntityAuthenticationFactory>();
for (final EntityAuthenticationHandle adh : appCtx.getEntityAuthenticationHandles()) {
entityAuthFactories.add(adh.getEntityAuthenticationFactory(appCtx, args, authutils));
}
return Collections.<EntityAuthenticationFactory>unmodifiableSet(entityAuthFactories);
}
/**
* @return registered entity authentication scheme names
*/
private List<String> getEntityAuthenticationSchemeNames() {
final List<String> schemes = new ArrayList<String>();
for (final EntityAuthenticationHandle eah : appCtx.getEntityAuthenticationHandles())
schemes.add(eah.getScheme().name());
return schemes;
}
/**
* validate entity authentication arguments
* @throws IllegalCmdArgumentException
*/
private void validateEntityAuthenticationArgs() throws IllegalCmdArgumentException {
String easName = args.getEntityAuthenticationScheme();
if (easName != null && easName.trim().length() != 0) {
easName = easName.trim();
final List<String> schemes = getEntityAuthenticationSchemeNames();
if (!schemes.contains(easName))
throw new IllegalCmdArgumentException(String.format("Unsupported Entity Authentication Scheme %s, Supported: %s", easName, schemes));
}
}
/* ================================== USER AUTHENTICATION APIs ================================================ */
/**
* @return user authentication data
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public UserAuthenticationData getUserAuthenticationData()
throws ConfigurationException, IllegalCmdArgumentException
{
final UserAuthenticationHandle uah = getUserAuthenticationHandle();
final UserAuthenticationData uad = uah.getUserAuthenticationData(appCtx, args, getMslStore());
if (uad != null)
appCtx.info(String.format("%s: Generated %s", this, SharedUtil.toString(uad, uad.getScheme())));
return uad;
}
/**
* @return current user ID
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public String getUserId()
throws ConfigurationException, IllegalCmdArgumentException
{
final UserAuthenticationHandle uah = getUserAuthenticationHandle();
return uah.getUserId(appCtx, args);
}
/**
* @return UserAuthenticationHandle for a given user authentication scheme
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
private UserAuthenticationHandle getUserAuthenticationHandle()
throws ConfigurationException, IllegalCmdArgumentException
{
final String uasName = args.getUserAuthenticationScheme();
if (uasName == null || uasName.trim().length() == 0)
throw new IllegalCmdArgumentException("User Authentication Scheme is not set");
for (final UserAuthenticationHandle uah : appCtx.getUserAuthenticationHandles()) {
if (uah.getScheme().name().equals(uasName)) {
return uah;
}
}
// UserAuthenticationHandle not found. Generate helpful exception
final List<String> schemes = getUserAuthenticationSchemeNames();
throw new IllegalCmdArgumentException(String.format("Unsupported User Authentication Scheme %s, Supported: %s", uasName, schemes));
}
/**
* @return user authentication factories
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public final Set<UserAuthenticationFactory> getUserAuthenticationFactories()
throws ConfigurationException, IllegalCmdArgumentException
{
final Set<UserAuthenticationFactory> userAuthFactories = new HashSet<UserAuthenticationFactory>();
for (final UserAuthenticationHandle uah : appCtx.getUserAuthenticationHandles()) {
userAuthFactories.add(uah.getUserAuthenticationFactory(appCtx, args, authutils));
}
return Collections.<UserAuthenticationFactory>unmodifiableSet(userAuthFactories);
}
/**
* @return registered user authentication scheme names
*/
private List<String> getUserAuthenticationSchemeNames() {
final List<String> schemes = new ArrayList<String>();
for (final UserAuthenticationHandle uah : appCtx.getUserAuthenticationHandles())
schemes.add(uah.getScheme().name());
return schemes;
}
/**
* validate user authentication arguments
* @throws IllegalCmdArgumentException
*/
private void validateUserAuthenticationArgs() throws IllegalCmdArgumentException {
String uasName = args.getUserAuthenticationScheme();
if (uasName != null && uasName.trim().length() != 0) {
uasName = uasName.trim();
final List<String> schemes = getUserAuthenticationSchemeNames();
if (!schemes.contains(uasName))
throw new IllegalCmdArgumentException(String.format("Unsupported User Authentication Scheme %s, Supported: %s", uasName, schemes));
}
}
/* ================================== KEY EXCHANGE APIs ================================================ */
/**
* @return key request data
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
* @throws MslKeyExchangeException
*/
public KeyRequestData getKeyRequestData()
throws ConfigurationException, IllegalCmdArgumentException, MslKeyExchangeException
{
final String kxsName = args.getKeyExchangeScheme();
if (kxsName == null || kxsName.trim().isEmpty()) {
throw new IllegalCmdArgumentException("NULL Key Exchange Type");
}
final String kxmName = args.getKeyExchangeMechanism();
for (final KeyExchangeHandle kxh : appCtx.getKeyExchangeHandles()) {
if (kxh.getScheme().name().equals(kxsName)) {
final KeyRequestData krd = kxh.getKeyRequestData(appCtx, args);
appCtx.info(String.format("%s: Generated %s", this, SharedUtil.toString(krd, krd.getKeyExchangeScheme(), kxmName)));
return krd;
}
}
final List<String> schemes = getKeyExchangeSchemeNames();
throw new IllegalCmdArgumentException(String.format("Unsupported Key Exchange Scheme %s, Supported: %s", kxsName, schemes));
}
/**
* @return key exchange factories
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public final SortedSet<KeyExchangeFactory> getKeyExchangeFactories()
throws ConfigurationException, IllegalCmdArgumentException
{
// key exchange handles
final List<KeyExchangeFactory> keyxFactoriesList = new ArrayList<KeyExchangeFactory>();
final List<KeyExchangeHandle> keyxHandles = appCtx.getKeyExchangeHandles();
for (final KeyExchangeHandle kxh : keyxHandles) {
keyxFactoriesList.add(kxh.getKeyExchangeFactory(appCtx, args, authutils));
}
final KeyExchangeFactoryComparator keyxFactoryComparator = new KeyExchangeFactoryComparator(keyxFactoriesList);
final TreeSet<KeyExchangeFactory> keyxFactoriesSet = new TreeSet<KeyExchangeFactory>(keyxFactoryComparator);
keyxFactoriesSet.addAll(keyxFactoriesList);
return Collections.unmodifiableSortedSet(keyxFactoriesSet);
}
/**
* @return registered user authentication scheme names
*/
private List<String> getKeyExchangeSchemeNames() {
final List<String> schemes = new ArrayList<String>();
for (final KeyExchangeHandle kxh : appCtx.getKeyExchangeHandles())
schemes.add(kxh.getScheme().name());
return schemes;
}
/**
* validate key exchange arguments
* @throws IllegalCmdArgumentException
*/
private void validateKeyExchangeArgs() throws IllegalCmdArgumentException {
String kxsName = args.getKeyExchangeScheme();
if (kxsName != null && kxsName.trim().length() != 0) {
kxsName = kxsName.trim();
final List<String> schemes = getKeyExchangeSchemeNames();
if (!schemes.contains(kxsName))
throw new IllegalCmdArgumentException(String.format("Unsupported Key Exchange Scheme %s, Supported: %s", kxsName, schemes));
}
}
/**
* Key exchange factory comparator. The purpose is to list key exchange schemes in order of preference.
*/
private static class KeyExchangeFactoryComparator implements Comparator<KeyExchangeFactory> {
/** Scheme priorities. Lower values are higher priority. */
private final Map<KeyExchangeScheme,Integer> schemePriorities = new HashMap<KeyExchangeScheme,Integer>();
/**
* Create a new key exchange factory comparator.
* @param factories factories in order of their preference
*/
public KeyExchangeFactoryComparator(final List<KeyExchangeFactory> factories) {
int priority = 0;
for (final KeyExchangeFactory f : factories) {
schemePriorities.put(f.getScheme(), priority++);
}
}
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(final KeyExchangeFactory a, final KeyExchangeFactory b) {
final KeyExchangeScheme schemeA = a.getScheme();
final KeyExchangeScheme schemeB = b.getScheme();
final Integer priorityA = schemePriorities.get(schemeA);
final Integer priorityB = schemePriorities.get(schemeB);
return priorityA.compareTo(priorityB);
}
}
/* ================================== MSL STORE APIs ================================================ */
/**
* @return entity-specific instance of MslStore
*/
public final MslStore getMslStore() {
return mslStoreWrapper;
}
/**
* persist MSL store
*
* @throws IOException
*/
public void saveMslStore() throws IOException {
if (mslStorePath == null) {
appCtx.info(String.format("%s: Not Persisting In-Memory MSL Store", this));
return;
}
synchronized (mslStoreWrapper) {
try {
SharedUtil.saveToFile(mslStorePath, SharedUtil.marshalMslStore((SimpleMslStore)mslStoreWrapper.getMslStore()), true /*overwrite*/);
} catch (final MslEncodingException e) {
throw new IOException("Error Saving MslStore file " + mslStorePath, e);
} catch (final MslEncoderException e) {
throw new IOException("Error Saving MslStore file " + mslStorePath, e);
}
appCtx.info(String.format("%s: MSL Store %s Updated", this, mslStorePath));
}
}
/**
* Initialize MslStore
*
* @param appCtx application context
* @param mslStorePath MSL store path
* @return MSL store
* @throws ConfigurationException
*/
private static SimpleMslStore initMslStore(final AppContext appCtx, final String mslStorePath)
throws ConfigurationException
{
if (mslStorePath == null) {
appCtx.info("Creating Non-Persistent MSL Store");
return new SimpleMslStore();
} else if (SharedUtil.isExistingFile(mslStorePath)) {
appCtx.info("Loading Existing MSL Store " + mslStorePath);
try {
return (SimpleMslStore)SharedUtil.unmarshalMslStore(SharedUtil.readFromFile(mslStorePath));
} catch (final Exception e) {
throw new ConfigurationException("Error Loading MSL Store " + mslStorePath, e);
}
} else if (SharedUtil.isValidNewFile(mslStorePath)) {
appCtx.info("Creating New MSL Store " + mslStorePath);
return new SimpleMslStore();
} else {
throw new IllegalArgumentException("MSL Store: Invalid File Path: " + mslStorePath);
}
}
/**
* This is a class to serve as an interceptor to all MslStore calls.
* It can override only the methods in MslStore the app cares about.
* This sample implementation just prints out the information about
* calling some selected MslStore methods.
*/
private static final class AppMslStoreWrapper extends MslStoreWrapper {
/**
* @param appCtx application context
* @param entityId entity identity
* @param mslStore MSL store
*/
private AppMslStoreWrapper(final AppContext appCtx, final String entityId, final MslStore mslStore) {
super(mslStore);
if (appCtx == null) {
throw new IllegalArgumentException("NULL app context");
}
this.appCtx = appCtx;
this.entityId = entityId;
}
@Override
public long getNonReplayableId(final MasterToken masterToken) {
final long nextId = super.getNonReplayableId(masterToken);
appCtx.info(String.format("%s: %s - next non-replayable id %d", this, SharedUtil.getMasterTokenInfo(masterToken), nextId));
return nextId;
}
@Override
public void setCryptoContext(final MasterToken masterToken, final ICryptoContext cryptoContext) {
if (masterToken == null) {
appCtx.info(String.format("%s: setting crypto context with NULL MasterToken???", this));
} else {
appCtx.info(String.format("%s: %s %s", this,
(cryptoContext != null)? "Adding" : "Removing", SharedUtil.getMasterTokenInfo(masterToken)));
}
super.setCryptoContext(masterToken, cryptoContext);
}
@Override
public void removeCryptoContext(final MasterToken masterToken) {
appCtx.info(String.format("%s: Removing Crypto Context for %s", this, SharedUtil.getMasterTokenInfo(masterToken)));
super.removeCryptoContext(masterToken);
}
@Override
public void clearCryptoContexts() {
appCtx.info(String.format("%s: Clear Crypto Contexts", this));
super.clearCryptoContexts();
}
@Override
public void addUserIdToken(final String userId, final UserIdToken userIdToken) throws MslException {
appCtx.info(String.format("%s: Adding %s for userId %s", this, SharedUtil.getUserIdTokenInfo(userIdToken), userId));
super.addUserIdToken(userId, userIdToken);
}
@Override
public void removeUserIdToken(final UserIdToken userIdToken) {
appCtx.info(String.format("%s: Removing %s", this, SharedUtil.getUserIdTokenInfo(userIdToken)));
super.removeUserIdToken(userIdToken);
}
@Override
public String toString() {
return String.format("%s{%s}", super.toString(), entityId);
}
/** application context */
private final AppContext appCtx;
/** entity identity */
private final String entityId;
}
/* ================================== INSTANCE VARIABLES ================================================ */
/** application context */
protected final AppContext appCtx;
/** entity identity */
protected final String entityId;
/** command arguments */
protected final CmdArguments args;
/** authentication utilities */
protected final AuthenticationUtils authutils;
/** MSL store */
private final MslStoreWrapper mslStoreWrapper;
/** MSL store file path */
private final String mslStorePath;
/** entity authentication data per scheme */
private final Map<String,EntityAuthenticationData> eadMap;
}
| 1,974 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/IllegalCmdArgumentException.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common;
/**
* <p>Exception for invalid MSL CLI command line arguments.</p>
*
* @author Vadim Spector <[email protected]>
*/
public class IllegalCmdArgumentException extends Exception {
/** for proper serialization */
private static final long serialVersionUID = -6754762182112853406L;
/** default ctor */
public IllegalCmdArgumentException() {
super();
}
/**
* @param message exception message
*/
public IllegalCmdArgumentException(String message) {
super(message);
}
/**
* @param message exception message
* @param cause exception cause
*/
public IllegalCmdArgumentException(String message, Throwable cause) {
super(message, cause);
}
/**
* @param cause exception cause
*/
public IllegalCmdArgumentException(Throwable cause) {
super(cause);
}
}
| 1,975 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/util/SharedUtil.java
|
/**
* Copyright (c) 2014-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.SortedSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Mac;
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.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.crypto.ClientMslCryptoContext;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.io.DefaultMslEncoderFactory;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.msg.MessageCapabilities;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslStore;
import com.netflix.msl.util.SimpleMslStore;
import mslcli.common.Triplet;
/**
* <p>Collection of utilities.</p>
*
* @author Vadim Spector <[email protected]>
*/
public final class SharedUtil {
/** to disable instantiation */
private SharedUtil() {}
/**
* extract useful info from MasterToken for display
*
* @param masterToken master token, can be null
* @return master token info as a string, or null if masterToken is null
*/
public static final String getMasterTokenInfo(final MasterToken masterToken) {
if (masterToken == null) {
return null;
}
final long t_now = System.currentTimeMillis();
final long t_rnw = (masterToken.getRenewalWindow().getTime() - t_now)/1000L;
final long t_exp = (masterToken.getExpiration().getTime() - t_now)/1000L;
return String.format("%s{ser_num %x, seq_num %x, renew %d sec, expire %d sec}",
getSimpleClassName(masterToken),
masterToken.getSerialNumber(),
masterToken.getSequenceNumber(),
t_rnw,
t_exp);
}
/**
* extract useful info from UserIdToken for display
*
* @param userIdToken user ID token, can be null
* @return user ID token info as a string, or null if userIdToken is null
*/
public static final String getUserIdTokenInfo(final UserIdToken userIdToken) {
if (userIdToken == null) {
return null;
}
final long t_now = System.currentTimeMillis();
final long t_rnw = (userIdToken.getRenewalWindow().getTime() - t_now)/1000L;
final long t_exp = (userIdToken.getExpiration().getTime() - t_now)/1000L;
return String.format("%s{user %s, ser_num %x, mt_ser_num %x, renew %d sec, expire %d sec}",
getSimpleClassName(userIdToken),
(userIdToken.getUser() != null) ? userIdToken.getUser().getEncoded() : "opaque",
userIdToken.getSerialNumber(),
userIdToken.getMasterTokenSerialNumber(),
t_rnw,
t_exp);
}
/**
* extract useful info from ServiceToken for display
*
* @param serviceToken service token, can be null
* @return service token info as a string, or null if serviceToken is null
*/
public static final String getServiceTokenInfo(final ServiceToken serviceToken) {
if (serviceToken == null) {
return null;
}
return String.format("%s{name %s, mt_ser_num %x, ut_ser_num %x, enc %b}",
getSimpleClassName(serviceToken),
serviceToken.getName(),
serviceToken.getMasterTokenSerialNumber(),
serviceToken.getUserIdTokenSerialNumber(),
serviceToken.isEncrypted());
}
/**
* IO Helper: read input stream into byte array
*
* @param in input stream
* @return byte array read from the input stream
* @throws IOException
*/
public static byte[] readIntoArray(final InputStream in) throws IOException {
assertNotNull(in, "Input Stream");
final ByteArrayOutputStream out = new ByteArrayOutputStream();
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
return out.toByteArray();
}
/**
* IO Helper: read single line from STDIN
*
* @param prompt reading prompt
* @return user input converted to a string
* @throws IOException
*/
public static String readInput(final String prompt) throws IOException {
assertNotNull(prompt, "prompt");
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in, MslConstants.DEFAULT_CHARSET));
System.out.print(prompt.trim() + "> ");
return br.readLine();
}
/**
* IO Helper: read parameter from STDIN
*
* @param prompt reading prompt
* @param def default value accepted if no input is supplied
* @return user input converted to a string
* @throws IOException
*/
public static String readParameter(final String prompt, final String def) throws IOException {
assertNotNull(prompt, "prompt");
final String value = readInput(String.format("%s[%s]", prompt, def));
if (value == null || value.isEmpty()) {
return def;
} else if (value.trim().isEmpty()) {
return null;
} else {
return value.trim();
}
}
/**
* IO Helper: read boolean value from STDIN.
* Repeat prompt till one of the valid values is entered.
*
* @param name reading prompt
* @param def default value accepted if no input is supplied
* @param yesStr input accepted as true
* @param noStr input accepted as false
* @return user input converted to a string
* @throws IOException
*/
public static boolean readBoolean(final String name, final boolean def, final String yesStr, final String noStr) throws IOException {
assertNotNull(name, "name");
assertNotNull(yesStr, "yesStr");
assertNotNull(noStr, "noStr");
String value;
do {
value = readInput(String.format("%s[%s]", name, def ? "y" : "n"));
if (value.trim().isEmpty()) {
return def;
} else if (yesStr.equalsIgnoreCase(value)) {
return true;
} else if (noStr.equalsIgnoreCase(value)) {
return false;
}
} while (true);
}
/**
* Helper: convert hex string into byte array
*
* @param hex byte array hex-encoded as a string
* @return byte array
*/
public static byte[] hexStringToByteArray(final String hex) {
assertNotNull(hex, "hex string");
final int len = hex.length();
if (len % 2 != 0) {
throw new IllegalArgumentException("hex-encoded string size " + len + " - must be even");
}
final byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i ), 16) << 4)
+ Character.digit(hex.charAt(i+1), 16) );
}
return data;
}
/**
* split string of space-separated tokens into a List of tokens, treating quoted group of tokens as a single token
*
* @param str input string
* @return array of tokens
*/
public static String[] split(final String str) {
final List<String> list = new ArrayList<String>();
final Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(str);
while (m.find()) {
list.add(m.group(1).replace("\"", ""));
}
return list.toArray(new String[list.size()]);
}
/**
* Helper: get innermost cause exception
*
* @param t Throwable
* @return innermost cause Throwable
*/
public static Throwable getRootCause(Throwable t) {
assertNotNull(t, "throwable");
while (t.getCause() != null) {
t = t.getCause();
}
return t;
}
/**
* load properties from file
*
* @param file file name
* @return properties loaded from this file
* @throws IOException
*/
public static Properties loadPropertiesFromFile(final String file) throws IOException {
assertNotNull(file, "file");
final File f = new File(file);
if (!f.isFile()) {
throw new IllegalArgumentException(file + " not a file");
}
final Properties p = new Properties();
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
fis = new FileInputStream(f);
isr = new InputStreamReader(fis, MslConstants.DEFAULT_CHARSET);
br = new BufferedReader(isr);
p.load(br);
} finally {
if (fis != null) try { fis.close(); } catch (final IOException ignore) {}
if (isr != null) try { isr.close(); } catch (final IOException ignore) {}
if (br != null) try { br.close(); } catch (final IOException ignore) {}
}
return p;
}
/**
* load file content into a byte array
*
* @param file file path
* @return file content as byte array
* @throws IOException
*/
public static byte[] readFromFile(final String file) throws IOException {
assertNotNull(file, "file");
final File f = new File(file);
if (!f.isFile()) {
throw new IllegalArgumentException(file + " not a file");
}
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
return readIntoArray(fis);
} finally {
if (fis != null) try { fis.close(); } catch (final IOException ignore) {}
}
}
/**
* read special pre-shared key file that contains exactly 3 lines:
* entityId
* encryption key, base64-encoded
* hmac key, base64-encoded
*
* @param file PSK file path
* @return { entityId, encryption_key, hmac_key } triplet
* @throws IOException
*/
public static Triplet<String,String,String> readPskFile(final String file) throws IOException {
final List<String> lines = readTextFile(file);
if (lines.size() != 3)
throw new IOException("Invalid PSK File " + file);
final String entityId = lines.get(0);
final String encKey = lines.get(1);
final String hmacKey = lines.get(2);
return new Triplet<String,String,String>(entityId.trim(), "b64:" + encKey.trim(), "b64:" + hmacKey.trim());
}
/**
* read text file into a list of strings
*
* @param file file path
* @return List of strings, each string representing a line of text
* @throws IOException
*/
public static List<String> readTextFile(final String file) throws IOException {
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
fis = new FileInputStream(file);
isr = new InputStreamReader(fis, MslConstants.DEFAULT_CHARSET);
br = new BufferedReader(isr);
String line;
final List<String> lines = new ArrayList<String>();
while ((line = br.readLine()) != null) {
lines.add(line);
}
return lines;
} finally {
if (fis != null) try { fis.close(); } catch (final IOException ignore) {}
if (isr != null) try { isr.close(); } catch (final IOException ignore) {}
if (br != null) try { br.close(); } catch (final IOException ignore) {}
}
}
/**
* save byte array into a file
*
* @param file file path
* @param data data to save into a file
* @param overwrite true if the existing file can be overwritten
* @throws IOException
*/
public static void saveToFile(final String file, final byte[] data, final boolean overwrite) throws IOException {
assertNotNull(file, "file");
assertNotNull(data, "data");
final File f = new File(file);
if (f.exists() && !overwrite) {
throw new IllegalArgumentException("cannot overwrite file " + file);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
fos.write(data);
} finally {
if (fos != null) try { fos.close(); } catch (final IOException ignore) {}
}
}
/**
* Serialize MslStore
*
* @param mslStore SimpleMslStore instance
* @return serialized MslStore
* @throws IOException
* @throws MslEncodingException
* @throws MslEncoderException
*/
public static byte[] marshalMslStore(final SimpleMslStore mslStore) throws IOException, MslEncodingException, MslEncoderException {
return MslStoreData.serialize(mslStore, new DummyMslContext());
}
/**
* Serialize MslStore
*
* @param mslStoreData MslStore blob
* @return serialized MslStore
* @throws IOException
* @throws MslEncodingException
* @throws MslException
* @throws MslEncoderException
*/
public static MslStore unmarshalMslStore(final byte[] mslStoreData) throws IOException, MslEncodingException, MslException, MslEncoderException {
return MslStoreData.deserialize(mslStoreData, new DummyMslContext());
}
/**
* this class is needed exclusively for deserialization of SimpleMslStore on the client side
*/
private static final class DummyMslContext extends MslContext {
@Override
public long getTime() {
return System.currentTimeMillis();
}
@Override
public Random getRandom() {
return new SecureRandom();
}
@Override
public boolean isPeerToPeer() {
throw new UnsupportedOperationException();
}
@Override
public MessageCapabilities getMessageCapabilities() {
throw new UnsupportedOperationException();
}
@Override
public EntityAuthenticationData getEntityAuthenticationData(final ReauthCode reauthCode) {
throw new UnsupportedOperationException();
}
@Override
public ICryptoContext getMslCryptoContext() throws MslCryptoException {
return mslCryptoContext;
}
@Override
public EntityAuthenticationFactory getEntityAuthenticationFactory(final EntityAuthenticationScheme scheme) {
throw new UnsupportedOperationException();
}
@Override
public UserAuthenticationFactory getUserAuthenticationFactory(final UserAuthenticationScheme scheme) {
throw new UnsupportedOperationException();
}
@Override
public TokenFactory getTokenFactory() {
throw new UnsupportedOperationException();
}
@Override
public KeyExchangeFactory getKeyExchangeFactory(final KeyExchangeScheme scheme) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet<KeyExchangeFactory> getKeyExchangeFactories() {
throw new UnsupportedOperationException();
}
@Override
public EntityAuthenticationScheme getEntityAuthenticationScheme(final String name) {
throw new UnsupportedOperationException();
}
@Override
public KeyExchangeScheme getKeyExchangeScheme(final String name) {
throw new UnsupportedOperationException();
}
@Override
public UserAuthenticationScheme getUserAuthenticationScheme(final String name) {
throw new UnsupportedOperationException();
}
@Override
public MslStore getMslStore() {
throw new UnsupportedOperationException();
}
@Override
public MslEncoderFactory getMslEncoderFactory() {
return encoderFactory;
}
/** MSL crypto context */
private final ICryptoContext mslCryptoContext = new ClientMslCryptoContext();
/** MSL encoder factory. */
private final MslEncoderFactory encoderFactory = new DefaultMslEncoderFactory();
}
/** Base64 utilities */
public static final class Base64Util {
/**
* @param encoded base64-encoded string
* @return decoded array
*/
public static byte[] decodeToByteArray(final String encoded) {
return Base64.decode(encoded);
}
/**
* @param encoded base64-encoded string
* @return decoded String
*/
public static String decode(final String encoded) {
return new String(Base64.decode(encoded), MslConstants.DEFAULT_CHARSET);
}
/**
* @param data byte array to be encoded
* @return base64 encoding of the input byte array
*/
public static String encode(final byte[] data) {
return Base64.encode(data);
}
/**
* @param data byte array to be encoded
* @return base64 encoding of the input byte array
*/
public static String encode(final String data) {
return Base64.encode(data.getBytes(MslConstants.DEFAULT_CHARSET));
}
}
/**
* extract useful info from MslException for display
*
* @param e MslException object
* @return useful info from MslException for display
*/
public static String getMslExceptionInfo(final MslException e) {
if (e == null) return null;
final MslError mErr = e.getError();
if (mErr != null) {
final ResponseCode respCode = mErr.getResponseCode();
if (respCode != null) {
return String.format("MslException: error_code %d, error_msg %s", respCode.intValue(), mErr.getMessage());
} else {
return String.format("MslException: error_msg %s", mErr.getMessage());
}
} else {
return String.format("MslException: %s", e.getMessage());
}
}
/** Wrapping key derivation algorithm salt. */
private static final byte[] SALT = {
(byte)0x02, (byte)0x76, (byte)0x17, (byte)0x98, (byte)0x4f, (byte)0x62, (byte)0x27, (byte)0x53,
(byte)0x9a, (byte)0x63, (byte)0x0b, (byte)0x89, (byte)0x7c, (byte)0x01, (byte)0x7d, (byte)0x69 };
/** Wrapping key derivation algorithm info. */
private static final byte[] INFO = {
(byte)0x80, (byte)0x9f, (byte)0x82, (byte)0xa7, (byte)0xad, (byte)0xdf, (byte)0x54, (byte)0x8d,
(byte)0x3e, (byte)0xa9, (byte)0xdd, (byte)0x06, (byte)0x7f, (byte)0xf9, (byte)0xbb, (byte)0x91, };
/** Wrapping key length in bytes. */
private static final int WRAPPING_KEY_LENGTH = 128 / Byte.SIZE;
/**
* Derives the pre-shared or model group keys AES-128 Key Wrap key from the
* provided AES-128 encryption key and HMAC-SHA256 key.
*
* @param encryptionKey the encryption key.
* @param hmacKey the HMAC key.
* @return the wrapping key.
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public static byte[] deriveWrappingKey(final byte[] encryptionKey, final byte[] hmacKey) throws InvalidKeyException, NoSuchAlgorithmException {
// Concatenate the keys.
final byte[] bits = Arrays.copyOf(encryptionKey, encryptionKey.length + hmacKey.length);
System.arraycopy(hmacKey, 0, bits, encryptionKey.length, hmacKey.length);
final Mac mac = Mac.getInstance("HmacSHA256");
// HMAC-SHA256 the keys with the salt as the HMAC key.
final SecretKey saltKey = new SecretKeySpec(SALT, JcaAlgorithm.AESKW);
mac.init(saltKey);
final byte[] intermediateBits = mac.doFinal(bits);
// HMAC-SHA256 the info with the intermediate key as the HMAC key.
final SecretKey intermediateKey = new SecretKeySpec(intermediateBits, JcaAlgorithm.AESKW);
mac.init(intermediateKey);
final byte[] finalBits = mac.doFinal(INFO);
// Grab the first 128 bits.
return Arrays.copyOf(finalBits, WRAPPING_KEY_LENGTH);
}
/**
* Compare two objects, one or both of which can be null. Null objects are considered equal.
*
* @param x first object
* @param y second object
* @return true if both objects are null or equal to each other per Object.equals() method
*/
public static boolean safeEqual(final Object x, final Object y) {
return (x == null) ? (y == null) : x.equals(y);
}
/**
* @param obj object to stringize
* @param args object's parameters to include into the result
* @return simple toString() implementation for this object and parameters
*/
public static String toString(final Object obj, final Object... args) {
if (args.length == 0) {
return String.format("%s[%x]", getSimpleClassName(obj), (obj != null) ? obj.hashCode() : "");
} else {
return String.format("%s[%x]%s", getSimpleClassName(obj), (obj != null) ? obj.hashCode() : "",
Arrays.toString(args).replaceFirst("^\\[", "{").replaceFirst("\\]$", "}"));
}
}
/**
* <p>
* Class.getSimpleName() is stripping off too much for nested classes, so using this method instead.
* </p>
*
* @param o object
* @return object's simple class name
*/
public static String getSimpleClassName(final Object o) {
if (o == null) return "null";
final String cls = o.getClass().getName();
final int lastDot = cls.lastIndexOf('.');
return (lastDot >= 0 && lastDot < (cls.length() - 1)) ? cls.substring(lastDot + 1) : cls;
}
/**
* @param path file path
* @return true if the file path corresponds to the existing file
*/
public static boolean isExistingFile(final String path) {
if (path == null || path.trim().length() == 0)
throw new IllegalArgumentException("NULL or empty file path");
return new File(path).isFile();
}
/**
* @param path file path
* @return true if the file path corresponds to the non-existing file that can be created
* @throws IOException
*/
public static boolean isValidNewFile(final String path) {
if (path == null || path.trim().length() == 0)
throw new IllegalArgumentException("NULL or empty file path");
final File f = new File(path);
try {
return !f.exists() && f.getCanonicalFile().getParentFile().isDirectory();
} catch (final IOException e) {
throw new IllegalArgumentException(String.format("Invalid file path %s: %s", path, e.getMessage()), e);
}
}
/**
* @param wrapdata wrap data as raw bytes
* @return wrap data as a string (implemented using b64 encoding) or null if wrapdata input parameter is null
*/
public static String getWrapDataInfo(final byte[] wrapdata) {
return (wrapdata != null) ? Base64Util.encode(wrapdata) : null;
}
/**
* @param param parameter
* @param name parameter name
*/
public static void assertNotNull(final Object param, final String name) {
if (param == null) throw new IllegalArgumentException(String.format("NULL %s", (name != null) ? name : "parameter"));
}
}
| 1,976 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/util/ConfigurationException.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.util;
/**
* <p>ConfigurationException class for MSL CLI configuration file errors.</p>
*
* @author Vadim Spector <[email protected]>
*/
public class ConfigurationException extends Exception {
/** serial version for serialization */
private static final long serialVersionUID = 8802095343158937216L;
/** Default Ctor */
public ConfigurationException() {
super();
}
/**
* @param message exception message
*/
public ConfigurationException(String message) {
super(message);
}
/**
* @param message exception message
* @param cause exception cause
*/
public ConfigurationException(String message, Throwable cause) {
super(message, cause);
}
/**
* @param cause exception cause
*/
public ConfigurationException(Throwable cause) {
super(cause);
}
}
| 1,977 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/util/CommonMslContext.java
|
/**
* Copyright (c) 2014-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.util;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslCryptoException;
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.DefaultMslEncoderFactory;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.msg.MessageCapabilities;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslStore;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.MslConfig;
/**
* <p>ABstract class for MSL context specific to the given entity.</p>
*
* @author Vadim Spector <[email protected]>
*/
public abstract class CommonMslContext extends MslContext {
/**
* <p>Create a new MSL context.</p>
*
* @param appCtx application context
* @param mslCfg MSL configuration.
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
protected CommonMslContext(final AppContext appCtx, final MslConfig mslCfg) throws ConfigurationException, IllegalCmdArgumentException {
if (appCtx == null) {
throw new IllegalArgumentException("NULL app context");
}
if (mslCfg == null) {
throw new IllegalArgumentException("NULL MSL config");
}
// Initialize MSL config.
this.mslCfg = mslCfg;
// Entity authentication data.
this.entityAuthData = mslCfg.getEntityAuthenticationData();
// Message capabilities.
final Set<CompressionAlgorithm> compressionAlgos = new HashSet<CompressionAlgorithm>(Arrays.asList(CompressionAlgorithm.GZIP, CompressionAlgorithm.LZW));
final List<String> languages = Arrays.asList("en-US");
final Set<MslEncoderFormat> encoderFormats = new HashSet<MslEncoderFormat>(Arrays.asList(MslEncoderFormat.JSON));
this.messageCaps = new MessageCapabilities(compressionAlgos, languages, encoderFormats);
// Entity authentication factories.
this.entityAuthFactories = mslCfg.getEntityAuthenticationFactories();
// User authentication factories.
this.userAuthFactories = mslCfg.getUserAuthenticationFactories();
// Key exchange factories.
this.keyxFactories = mslCfg.getKeyExchangeFactories();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getTime()
*/
@Override
public final long getTime() {
return System.currentTimeMillis();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getRandom()
*/
@Override
public final Random getRandom() {
return new SecureRandom();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#isPeerToPeer()
*/
@Override
public final boolean isPeerToPeer() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMessageCapabilities()
*/
@Override
public final MessageCapabilities getMessageCapabilities() {
return messageCaps;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getEntityAuthenticationData(com.netflix.msl.util.MslContext.ReauthCode)
*/
@Override
public final EntityAuthenticationData getEntityAuthenticationData(final ReauthCode reauthCode) {
return entityAuthData;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslCryptoContext()
*/
@Override
public abstract ICryptoContext getMslCryptoContext() throws MslCryptoException;
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getEntityAuthenticationFactory(com.netflix.msl.entityauth.EntityAuthenticationScheme)
*/
@Override
public final EntityAuthenticationFactory getEntityAuthenticationFactory(final EntityAuthenticationScheme scheme) {
for (final EntityAuthenticationFactory factory : entityAuthFactories) {
if (factory.getScheme().equals(scheme))
return factory;
}
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getUserAuthenticationFactory(com.netflix.msl.userauth.UserAuthenticationScheme)
*/
@Override
public final UserAuthenticationFactory getUserAuthenticationFactory(final UserAuthenticationScheme scheme) {
for (final UserAuthenticationFactory factory : userAuthFactories) {
if (factory.getScheme().equals(scheme))
return factory;
}
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getTokenFactory()
*/
@Override
public abstract TokenFactory getTokenFactory();
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getKeyExchangeFactory(com.netflix.msl.keyx.KeyExchangeScheme)
*/
@Override
public final KeyExchangeFactory getKeyExchangeFactory(final KeyExchangeScheme scheme) {
for (final KeyExchangeFactory factory : keyxFactories) {
if (factory.getScheme().equals(scheme))
return factory;
}
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getKeyExchangeFactories()
*/
@Override
public final SortedSet<KeyExchangeFactory> getKeyExchangeFactories() {
return keyxFactories;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getEntityAuthenticationScheme()
*/
@Override
public final EntityAuthenticationScheme getEntityAuthenticationScheme(final String name) {
return EntityAuthenticationScheme.getScheme(name);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getKeyExchangeScheme()
*/
@Override
public final KeyExchangeScheme getKeyExchangeScheme(final String name) {
return KeyExchangeScheme.getScheme(name);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getUserAuthenticationScheme()
*/
@Override
public final UserAuthenticationScheme getUserAuthenticationScheme(final String name) {
return UserAuthenticationScheme.getScheme(name);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslStore()
*/
@Override
public final MslStore getMslStore() {
return mslCfg.getMslStore();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslEncoderFactory()
*/
@Override
public MslEncoderFactory getMslEncoderFactory() {
return encoderFactory;
}
@Override
public final String toString() {
return SharedUtil.toString(this);
}
/** MSL config */
private final MslConfig mslCfg;
/** Entity authentication data. */
private final EntityAuthenticationData entityAuthData;
/** message capabilities */
private final MessageCapabilities messageCaps;
/** entity authentication factories */
private final Set<EntityAuthenticationFactory> entityAuthFactories;
/** user authentication factories */
private final Set<UserAuthenticationFactory> userAuthFactories;
/** key exchange factories */
private final SortedSet<KeyExchangeFactory> keyxFactories;
/** MSL encoder factory. */
private final MslEncoderFactory encoderFactory = new DefaultMslEncoderFactory();
}
| 1,978 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/util/MslStoreWrapper.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.util;
import java.util.Set;
import com.netflix.msl.MslException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.util.MslStore;
/**
* <p>
* Wrapper class for MslStore to enable selective call interception by deriving from this class.
* Extending this class allows overwriting selected method in order to change their behavior,
* for reporting, testing, etc.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class MslStoreWrapper implements MslStore {
/** target MslStore instance to which all calls are delegated */
private final MslStore mslStore;
/**
* Ctor.
*
* @param mslStore target MslStore instance to which all calls are delegated
*/
public MslStoreWrapper(final MslStore mslStore) {
if (mslStore == null) {
throw new IllegalArgumentException("NULL MSL Store");
}
if (mslStore instanceof MslStoreWrapper) {
throw new IllegalArgumentException("MSL Store is MslStoreWrapper instance");
}
this.mslStore = mslStore;
}
/**
* @return underlying instance of MslStore
*/
public final MslStore getMslStore() {
return mslStore;
}
/**
* @see com.netflix.msl.util.MslStore#setCryptoContext(MasterToken,ICryptoContext)
*/
@Override
public void setCryptoContext(final MasterToken masterToken, final ICryptoContext cryptoContext) {
mslStore.setCryptoContext(masterToken, cryptoContext);
}
/**
* @see com.netflix.msl.util.MslStore#getMasterToken()
*/
@Override
public MasterToken getMasterToken() {
return mslStore.getMasterToken();
}
/**
* @see com.netflix.msl.util.MslStore#getNonReplayableId(MasterToken)
*/
@Override
public long getNonReplayableId(final MasterToken masterToken) {
return mslStore.getNonReplayableId(masterToken);
}
/**
* @see com.netflix.msl.util.MslStore#getCryptoContext(MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MasterToken masterToken) {
return mslStore.getCryptoContext(masterToken);
}
/**
* @see com.netflix.msl.util.MslStore#removeCryptoContext(MasterToken)
*/
@Override
public void removeCryptoContext(final MasterToken masterToken) {
mslStore.removeCryptoContext(masterToken);
}
/**
* @see com.netflix.msl.util.MslStore#clearCryptoContexts()
*/
@Override
public void clearCryptoContexts() {
mslStore.clearCryptoContexts();
}
/**
* @see com.netflix.msl.util.MslStore#addUserIdToken(String,UserIdToken)
*/
@Override
public void addUserIdToken(final String userId, final UserIdToken userIdToken) throws MslException {
mslStore.addUserIdToken(userId, userIdToken);
}
/**
* @see com.netflix.msl.util.MslStore#getUserIdToken(String)
*/
@Override
public UserIdToken getUserIdToken(final String userId) {
return mslStore.getUserIdToken(userId);
}
/**
* @see com.netflix.msl.util.MslStore#removeUserIdToken(UserIdToken)
*/
@Override
public void removeUserIdToken(final UserIdToken userIdToken) {
mslStore.removeUserIdToken(userIdToken);
}
/**
* @see com.netflix.msl.util.MslStore#clearUserIdTokens()
*/
@Override
public void clearUserIdTokens() {
mslStore.clearUserIdTokens();
}
/**
* @see com.netflix.msl.util.MslStore#addServiceTokens(Set)
*/
@Override
public void addServiceTokens(final Set<ServiceToken> tokens) throws MslException {
mslStore.addServiceTokens(tokens);
}
/**
* @see com.netflix.msl.util.MslStore#getServiceTokens(MasterToken,UserIdToken)
*/
@Override
public Set<ServiceToken> getServiceTokens(final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
return mslStore.getServiceTokens(masterToken, userIdToken);
}
/**
* @see com.netflix.msl.util.MslStore#removeServiceTokens(String,MasterToken,UserIdToken)
*/
@Override
public void removeServiceTokens(final String name, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
mslStore.removeServiceTokens(name, masterToken, userIdToken);
}
/**
* @see com.netflix.msl.util.MslStore#clearServiceTokens()
*/
@Override
public void clearServiceTokens() {
mslStore.clearServiceTokens();
}
@Override
public String toString() {
return SharedUtil.toString(mslStore);
}
}
| 1,979 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/util/WrapCryptoContextRepositoryWrapper.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.util;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.WrapCryptoContextRepository;
/**
* <p>
* WrapCryptoContextRepositoryWrapper class makes pass-through calls to WrapCryptoContextRepositoryHandle.
* Extending this class allows intercepting selected methods in order to customize their behavior,
* including reporting, testing, etc.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class WrapCryptoContextRepositoryWrapper implements WrapCryptoContextRepositoryHandle {
/** target WrapCryptoContextRepositoryHandle implementation to which all calls are delegated */
private final WrapCryptoContextRepositoryHandle rep;
/**
* <P>Constructor.
*
* @param rep underlying instance of WrapCryptoContextRepositoryHandle implementation
*/
public WrapCryptoContextRepositoryWrapper(final WrapCryptoContextRepositoryHandle rep) {
if (rep == null) {
throw new IllegalArgumentException("NULL WrapCryptoContextRepository");
}
if (rep instanceof WrapCryptoContextRepositoryWrapper) {
throw new IllegalArgumentException("WrapCryptoContextRepository is WrapCryptoContextRepositoryWrapper instance");
}
this.rep = rep;
}
/**
* @see com.netflix.msl.keyx.WrapCryptoContextRepository#addCryptoContext(byte[],ICryptoContext)
*/
@Override
public void addCryptoContext(final byte[] wrapdata, final ICryptoContext cryptoContext) {
rep.addCryptoContext(wrapdata, cryptoContext);
}
/**
* @see com.netflix.msl.keyx.WrapCryptoContextRepository#getCryptoContext(byte[])
*/
@Override
public ICryptoContext getCryptoContext(final byte[] wrapdata) {
return rep.getCryptoContext(wrapdata);
}
/**
*@see com.netflix.msl.keyx.WrapCryptoContextRepository#removeCryptoContext(byte[])
*/
@Override
public void removeCryptoContext(final byte[] wrapdata) {
rep.removeCryptoContext(wrapdata);
}
@Override
public byte[] getLastWrapdata() {
return rep.getLastWrapdata();
}
@Override
public String toString() {
return rep.toString();
}
}
| 1,980 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/util/ConfigurationRuntimeException.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.util;
/**
* <p>
* Wrapper class for ConfigurationException.
* It is used to be thrown from the existing MSL core methods
* which cannot be modified to throw ConfigurationException.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class ConfigurationRuntimeException extends RuntimeException {
/** for proper serialization */
private static final long serialVersionUID = 2452369560136305840L;
/**
* @param cause exception cause
*/
public ConfigurationRuntimeException(ConfigurationException cause) {
super(cause);
}
}
| 1,981 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/util/CommonAuthenticationUtils.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.util;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.AuthenticationUtils;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.ConfigurationRuntimeException;
/**
* <p>
* Utility telling which entity authentication, user authentication, and key exchange
* mechanisms are allowed/supported for a given entity.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class CommonAuthenticationUtils implements AuthenticationUtils {
/**
* <p>Create a new authentication utils instance.</p>
*
* @param entityId entity identity
* @param appCtx application context
* @throws ConfigurationException
*/
protected CommonAuthenticationUtils(final String entityId, final AppContext appCtx) throws ConfigurationException {
if (entityId == null) {
throw new IllegalArgumentException("NULL entity identity");
}
if (appCtx == null) {
throw new IllegalArgumentException("NULL app context");
}
this.entityId = entityId;
this.appCtx = appCtx;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isEntityRevoked(java.lang.String)
*
* typical client entity probably won't be able to check its revocation status
*/
@Override
public boolean isEntityRevoked(final String identity) {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.entityauth.EntityAuthenticationScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final EntityAuthenticationScheme scheme) {
try {
return appCtx.getAllowedEntityAuthenticationSchemes(identity).contains(scheme);
} catch (ConfigurationException e) {
throw new ConfigurationRuntimeException(e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.userauth.UserAuthenticationScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final UserAuthenticationScheme scheme) {
try {
return appCtx.getAllowedUserAuthenticationSchemes(identity).contains(scheme);
} catch (ConfigurationException e) {
throw new ConfigurationRuntimeException(e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.tokens.MslUser, com.netflix.msl.userauth.UserAuthenticationScheme)
*
* In this specific implementation, allowed user authentication schemes depend on entity identity, not a specific user of that entity,
* so the implementation is the same as in the method above.
*/
@Override
public boolean isSchemePermitted(final String identity, final MslUser user, final UserAuthenticationScheme scheme) {
return isSchemePermitted(identity, scheme);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.keyx.KeyExchangeScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final KeyExchangeScheme scheme) {
try {
return appCtx.getAllowedKeyExchangeSchemes(identity).contains(scheme);
} catch (ConfigurationException e) {
throw new ConfigurationRuntimeException(e);
}
}
@Override
public String toString() {
return SharedUtil.toString(this, entityId);
}
/** Local client entity identity. */
protected final String entityId;
/** app context. */
protected final AppContext appCtx;
}
| 1,982 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/util/WrapCryptoContextRepositoryHandle.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.util;
import com.netflix.msl.keyx.WrapCryptoContextRepository;
/**
* <p>
* Wrap Crypto Context Repository Handle adding method to access the most recently added wrapdata.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public interface WrapCryptoContextRepositoryHandle extends WrapCryptoContextRepository {
/**
* @return the latest wrap data added to the store
*/
byte[] getLastWrapdata();
}
| 1,983 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/util/AppContext.java
|
/**
* Copyright (c) 2014-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.util;
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.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.crypto.CryptoCache;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.entityauth.KeySetStore;
import com.netflix.msl.entityauth.KeySetStore.KeySet;
import com.netflix.msl.entityauth.RsaStore;
import com.netflix.msl.keyx.DiffieHellmanParameters;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.msg.MslControl;
import com.netflix.msl.userauth.EmailPasswordStore;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import mslcli.common.Pair;
import mslcli.common.Triplet;
import mslcli.common.entityauth.EntityAuthenticationHandle;
import mslcli.common.entityauth.SimplePresharedKeyStore;
import mslcli.common.entityauth.SimpleRsaStore;
import mslcli.common.keyx.KeyExchangeHandle;
import mslcli.common.userauth.SimpleEmailPasswordStore;
import mslcli.common.userauth.UserAuthenticationHandle;
import mslcli.common.util.SharedUtil.Base64Util;
/**
* <p>
* Collection of MSL configuration-specific functions, based
* on the data extracted from MSL CLI configuration file.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public final class AppContext {
/**
* Singleton instance
*/
private static AppContext _instance;
/** properties from the config file */
private final MslProperties prop;
/** MslControl implementing MSL protocol stack */
private final MslControl mslControl;
/** entity preshared keys database */
private final KeySetStore presharedKeyStore;
/** entity MGK keys database */
private final KeySetStore mgkKeyStore;
/** user email / password database */
private final EmailPasswordStore emailPasswordStore;
/** named RSA key pairs database */
private final RsaStore rsaStore;
/** named Diffie-Hellman algorithm parameters database */
private final DiffieHellmanParameters diffieHellmanParameters;
/** entity authentication handles configured for this app */
private final Set<EntityAuthenticationHandle> entityAuthenticationHandles;
/** ordered list of key exchange handles configured for this app in the order of their preference */
private final List<KeyExchangeHandle> keyExchangeHandles;
/** user authentication handles configured for this app */
private final Set<UserAuthenticationHandle> userAuthenticationHandles;
/**
* @param p properties loaded from some configuration source
* @return singleton instance of AppContext
* @throws ConfigurationException
*/
public static synchronized AppContext getInstance(final MslProperties p) throws ConfigurationException {
if (_instance == null) {
if (p == null) {
throw new IllegalArgumentException("NULL properties");
}
return (_instance = new AppContext(p));
} else {
throw new IllegalStateException("Illegal Attempt to Re-Initialize AppContext");
}
}
/**
* Ctor
*
* @param p MslProperties based on the configuration properties file
* @throws ConfigurationException
*/
private AppContext(final MslProperties p) throws ConfigurationException {
if (p == null) {
throw new IllegalArgumentException("NULL MslProperties");
}
this.prop = p;
this.mslControl = new MslControl(p.getNumMslControlThreads());
this.diffieHellmanParameters = new SimpleDiffieHellmanParameters(p);
this.presharedKeyStore = initPresharedKeyStore(p);
this.mgkKeyStore = initMgkKeyStore(p);
this.emailPasswordStore = initEmailPasswordStore(p);
this.rsaStore = initRsaStore(p);
this.entityAuthenticationHandles = new HashSet<EntityAuthenticationHandle>(populateHandles(EntityAuthenticationHandle.class, p.getEntityAuthenticationHandles()));
this.keyExchangeHandles = populateHandles(KeyExchangeHandle.class, p.getKeyExchangeHandles());
this.userAuthenticationHandles = new HashSet<UserAuthenticationHandle>(populateHandles(UserAuthenticationHandle.class, p.getUserAuthenticationHandles()));
}
/**
* populate list of handles
* @param cls handle super-class
* @param clspaths list of handle class names
* @param <T> handle super-class template type
* @return list of handle instances
* @throws ConfigurationException
*/
private static <T> List<T> populateHandles(final Class<T> cls, final List<String> clspaths)
throws ConfigurationException
{
final List<T> handles = new ArrayList<T>();
for (String s : clspaths) {
final Object h;
try {
h = Class.forName(s).newInstance();
} catch (ClassNotFoundException e) {
throw new ConfigurationException(String.format("%s class not found", s), e);
} catch (InstantiationException e) {
throw new ConfigurationException(String.format("%s class cannot be instantiated", s), e);
} catch (IllegalAccessException e) {
throw new ConfigurationException(String.format("%s class cannot be instantiated", s), e);
}
if (cls.isAssignableFrom(h.getClass())) {
handles.add(cls.cast(h));
} else {
throw new ConfigurationException(String.format("%s class %s: wrong type", cls.getSimpleName(), s));
}
}
return handles;
}
/**
* @return MslProperties
*/
public MslProperties getProperties() {
return prop;
}
/**
* @return MSL control
*/
public MslControl getMslControl() {
return mslControl;
}
/**
* @return preshared key store
*/
public KeySetStore getPresharedKeyStore() {
return presharedKeyStore;
}
/**
* @return MGK key store
*/
public KeySetStore getMgkKeyStore() {
return mgkKeyStore;
}
/**
* @return entity authentication data handle for a given scheme
*/
public Set<EntityAuthenticationHandle> getEntityAuthenticationHandles() {
return Collections.unmodifiableSet(entityAuthenticationHandles);
}
/**
* @return key exchange handles
*/
public List<KeyExchangeHandle> getKeyExchangeHandles() {
return Collections.unmodifiableList(keyExchangeHandles);
}
/**
* @return user authentication handles
*/
public Set<UserAuthenticationHandle> getUserAuthenticationHandles() {
return Collections.unmodifiableSet(userAuthenticationHandles);
}
/**
* @param s key encoded as HEX or BASE64 string
* @return key decoded into a byte array
* @throws ConfigurationException
*/
private static byte[] parseKey(final String s) throws ConfigurationException {
if (s == null || s.trim().isEmpty()) {
throw new ConfigurationException("Empty Key Value");
}
if (s.startsWith("b64:")) {
try {
return Base64Util.decodeToByteArray(s.trim().substring(4));
} catch (IllegalArgumentException e) {
throw new ConfigurationException("Invalid Base64 Value " + s);
}
} else {
return SharedUtil.hexStringToByteArray(s.trim());
}
}
/**
* @param p MslProperties
* @return preshared key store database
* @throws ConfigurationException
*/
private static KeySetStore initPresharedKeyStore(final MslProperties p) throws ConfigurationException {
return _initKeyStore(p.getPresharedKeyStore());
}
/**
* @param p MslProperties
* @return MGK key store database
* @throws ConfigurationException
*/
private static KeySetStore initMgkKeyStore(final MslProperties p) throws ConfigurationException {
return _initKeyStore(p.getMgkKeyStore());
}
/**
* @param keys map of entity ID to key triplet
* @return key store database
* @throws ConfigurationException
*/
private static KeySetStore _initKeyStore(final Map<String,Triplet<String,String,String>> keys) throws ConfigurationException {
final Map<String,KeySet> keySets = new HashMap<String,KeySet>();
for (Map.Entry<String,Triplet<String,String,String>> entry : keys.entrySet()) {
final byte[] encKey = parseKey(entry.getValue().x);
final byte[] hmacKey = parseKey(entry.getValue().y);
final byte[] wrapKey;
if (entry.getValue().z != null) {
wrapKey = parseKey(entry.getValue().z);
} else {
try {
wrapKey = SharedUtil.deriveWrappingKey(encKey, hmacKey);
} catch (InvalidKeyException e) {
throw new ConfigurationException("Failed to initialize preshared keys", e);
} catch (NoSuchAlgorithmException e) {
throw new ConfigurationException("Failed to initialize preshared keys", e);
}
}
keySets.put(entry.getKey(), new KeySet(
new SecretKeySpec(encKey, JcaAlgorithm.AES),
new SecretKeySpec(hmacKey, JcaAlgorithm.HMAC_SHA256),
new SecretKeySpec(wrapKey, JcaAlgorithm.AESKW)
));
}
return new SimplePresharedKeyStore(keySets);
}
/**
* @return {email,password} store
*/
public EmailPasswordStore getEmailPasswordStore() {
return emailPasswordStore;
}
/**
* @param p MslProperties
* @return user email / password database
* @throws ConfigurationException
*/
private static EmailPasswordStore initEmailPasswordStore(final MslProperties p) throws ConfigurationException {
return new SimpleEmailPasswordStore(p.getEmailPasswordStore());
}
/**
* @return RSA key store
*/
public RsaStore getRsaStore() {
return rsaStore;
}
/**
* Client would normally have only the server public key to authenticate server responses.
* Server would normally have both public and private keys
*
* @param p MslProperties
* @return RSA key store
* @throws ConfigurationException
*/
private static RsaStore initRsaStore(final MslProperties p) throws ConfigurationException {
try {
final KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");
final Map<String,Pair<String,String>> rsaKeyPairsB64 = p.getRsaKeyStore();
final Map<String,KeyPair> rsaKeyPairs = new HashMap<String,KeyPair>();
for (Map.Entry<String,Pair<String,String>> entry : rsaKeyPairsB64.entrySet()) {
final PublicKey pubKey;
if (entry.getValue().x != null) {
final byte[] pubKeyEncoded = Base64Util.decodeToByteArray(entry.getValue().x);
final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyEncoded);
pubKey = rsaKeyFactory.generatePublic(pubKeySpec);
} else {
pubKey = null;
}
final PrivateKey privKey;
if (entry.getValue().y != null) {
final byte[] privKeyEncoded = Base64Util.decodeToByteArray(entry.getValue().y);
final PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyEncoded);
privKey = rsaKeyFactory.generatePrivate(privKeySpec);
} else {
privKey = null;
}
rsaKeyPairs.put(entry.getKey(), new KeyPair(pubKey, privKey));
}
return new SimpleRsaStore(rsaKeyPairs);
} catch (final NoSuchAlgorithmException e) {
throw new RuntimeException("RSA algorithm not found.", e);
} catch (final InvalidKeySpecException e) {
throw new RuntimeException("Invalid RSA private key.", e);
}
}
/**
* Class encapsulating Diffie-Hellman parameters Map keyed by parameters ID.
* Parameters are loaded from the configuration.
*/
private static final class SimpleDiffieHellmanParameters implements DiffieHellmanParameters {
/** Default parameters. */
/**
* Ctor
* @param prop MslProperties
* @throws ConfigurationException
*/
private SimpleDiffieHellmanParameters(final MslProperties prop) throws ConfigurationException {
for (Map.Entry<String,Pair<String,String>> entry : prop.getDHParameterStore().entrySet()) {
params.put(entry.getKey(), new DHParameterSpec(
new BigInteger(entry.getValue().x, 16),
new BigInteger(entry.getValue().y, 16)
));
}
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.DiffieHellmanParameters#getParameterSpecs()
*/
@Override
public Map<String,DHParameterSpec> getParameterSpecs() {
return Collections.unmodifiableMap(params);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.DiffieHellmanParameters#getParameterSpec(java.lang.String)
*/
@Override
public DHParameterSpec getParameterSpec(final String id) {
return params.get(id);
}
/** Diffie-Hellman parameters Map. */
private final Map<String,DHParameterSpec> params = new HashMap<String,DHParameterSpec>();
}
/**
* @return mapping from Diffie-Hellman parameters ID to Diffie-Hellman parameters
*/
public final DiffieHellmanParameters getDiffieHellmanParameters() {
return diffieHellmanParameters;
}
/**
* @param entityId entity identity string
* @return Diffie-Hellman parameters ID to be used by the given entity for key exchange
* @throws ConfigurationException
*/
public String getDiffieHellmanParametersId(String entityId) throws ConfigurationException {
return prop.getEntityDiffieHellmanParametersId(entityId);
}
/**
* Generate Diffie-Hellman key pair for key exchange, with parameters corresponding
* to specified parameters ID
* @param paramId Diffie-Hellman parameters ID
* @return Diffie-Hellman key pair generated using parameters corresponding to the provided ID
* @throws MslKeyExchangeException
*/
public KeyPair generateDiffieHellmanKeys(final String paramId) throws MslKeyExchangeException {
final DHParameterSpec paramSpec = getDiffieHellmanParameters().getParameterSpec(paramId);
try {
final KeyPairGenerator generator = CryptoCache.getKeyPairGenerator("DH");
generator.initialize(paramSpec);
return generator.generateKeyPair();
} 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);
}
}
/**
* Generate RSA key pair used for wrapped key exchange
* @return RSA key pair
* @throws MslInternalException
*/
public KeyPair generateAsymmetricWrappedExchangeKeyPair() throws MslInternalException {
try {
info("Generating RSA Key Pair - please, wait ...");
final KeyPairGenerator generator = CryptoCache.getKeyPairGenerator("RSA");
generator.initialize(4096);
return generator.generateKeyPair();
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("RSA algorithm not found.", e);
}
}
/**
* @param entityId entity identity
* @return entity authentication schemes allowed for a given entity
* @throws ConfigurationException
*/
public Set<EntityAuthenticationScheme> getAllowedEntityAuthenticationSchemes(final String entityId) throws ConfigurationException {
final Set<EntityAuthenticationScheme> schemes = new HashSet<EntityAuthenticationScheme>();
for (String scheme : prop.getSupportedEntityAuthenticationSchemes(entityId)) {
final EntityAuthenticationScheme eas = EntityAuthenticationScheme.getScheme(scheme);
if (eas == null) {
throw new IllegalArgumentException(String.format("Unknown Entity Authentication Scheme for Entity %s: %s", entityId, scheme));
}
schemes.add(eas);
}
return Collections.unmodifiableSet(schemes);
}
/**
* @param entityId entity identity
* @return entity authentication schemes allowed for a given entity
* @throws ConfigurationException
*/
public Set<UserAuthenticationScheme> getAllowedUserAuthenticationSchemes(final String entityId) throws ConfigurationException {
final Set<UserAuthenticationScheme> schemes = new HashSet<UserAuthenticationScheme>();
for (String scheme : prop.getSupportedUserAuthenticationSchemes(entityId)) {
final UserAuthenticationScheme uas = UserAuthenticationScheme.getScheme(scheme);
if (uas == null) {
throw new IllegalArgumentException(String.format("Unknown User Authentication Scheme for Entity %s: %s", entityId, scheme));
}
schemes.add(uas);
}
return Collections.unmodifiableSet(schemes);
}
/**
* @param entityId entity identity
* @return key exchange schemes allowed for a given entity
* @throws ConfigurationException
*/
public Set<KeyExchangeScheme> getAllowedKeyExchangeSchemes(final String entityId) throws ConfigurationException {
final Set<KeyExchangeScheme> schemes = new HashSet<KeyExchangeScheme>();
for (String scheme : prop.getSupportedKeyExchangeSchemes(entityId)) {
final KeyExchangeScheme kxs = KeyExchangeScheme.getScheme(scheme);
if (kxs == null) {
throw new IllegalArgumentException(String.format("Illegal Key Exchange Scheme for Entity %s: %s", entityId, scheme));
}
schemes.add(kxs);
}
return Collections.unmodifiableSet(schemes);
}
/**
* @param entityId entity identity
* @return RSA key pair ID to be used for a given entity for RSA entity authentication
* @throws ConfigurationException
*/
public String getRsaKeyId(final String entityId) throws ConfigurationException {
return prop.getRsaKeyId(entityId);
}
/**
* @return MSL encryption, HMAC, and wrapping keys
* @throws ConfigurationException
*/
public Triplet<SecretKey,SecretKey,SecretKey> getMslKeys() throws ConfigurationException {
final Triplet<String,String,String> mslKeys = prop.getMslKeys();
return new Triplet<SecretKey,SecretKey,SecretKey>(
new SecretKeySpec(SharedUtil.hexStringToByteArray(mslKeys.x), JcaAlgorithm.AES),
new SecretKeySpec(SharedUtil.hexStringToByteArray(mslKeys.y), JcaAlgorithm.HMAC_SHA256),
new SecretKeySpec(SharedUtil.hexStringToByteArray(mslKeys.z), JcaAlgorithm.AESKW)
);
}
/**
* @param keySetId for a given RSA key pair
* @return service token encryption and HMAC keys for a given key set ID
* @throws ConfigurationException
*/
public Pair<SecretKey,SecretKey> getServiceTokenKeys(final String keySetId) throws ConfigurationException {
final Pair<String,String> keys = prop.getServiceTokenKeys(keySetId);
return new Pair<SecretKey,SecretKey>(
new SecretKeySpec(SharedUtil.hexStringToByteArray(keys.x), JcaAlgorithm.AES),
new SecretKeySpec(SharedUtil.hexStringToByteArray(keys.y), JcaAlgorithm.HMAC_SHA256)
);
}
/**
* info logging
*
* @param msg info message
*/
public void info(final String msg) {
System.err.println("INFO: " + msg);
}
/**
* warning logging
*
* @param msg warning message
*/
public void warning(final String msg) {
System.err.println("WARNING: " + msg);
}
/**
* error logging
*
* @param msg error message
*/
public void error(final String msg) {
System.err.println("ERROR: " + msg);
}
@Override
public String toString() {
return SharedUtil.toString(this);
}
}
| 1,984 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/util/MslStoreData.java
|
/**
* Copyright (c) 2014-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.crypto.SecretKey;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslException;
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.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.SimpleMslStore;
/**
* <p>
* The class for serializing SimpleMslStore. Because of using reflection, this code is pretty brittle and
* must keep in-sync with SimpleMslStore changes.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class MslStoreData implements Serializable {
/** for proper serialization */
private static final long serialVersionUID = 5207304253726353139L;
/*
* SimpleMslStore fields that need to be accessed for serialization.
* To be kept in-sync with SimpleMslStore code
*/
/** SimpleMslStore field */
private static final String MS_CRYPTO_CONTEXT_FIELD = "cryptoContexts";
/** SimpleMslStore field */
private static final String MS_UID_TOKENS_FIELD = "userIdTokens";
/** SimpleMslStore field */
private static final String MS_UNB_SVC_TOKENS_FIELD = "unboundServiceTokens";
/** SimpleMslStore field */
private static final String MS_MT_SVC_TOKENS_FIELD = "mtServiceTokens";
/** SimpleMslStore field */
private static final String MS_UIT_SVC_TOKENS_FIELD = "uitServiceTokens";
/** SimpleMslStore field */
private static final String MS_NON_REPLAY_IDS_FIELD = "nonReplayableIds";
/**
* Create serializable MslStoreData from non-serializable SimpleMslStore
* @param ctx MSL context
* @param mslStore SimpleMslStore instance
* @throws MslEncoderException
*/
@SuppressWarnings("unchecked")
private MslStoreData(final MslContext ctx, final SimpleMslStore mslStore) throws MslEncoderException {
if (mslStore == null)
throw new IllegalArgumentException("NULL MslStore");
// extract all master tokens with crypto contexts
final Map<MasterToken,ICryptoContext> cryptoContexts = (Map<MasterToken,ICryptoContext>)getFieldValue(mslStore, MS_CRYPTO_CONTEXT_FIELD);
for (final Map.Entry<MasterToken,ICryptoContext> e : cryptoContexts.entrySet()) {
this.cryptoContextData.put(new MasterTokenData(ctx, e.getKey()), new CryptoContextData(e.getValue()));
}
// extract all user id tokens
final Map<String,UserIdToken> userIdTokens = new HashMap<String,UserIdToken>((Map<String,UserIdToken>)getFieldValue(mslStore, MS_UID_TOKENS_FIELD));
for (final Map.Entry<String,UserIdToken> e : userIdTokens.entrySet()) {
this.userIdTokenData.put(e.getKey(), new UserIdTokenData(ctx, e.getValue()));
}
// extract all service tokens
final Set<ServiceToken> serviceTokens = new HashSet<ServiceToken>();
{
final Set<ServiceToken> unboundServiceTokens = (Set<ServiceToken>)getFieldValue(mslStore, MS_UNB_SVC_TOKENS_FIELD);
serviceTokens.addAll(unboundServiceTokens);
final Map<Long,Set<ServiceToken>> mtServiceTokens = (Map<Long,Set<ServiceToken>>)getFieldValue(mslStore, MS_MT_SVC_TOKENS_FIELD);
for (final Set<ServiceToken> sts : mtServiceTokens.values()) {
serviceTokens.addAll(sts);
}
final Map<Long,Set<ServiceToken>> uitServiceTokens = (Map<Long,Set<ServiceToken>>)getFieldValue(mslStore, MS_UIT_SVC_TOKENS_FIELD);
for (final Set<ServiceToken> sts : uitServiceTokens.values()) {
serviceTokens.addAll(sts);
}
}
for (final ServiceToken st : serviceTokens) {
this.serviceTokenData.add(new ServiceTokenData(ctx, st));
}
// extract non-replayable id's
this.nonReplayableIds = (Map<Long,Long>)getFieldValue(mslStore, MS_NON_REPLAY_IDS_FIELD);
}
/**
* SimpleMslStore serializer
*
* @param ms SimpleMslStore instance
* @return blob serialized SimpleMslStore instance
* @throws IOException
* @throws MslEncoderException
*/
public static byte[] serialize(final SimpleMslStore ms, final MslContext ctx) throws IOException, MslEncoderException {
final MslStoreData msd = new MslStoreData(ctx, ms);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(out);
oos.writeObject(msd);
return out.toByteArray();
} finally {
if (oos != null) try { oos.close(); } catch (final Exception ignore) { }
}
}
/**
* SimpleMslStore deserializer
*
* @param blob serialized SimpleMslStore
* @param mslCtx MslContext instance
* @return deserialized SimpleMslStore instance
* @throws IOException
* @throws MslEncodingException
* @throws MslException
* @throws MslEncoderException
*/
public static SimpleMslStore deserialize(final byte[] blob, final MslContext mslCtx)
throws IOException, MslEncodingException, MslException, MslEncoderException
{
final MslStoreData msd;
final ByteArrayInputStream in = new ByteArrayInputStream(blob);
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(in);
msd = (MslStoreData)ois.readObject();
} catch (final ClassNotFoundException e) {
throw new IOException("SimpleMslStore unmarshalling error", e);
} finally {
if (ois != null) try { ois.close(); } catch (final Exception ignore) { }
}
final SimpleMslStore mslStore = new SimpleMslStore();
final Map<Long,MasterToken> mtokens = new HashMap<Long,MasterToken>();
for (final Map.Entry<MasterTokenData,CryptoContextData> e : msd.cryptoContextData.entrySet()) {
final MasterToken mt = e.getKey().get(mslCtx);
mslStore.setCryptoContext(mt, e.getValue().get(mslCtx, mt));
mtokens.put(mt.getSerialNumber(), mt);
}
final Map<Long,UserIdToken> uitokens = new HashMap<Long,UserIdToken>();
for (final Map.Entry<String,UserIdTokenData> e : msd.userIdTokenData.entrySet()) {
final UserIdTokenData uitd = e.getValue();
final UserIdToken uit = uitd.get(mslCtx, mtokens.get(uitd.mtSerialNumber));
mslStore.addUserIdToken(e.getKey(), uit);
uitokens.put(uit.getSerialNumber(), uit);
}
final Set<ServiceToken> stokens = new HashSet<ServiceToken>();
for (final ServiceTokenData std : msd.serviceTokenData) {
stokens.add(std.get(mslCtx, mtokens.get(std.mtSerialNumber), uitokens.get(std.uitSerialNumber)));
}
mslStore.addServiceTokens(stokens);
setFieldValue(mslStore, MS_NON_REPLAY_IDS_FIELD, msd.nonReplayableIds);
return mslStore;
}
/** Map of serializable master tokens onto serializable crypto contexts */
private final Map<MasterTokenData,CryptoContextData> cryptoContextData = new HashMap<MasterTokenData,CryptoContextData>();
/** Map of user IDs onto serializable user id tokens */
private final Map<String,UserIdTokenData> userIdTokenData = new HashMap<String,UserIdTokenData>();
/** Set of serializable service tokens */
private final Set<ServiceTokenData> serviceTokenData = new HashSet<ServiceTokenData>();
/** Map of master token serial numbers onto non-replayable IDs. */
private final Map<Long,Long> nonReplayableIds;
/**
* serializable wrapper class for MasterToken
*/
private static final class MasterTokenData implements Serializable {
/** for proper serialization */
private static final long serialVersionUID = -4900828984126453948L;
/**
* @param ctx MslContext
* @param mt master token
* @throws MslEncoderException
*/
MasterTokenData(final MslContext ctx, final MasterToken mt) throws MslEncoderException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
this.s = mt.toMslEncoding(encoder, MslEncoderFormat.JSON);
}
/**
* @param ctx MslContext
* @return re-created master token
* @throws MslEncodingException
* @throws MslException
* @throws MslCryptoException
* @throws MslEncoderException
*/
MasterToken get(final MslContext ctx) throws MslEncodingException, MslException, MslCryptoException, MslEncoderException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject mo = encoder.parseObject(s);
return new MasterToken(ctx, mo);
}
/** serialized master token */
private final byte[] s;
}
/**
* serializable wrapper class for UserIdToken
*/
private static final class UserIdTokenData implements Serializable {
/** for proper serialization */
private static final long serialVersionUID = -5191856143592904675L;
/**
* @param ctx MslContext
* @param uit user id token
* @throws MslEncoderException
*/
UserIdTokenData(final MslContext ctx, final UserIdToken uit) throws MslEncoderException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
this.s = uit.toMslEncoding(encoder, MslEncoderFormat.JSON);
this.mtSerialNumber = uit.getMasterTokenSerialNumber();
}
/**
* @param ctx MslContext
* @param mt master token
* @return re-created user id token
* @throws MslEncodingException
* @throws MslException
* @throws MslCryptoException
* @throws MslEncoderException
*/
UserIdToken get(final MslContext ctx, final MasterToken mt) throws MslEncodingException, MslException, MslCryptoException, MslEncoderException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject mo = encoder.parseObject(s);
return new UserIdToken(ctx, mo, mt);
}
/** serialized user id token */
private final byte[] s;
/** master token serial number */
private final long mtSerialNumber;
}
/**
* serializable wrapper class for ServiceToken
*/
private static final class ServiceTokenData implements Serializable {
/** for proper serialization */
private static final long serialVersionUID = -2854005430616613106L;
/**
* @param ctx MslContext
* @param st service token
* @throws MslEncoderException
*/
ServiceTokenData(final MslContext ctx, final ServiceToken st) throws MslEncoderException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
this.s = st.toMslEncoding(encoder, MslEncoderFormat.JSON);
this.mtSerialNumber = st.getMasterTokenSerialNumber();
this.uitSerialNumber = st.getUserIdTokenSerialNumber();
}
/**
* @param ctx MslContext
* @param mt master token
* @param uit user id token
* @return re-created service token
* @throws MslEncodingException
* @throws MslException
* @throws MslCryptoException
* @throws MslEncoderException
*/
ServiceToken get(final MslContext ctx, final MasterToken mt, final UserIdToken uit)
throws MslEncodingException, MslException, MslCryptoException, MslEncoderException
{
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject mo = encoder.parseObject(s);
return new ServiceToken(ctx, mo, mt, uit, (ICryptoContext)null);
}
/** serialized service token */
private final byte[] s;
/** master token serial number */
private final long mtSerialNumber;
/** user id token serial number */
private final long uitSerialNumber;
}
/**
* serializable wrapper class for SessionCryptoContext
*/
private static final class CryptoContextData implements Serializable {
/** for proper serialization */
private static final long serialVersionUID = -4094166271048593127L;
/** SessionEncryptionContext field name */
private static final String ID_FIELD = "id";
/** SessionEncryptionContext field name */
private static final String ENC_FIELD = "encryptionKey";
/** SessionEncryptionContext field name */
private static final String SIG_FIELD = "signatureKey";
/** SessionEncryptionContext field name */
private static final String WRAP_FIELD = "wrappingKey";
/**
* @param ctx crypto context that must be of SessionCryptoContext type
*/
CryptoContextData(final ICryptoContext ctx) {
if (!(ctx instanceof SessionCryptoContext))
throw new IllegalArgumentException(String.format("CryptoContext[%s] - required %s",
ctx.getClass().getName(), SessionCryptoContext.class.getName()));
this.id = (String) getFieldValue(ctx, ID_FIELD );
this.encKey = (SecretKey)getFieldValue(ctx, ENC_FIELD );
this.hmacKey = (SecretKey)getFieldValue(ctx, SIG_FIELD );
this.wrapKey = (SecretKey)getFieldValue(ctx, WRAP_FIELD);
}
/**
* @param mctx MslContext
* @param mt master token
* @return recreated crypto context
*/
ICryptoContext get(final MslContext mctx, final MasterToken mt) {
final String suffix = "_" + mt.getSequenceNumber();
if (!id.endsWith(suffix)) {
throw new IllegalArgumentException(String.format("Internal Error: Unexpected Crypto Context ID %s, should end with %s", id, suffix));
}
final String id_without_suffix = id.substring(0, id.length() - suffix.length());
return new SessionCryptoContext(mctx, mt, id_without_suffix, encKey, hmacKey);
}
/** crypto context id */
private final String id;
/** crypto context encryption key */
private final SecretKey encKey;
/** crypto context hmac key */
private final SecretKey hmacKey;
/** crypto context wrapping key */
private final SecretKey wrapKey;
}
/* ********************************
* Java reflection helper methods *
**********************************/
/**
* get the value of the field with the given name for a given object
*
* @param o object
* @param name name of the field of this object
* @return value of the field with the given name of this object
*/
private static Object getFieldValue(final Object o, final String name) {
if (o == null)
throw new IllegalArgumentException("NULL object");
if (name == null)
throw new IllegalArgumentException("NULL field name");
final Field f = getField(o, name);
try {
return f.get(o);
} catch (final IllegalAccessException e) {
throw new IllegalArgumentException(String.format("Class %s field %s - cannot get value", o.getClass().getName(), name), e);
}
}
/**
* set the value of the field with the given name for a given object
*
* @param o object
* @param name name of the field of this object
* @param value value to assign to the given field of the given object
*/
private static void setFieldValue(final Object o, final String name, final Object value) {
if (o == null)
throw new IllegalArgumentException("NULL object");
if (name == null)
throw new IllegalArgumentException("NULL field name");
if (value == null)
throw new IllegalArgumentException("NULL field value");
final Field f = getField(o, name);
try {
f.set(o, value);
} catch (final IllegalAccessException e) {
throw new IllegalArgumentException(String.format("Class %s field %s - cannot set value", o.getClass().getName(), name), e);
}
}
/**
* Return the field with the given name of a given class (search superclasses as well)
* and make it accessible for get and set
*
* @param o object
* @param name name of the field of this object
* @return field with the given name, made accessible for get/set operations
*/
private static Field getField(final Object o, final String name) {
if (o == null)
throw new IllegalArgumentException("NULL object");
if (name == null)
throw new IllegalArgumentException("NULL field name");
Class<? extends Object> cls = o.getClass();
for ( ; cls.getSuperclass() != null; cls = cls.getSuperclass()) {
for (final Field f : cls.getDeclaredFields()) {
if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers())) {
continue;
}
if (name.equals(f.getName())) {
f.setAccessible(true);
return f;
}
}
}
throw new IllegalArgumentException(String.format("Class %s: no field %s found", o.getClass().getName(), name));
}
}
| 1,985 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/util/MslProperties.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.util;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import mslcli.common.Pair;
import mslcli.common.Triplet;
/**
* <p>
* Msl Properties extracted from MSL CLI configuration file.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public final class MslProperties {
/*
* APPLICATION-SPECIFIC CONFIGURATION PROPERTIY NAMES
*/
/** number of thread for MslControl to run on */
private static final String APP_CTRL_NUM_THR = "app.mslctrl.nthr";
/** server port */
private static final String APP_SERVER_PORT = "app.server.port";
/** entity authentication handle prefix */
private static final String APP_ENTITY_AUTH_HANDLE = "app.entityauth.handle.";
/** key exchange handle prefix */
private static final String APP_KEYX_HANDLE = "app.keyx.handle.";
/** user authentication handle prefix */
private static final String APP_USER_AUTH_HANDLE = "app.userauth.handle.";
/*
* ENTITY-SPECIFIC CONFIGURATION PROPERTY NAMES
*/
/** prefix for allowed entity authentication schemes for a given entity */
private static final String ENTITY_AUTH_SCHEMES = "entity.auth.schemes.";
/** prefix for allowed user authentication schemes for a given entity */
private static final String ENTITY_UAUTH_SCHEMES = "entity.userauth.schemes.";
/** prefix for allowed key exchange schemes for a given entity */
private static final String ENTITY_KX_SCHEMES = "entity.kx.schemes.";
/** prefix for RSA key ID used by a given entity */
private static final String ENTITY_RSA_KEY_ID = "entity.rsa.keyid.";
/** prefix for PSK key sets */
private static final String ENTITY_PSK = "entity.psk.";
/** prefix for MGK key sets */
private static final String ENTITY_MGK = "entity.mgk.";
/** prefix for the entity Diffie-Hellman key pair ID */
private static final String ENTITY_DH_ID = "entity.dh.id.";
/** prefix for the entity key set ID used for securing service tokens */
private static final String ENTITY_STOKEN_KEY_ID = "entity.stoken.keyid.";
/*
* USER-SPECIFIC CONFIGURATION PROPERTY NAMES
*/
/** suffix for email/password entries */
private static final String USER_EP = "user.ep.";
/** email */
private static final String EMAIL = "email";
/** password */
private static final String PWD = "pwd";
/*
* MSL ECOSYSTEM-WIDE CONFIGURATION PROPERTY NAMES
*/
/** RSA key pair sets */
private static final String MSL_RSA = "msl.rsa.";
/** Diffie-Hellman algorithm parameters sets */
private static final String MSL_DH = "msl.dh.";
/** MSL encryption key */
private static final String MSL_KEY_ENC = "msl.key.enc";
/** MSL HMAC key */
private static final String MSL_KEY_HMAC = "msl.key.hmac";
/** MSL wrapping key */
private static final String MSL_KEY_WRAP = "msl.key.wrap";
/** Master Token renewal offset in milliseconds */
private static final String MSL_MTOKEN_RENEWAL_OFFSET = "msl.mtoken.renewal";
/** Master Token expiration offset in milliseconds */
private static final String MSL_MTOKEN_EXPIRATION_OFFSET = "msl.mtoken.expiration";
/** Master Token non-replay ID window */
private static final String MSL_MTOKEN_NON_REPLAY_ID_WINDOW = "msl.mtoken.non_replay_id_window";
/** Master Token max number of skipped sequence numbers still allowed for renewal */
private static final String MSL_MTOKEN_MAX_SKIPPED = "msl.mtoken.max_skipped";
/** User Id Token renewal offset in milliseconds */
private static final String MSL_UITOKEN_RENEWAL_OFFSET = "msl.uitoken.renewal";
/** User Id Token expiration offset in milliseconds */
private static final String MSL_UITOKEN_EXPIRATION_OFFSET = "msl.uitoken.expiration";
/** prefix for service token encryption key */
private static final String MSL_STOKEN_KEY_ENC = "msl.stoken.keys.enc.";
/** prefix for service token HMAC key */
private static final String MSL_STOKEN_KEY_HMAC = "msl.stoken.keys.hmac.";
/** Common property name suffix for defining the number of properties of a given kind */
private static final String NUM = "num";
/** Common property name suffix for entry ID */
private static final String ID = "id";
/** Common property name suffix for encryption key */
private static final String ENC_KEY = "enc";
/** Common property name suffix for hmac key */
private static final String HMAC_KEY = "hmac";
/** Common property name suffix for hmac key */
private static final String WRAP_KEY = "wrap";
/** public key */
private static final String PUB_KEY = "pub";
/** private key */
private static final String PRIV_KEY = "priv";
/** Diffie-Hellman algorithm P parameter */
private static final String DH_P = "p";
/** Diffie-Hellman algorithm G parameter */
private static final String DH_G = "g";
/** Wildchar for "any" value in property name */
private static final String ANY = "*";
/** Regex for space */
private static final String SPACE_REGEX = "\\s";
/** Common separator between propert name elements */
private static final String SEP = ".";
/** lock object for synchronizing access to PSK store */
private final Object pskStoreLock = new Object();
/** lock object for synchronizing access to MGK store */
private final Object mgkStoreLock = new Object();
/** underlying representation of configuration properties */
private final Properties p;
/**
* @param prop provided in app-specific way
* @return singleton instance of MslProperties
*/
public static MslProperties getInstance(final Properties prop) {
if (prop == null) {
throw new IllegalArgumentException("NULL Properties");
}
return new MslProperties(prop);
}
/**
* @param p properties extracted from the configuration file
*/
private MslProperties(final Properties p) {
this.p = p;
}
/* ****************************
* ENTITY-SPECIFIC PROPERTIES *
******************************/
/**
* @param entityId entity identity
* @return names of entity authentication schemes supported by given entity
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Set<String> getSupportedEntityAuthenticationSchemes(final String entityId) throws ConfigurationException {
return split(getWildcharProperty(ENTITY_AUTH_SCHEMES, entityId));
}
/**
* @param entityId entity identity
* @return names of entity authentication schemes supported by given entity
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Set<String> getSupportedUserAuthenticationSchemes(final String entityId) throws ConfigurationException {
return split(getWildcharProperty(ENTITY_UAUTH_SCHEMES, entityId));
}
/**
* @param entityId entity identity
* @return names of key exchange schemes supported by given entity
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Set<String> getSupportedKeyExchangeSchemes(final String entityId) throws ConfigurationException {
return split(getWildcharProperty(ENTITY_KX_SCHEMES, entityId));
}
/**
/**
* @param entityId entity identity
* @param userId user identity
* @return names of key exchange scheme supported by given entity
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Set<String> getSupportedKeyExchangeSchemes(final String entityId, final String userId) throws ConfigurationException {
return getSupportedKeyExchangeSchemes(entityId);
}
/**
* @param entityId entity identity
* @return ID of Diffie-Hellman parameters to be used by given entity
* @throws ConfigurationException if the value is not defined or is not valid
*/
public String getEntityDiffieHellmanParametersId(final String entityId) throws ConfigurationException {
return getWildcharProperty(ENTITY_DH_ID, entityId);
}
/**
* @return mappings between entity identity and { encryption, hmac, wrapping} hex-encoded pre-shared keys triplet
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Map<String,Triplet<String,String,String>> getPresharedKeyStore() throws ConfigurationException {
synchronized (pskStoreLock) {
return getTripletMap(ENTITY_PSK, ID, ENC_KEY, HMAC_KEY, WRAP_KEY, true, true, false);
}
}
/**
* @return mappings between entity identity and { encryption, hmac, wrapping} hex-encoded mgk keys triplet
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Map<String,Triplet<String,String,String>> getMgkKeyStore() throws ConfigurationException {
synchronized (mgkStoreLock) {
return getTripletMap(ENTITY_MGK, ID, ENC_KEY, HMAC_KEY, WRAP_KEY, true, true, false);
}
}
/**
* @param entityId identity identity
* @return ID of the { encryption, hmac } key set to be used by this entity for issuing service tokens
* @throws ConfigurationException if the value is not defined or is not valid
*/
public String getServiceTokenKeySetId(final String entityId) throws ConfigurationException {
return getRequiredProperty(ENTITY_STOKEN_KEY_ID + entityId);
}
/**
* @param entityId entity identity, owner of RSA key pair used for RSA entity authentication
* @return ID of the RSA key pair to be used for specified entity's authentication
* @throws ConfigurationException if the value is not defined or is not valid
*/
public String getRsaKeyId(final String entityId) throws ConfigurationException {
return getWildcharProperty(ENTITY_RSA_KEY_ID, entityId);
}
/**
* add pre-shared key entry; it can be called by the client app
* @param pskEntry { entityId, encryptionKey, hmacKey}. Wrapping key is assumed to be derived.
* @throws ConfigurationException if the value is not defined or is not valid
*/
public void addPresharedKeys(final Triplet<String,String,String> pskEntry) throws ConfigurationException {
addKeyTriplet(pskEntry, ENTITY_PSK, pskStoreLock);
}
/**
* add MGK key entry; it can be called by the client app
* @param mgkEntry { entityId, encryptionKey, hmacKey}. Wrapping key is assumed to be derived.
* @throws ConfigurationException if the value is not defined or is not valid
*/
public void addMgkKeys(final Triplet<String,String,String> mgkEntry) throws ConfigurationException {
addKeyTriplet(mgkEntry, ENTITY_MGK, mgkStoreLock);
}
/**
* @param entry {enc,hmac,wrap} key triplet to be added to the configuration
* @param prefix name of the key family
* @param lock suncronization object for this key family
* @throws ConfigurationException if the value is not defined or is not valid
*/
private void addKeyTriplet(final Triplet<String,String,String> entry, final String prefix, final Object lock) throws ConfigurationException {
if (entry == null) {
throw new IllegalArgumentException("NULL keys");
}
synchronized (lock) {
final int num = getCountProperty(prefix + NUM);
p.setProperty(prefix + NUM, String.valueOf(num + 1));
p.setProperty(prefix + ID + SEP + num, entry.x);
p.setProperty(prefix + ENC_KEY + SEP + num, entry.y);
if (entry.z != null)
p.setProperty(prefix + HMAC_KEY + SEP + num, entry.z);
}
}
/* **************************
* USER-SPECIFIC PROPERTIES *
****************************/
/**
* @param userId user id, corresponding to local user account of some kind. Has no meaning outside local context.
* @return ( email,password ) tuple for a given user ID
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Pair<String,String> getEmailPassword(final String userId) throws ConfigurationException {
if (userId == null || userId.trim().isEmpty()) {
throw new IllegalArgumentException("Undefined userId");
}
final Map<String,Pair<String,String>> map = getPairMap(USER_EP, ID, EMAIL, PWD, true, true);
final Pair<String,String> emailPwd = map.get(userId.trim());
if (emailPwd != null)
return emailPwd;
else
throw new ConfigurationException("Missing Email-Password Entry for User Id " + userId);
}
/**
* @return mappings between user email and user password
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Map<String,String> getEmailPasswordStore() throws ConfigurationException {
return getMap(USER_EP, EMAIL, PWD);
}
/* *******************************
* MSL ECOSYSTEM-WIDE PROPERTIES *
*********************************/
/**
* @return MSL {encryption, HMAC, and wrapping} keys triplet.
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Triplet<String,String,String> getMslKeys() throws ConfigurationException {
return new Triplet<String,String,String>(
getRequiredProperty(MSL_KEY_ENC),
getRequiredProperty(MSL_KEY_HMAC),
getRequiredProperty(MSL_KEY_WRAP)
);
}
/**
* @return mappings between RSA key pair ID and { public, private } RSA key pair tuples
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Map<String,Pair<String,String>> getRsaKeyStore() throws ConfigurationException {
return getPairMap(MSL_RSA, ID, PUB_KEY, PRIV_KEY, true, false);
}
/**
* @return mappings between Diffie-Hellman parameters ID and actual Diffie-Hellman (P,G) parameters
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Map<String,Pair<String,String>> getDHParameterStore() throws ConfigurationException {
return getPairMap(MSL_DH, ID, DH_P, DH_G, true, true);
}
/**
* @param keyId ID of the { encryption, hmac } key pair used for service token issuing
* @return { encryption, hmac } key pair
* @throws ConfigurationException if the value is not defined or is not valid
*/
public Pair<String,String> getServiceTokenKeys(final String keyId) throws ConfigurationException {
return new Pair<String,String>(getRequiredProperty(MSL_STOKEN_KEY_ENC + keyId), getRequiredProperty(MSL_STOKEN_KEY_HMAC + keyId));
}
/**
* @return Master Token renewal offset in milliseconds
* @throws ConfigurationException if the value is not defined or is not valid
*/
public int getMasterTokenRenewalOffset() throws ConfigurationException {
return getCountProperty(MSL_MTOKEN_RENEWAL_OFFSET);
}
/**
* @return Master Token expiration offset in milliseconds
* @throws ConfigurationException if the value is not defined or is not valid
*/
public int getMasterTokenExpirationOffset() throws ConfigurationException {
return getCountProperty(MSL_MTOKEN_EXPIRATION_OFFSET);
}
/**
* @return Master Token non-replay ID window
* @throws ConfigurationException if the value is not defined or is not valid
*/
public int getMasterTokenNonReplayIdWindow() throws ConfigurationException {
return getCountProperty(MSL_MTOKEN_NON_REPLAY_ID_WINDOW);
}
/**
* @return Master Token's max allowed skipped sequence numbers still allowed for renewal
* @throws ConfigurationException if the value is not defined or is not valid
*/
public int getMasterTokenMaxSkipped() throws ConfigurationException {
return getCountProperty(MSL_MTOKEN_MAX_SKIPPED);
}
/**
* @return User ID Token renewal offset in milliseconds
* @throws ConfigurationException if the value is not defined or is not valid
*/
public int getUserIdTokenRenewalOffset() throws ConfigurationException {
return getCountProperty(MSL_UITOKEN_RENEWAL_OFFSET);
}
/**
* @return User ID Token expiration offset in milliseconds
* @throws ConfigurationException if the value is not defined or is not valid
*/
public int getUserIdTokenExpirationOffset() throws ConfigurationException {
return getCountProperty(MSL_UITOKEN_EXPIRATION_OFFSET);
}
/* ************************
* APPLICATION PROPERTIES *
**************************/
/**
* @return number of threads configured for "this" MslControl
* @throws ConfigurationException if the value is not defined or is not valid
*/
public int getNumMslControlThreads() throws ConfigurationException {
return getCountProperty(APP_CTRL_NUM_THR);
}
/**
* @return IP port to be used by "this" MSL server for listenning to incoming MSL messages
* @throws ConfigurationException if server port is not defined or is not valid
*/
public int getServerPort() throws ConfigurationException {
return getCountProperty(APP_SERVER_PORT);
}
/**
* @return list of entity authentication handle class names
* @throws ConfigurationException if the value is not defined or is not valid
*/
public List<String> getEntityAuthenticationHandles() throws ConfigurationException {
return getValueList(APP_ENTITY_AUTH_HANDLE);
}
/**
* @return list of key exchange handle class names
* @throws ConfigurationException if the value is not defined or is not valid
*/
public List<String> getKeyExchangeHandles() throws ConfigurationException {
return getValueList(APP_KEYX_HANDLE);
}
/**
* @return list of user authentication handle class names
* @throws ConfigurationException if the value is not defined or is not valid
*/
public List<String> getUserAuthenticationHandles() throws ConfigurationException {
return getValueList(APP_USER_AUTH_HANDLE);
}
/**
* @param prefix property name prefix
* @return subset of properties with the given name prefix. Prefix is removed.
* @throws ConfigurationException
*/
public Map<String,String> getPropertyFamily(String prefix) throws ConfigurationException {
if (prefix == null || prefix.trim().length() == 0)
throw new IllegalArgumentException("NULL prefix");
prefix = prefix.trim();
if (!prefix.endsWith(SEP)) prefix += SEP;
final Map<String,String> propFamily = new HashMap<String,String>();
for (String name : p.stringPropertyNames()) {
if (name.startsWith(prefix))
propFamily.put(name.substring(prefix.length()), p.getProperty(name));
}
return propFamily;
}
/* ****************
* Helper classes *
******************/
/**
* @param name prefix for all property names in the property triplets
* @return list of property values
* @throws ConfigurationException if the value is not defined or is not valid
*/
private List<String> getValueList(final String name) throws ConfigurationException {
final int num = getCountProperty(name + NUM);
final ArrayList<String> values = new ArrayList<String>(num);
for (int i = 0; i < num; i++) {
values.add(getRequiredProperty(name + i));
}
return values;
}
/**
* @param prefix prefix for all property names
* @param key suffix for property key names
* @param value suffix for property value names
* @return (key,value) map
* @throws ConfigurationException if the value is not defined or is not valid
*/
private Map<String,String> getMap(final String prefix, final String key, final String value) throws ConfigurationException {
final int num = getCountProperty(prefix + NUM);
final Map<String,String> map = new HashMap<String,String>(num);
for (int i = 0; i < num; i++) {
map.put(getRequiredProperty(prefix + key + SEP + i), getRequiredProperty(prefix + value + SEP + i));
}
return map;
}
/**
* @param prefix prefix for all property names in the property pairs
* @param key name of the property reprsenting the key
* @param name1 name of the property reprsenting the first value
* @param name2 name of the property reprsenting the second value
* @param required1 whether the property with name1 is required to be defined
* @param required2 whether the property with name2 is required to be defined
* @return Map of property pair values
* @throws ConfigurationException if the value is not defined or is not valid
*/
private Map<String,Pair<String,String>> getPairMap(
final String prefix, final String key,
final String name1, final String name2,
final boolean required1, final boolean required2)
throws ConfigurationException
{
final int num = getCountProperty(prefix + NUM);
final Map<String,Pair<String,String>> map = new HashMap<String,Pair<String,String>>(num);
for (int i = 0; i < num; i++) {
map.put(getRequiredProperty(prefix + key + SEP + i),
new Pair<String,String>(
required1 ? getRequiredProperty(prefix + name1 + SEP + i) : getProperty(prefix + name1 + SEP + i),
required2 ? getRequiredProperty(prefix + name2 + SEP + i) : getProperty(prefix + name2 + SEP + i)
)
);
}
return map;
}
/**
* @param prefix prefix for all property names in the property triplets
* @param key name of the property reprsenting the key
* @param name1 name of the property reprsenting the first value
* @param name2 name of the property reprsenting the second value
* @param name3 name of the property reprsenting the second value
* @param required1 whether the property with name1 is required to be defined
* @param required2 whether the property with name2 is required to be defined
* @param required3 whether the property with name3 is required to be defined
* @return Map of property pair values
* @throws ConfigurationException if the value is not defined or is not valid
*/
private Map<String,Triplet<String,String,String>> getTripletMap(
final String prefix, final String key,
final String name1, final String name2, final String name3,
final boolean required1, final boolean required2, final boolean required3)
throws ConfigurationException
{
final int num = getCountProperty(prefix + NUM);
final Map<String,Triplet<String,String,String>> map = new HashMap<String,Triplet<String,String,String>>(num);
for (int i = 0; i < num; i++) {
map.put(getRequiredProperty(prefix + key + SEP + i),
new Triplet<String,String,String>(
required1 ? getRequiredProperty(prefix + name1 + SEP + i) : getProperty(prefix + name1 + SEP + i),
required2 ? getRequiredProperty(prefix + name2 + SEP + i) : getProperty(prefix + name2 + SEP + i),
required3 ? getRequiredProperty(prefix + name3 + SEP + i) : getProperty(prefix + name3 + SEP + i)
)
);
}
return map;
}
/**
* return non-mandatory property.
* @param name property name
* @return property value or null if property is missing
* @throws ConfigurationException if property exists but its value is not defined
*/
private String getProperty(final String name) throws ConfigurationException {
final String value = p.getProperty(name);
if (value != null) {
if (value.trim().length() != 0) {
return value.trim();
} else {
throw new ConfigurationException(String.format("Property %s with blank value", name));
}
} else if (p.containsKey(name)) {
throw new ConfigurationException(String.format("Property %s with no value", name));
} else {
return null;
}
}
/**
* return mandatory non-negative integer property value
* @param name mandatory non-negative integer property name
* @return mandatory non-negative integer property value
* @throws ConfigurationException if mandatory property is missing or has negative value
*/
private int getCountProperty(final String name) throws ConfigurationException {
final String s = getRequiredProperty(name);
final int num = Integer.parseInt(s);
if (num < 0) {
throw new ConfigurationException(String.format("Invalid Property %s : %s --> %d", name, s, num));
}
return num;
}
/**
* return mandatory property value
* @param name mandatory property name
* @return mandatory property value
* @throws ConfigurationException if mandatory property is missing or has no value
*/
private String getRequiredProperty(final String name) throws ConfigurationException {
final String s = getProperty(name);
if (s == null) {
throw new ConfigurationException("Missing Property " + name);
}
return s;
}
/**
* return the value of mandatory property that supports wildchar
* @param prefix property name prefix
* @param id property name suffix which can be replaced with "*" to match any suffix
* @return mandatory property value
* @throws ConfigurationException if mandatory property is missing or has no value
*/
private String getWildcharProperty(final String prefix, String id) throws ConfigurationException {
String s = getProperty(prefix + id);
if (s == null) {
s = getProperty(prefix + ANY);
}
if (s == null) {
throw new ConfigurationException(String.format("Missing Property %s(%s|%s)", prefix, id, ANY));
}
return s;
}
/**
* parse multi-value property into a Set of unique values
* @param value string value that may contain multiple space-separated values
* @return set of values parsed out of the input string
*/
private Set<String> split(final String value) {
return Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(value.split(SPACE_REGEX))));
}
@Override
public String toString() {
return SharedUtil.toString(this);
}
}
| 1,986 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/msg/MessageConfig.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.msg;
import mslcli.common.util.SharedUtil;
/**
* <p>MSL message security configuration data object.</p>
*
* @author Vadim Spector <[email protected]>
*/
public final class MessageConfig {
/** whether message should be encrypted */
public boolean isEncrypted;
/** whether message should be integrity protected */
public boolean isIntegrityProtected;
/** whether message should be non-replayable */
public boolean isNonReplayable;
@Override
public String toString() {
return String.format("%s{encrypted: %b, integrity protected: %b, non-replayable: %b}",
SharedUtil.toString(this), isEncrypted, isIntegrityProtected, isNonReplayable);
}
}
| 1,987 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/keyx/DiffieHellmanExchangeHandle.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.keyx;
import java.security.KeyPair;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.keyx.DiffieHellmanExchange;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.util.AuthenticationUtils;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
/**
* <p>
* Diffie-hellman Key Exchange handle class
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class DiffieHellmanExchangeHandle extends KeyExchangeHandle {
/**
* default constructor
*/
public DiffieHellmanExchangeHandle() {
super(KeyExchangeScheme.DIFFIE_HELLMAN);
}
@Override
public KeyRequestData getKeyRequestData(final AppContext appCtx, final CmdArguments args)
throws ConfigurationException, IllegalCmdArgumentException, MslKeyExchangeException
{
if (args.getKeyExchangeMechanism() != null) {
throw new IllegalCmdArgumentException("No Key Wrapping Mechanism Needed for Key Exchange " + args.getKeyExchangeScheme());
}
final String diffieHellmanParametersId = appCtx.getDiffieHellmanParametersId(args.getEntityId());
final KeyPair dhKeyPair = appCtx.generateDiffieHellmanKeys(diffieHellmanParametersId);
return new DiffieHellmanExchange.RequestData(diffieHellmanParametersId,
((DHPublicKey)dhKeyPair.getPublic()).getY(), (DHPrivateKey)dhKeyPair.getPrivate());
}
@Override
public KeyExchangeFactory getKeyExchangeFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils) {
return new DiffieHellmanExchange(appCtx.getDiffieHellmanParameters(), authutils);
}
}
| 1,988 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/keyx/JsonWebEncryptionLadderExchangeHandle.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.keyx;
import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.keyx.JsonWebEncryptionLadderExchange;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.WrapCryptoContextRepository;
import com.netflix.msl.util.AuthenticationUtils;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.WrapCryptoContextRepositoryHandle;
/**
* <p>
* Json Web Encryption Ladder Key Exchange Handle class
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class JsonWebEncryptionLadderExchangeHandle extends KeyExchangeHandle {
/**
* default constructor
*/
public JsonWebEncryptionLadderExchangeHandle() {
super(KeyExchangeScheme.JWE_LADDER);
}
@Override
public KeyRequestData getKeyRequestData(final AppContext appCtx, final CmdArguments args)
throws ConfigurationException, IllegalCmdArgumentException, MslKeyExchangeException
{
final JsonWebEncryptionLadderExchange.Mechanism m = getKeyExchangeMechanism(
JsonWebEncryptionLadderExchange.Mechanism.class, args.getKeyExchangeMechanism());
final byte[] wrapdata;
if (m == JsonWebEncryptionLadderExchange.Mechanism.WRAP) {
wrapdata = getRepo(appCtx, args).getLastWrapdata();
if (wrapdata == null)
throw new IllegalCmdArgumentException(String.format("No Key Wrapping Data Found for {%s %s}", getScheme().name(), m));
} else {
wrapdata = null;
}
return new JsonWebEncryptionLadderExchange.RequestData(m, wrapdata);
}
@Override
public KeyExchangeFactory getKeyExchangeFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils)
throws ConfigurationException, IllegalCmdArgumentException
{
return new JsonWebEncryptionLadderExchange(getRepo(appCtx, args), authutils);
}
}
| 1,989 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/keyx/KeyExchangeHandle.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.keyx;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.WrapCryptoContextRepository;
import com.netflix.msl.util.AuthenticationUtils;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.SharedUtil;
import mslcli.common.util.WrapCryptoContextRepositoryHandle;
import mslcli.common.util.WrapCryptoContextRepositoryWrapper;
/**
* <p>
* Handle to facilitate plugin design for support of arbitrary key exchange schemes.
* Derived classes must have default constructors.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public abstract class KeyExchangeHandle {
/**
* @param scheme key exchange scheme
*/
protected KeyExchangeHandle(final KeyExchangeScheme scheme) {
this.scheme = scheme;
}
/**
* @return key exchange scheme
*/
public final KeyExchangeScheme getScheme() {
return scheme;
}
/**
* @param appCtx application context
* @param args command line arguments
* @return key exchange request data
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
* @throws MslKeyExchangeException
*/
public abstract KeyRequestData getKeyRequestData(final AppContext appCtx, final CmdArguments args)
throws ConfigurationException, IllegalCmdArgumentException, MslKeyExchangeException;
/**
* @param appCtx application context
* @param args command line arguments
* @param authutils authentication utilities
* @return key exchange request data
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public abstract KeyExchangeFactory getKeyExchangeFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils)
throws ConfigurationException, IllegalCmdArgumentException;
/**
* convenience method
* @param clazz class defining Enum values for key exchange mechanisms for a given key exchange scheme
* @param kxmName key exchange mechanism name
* @param <T> enumerated type
* @return key eachange mechanism Enum value
* @throws IllegalCmdArgumentException
*/
protected <T extends Enum<T>> T getKeyExchangeMechanism(final Class<T> clazz, final String kxmName)
throws IllegalCmdArgumentException
{
final List<T> values = Arrays.asList(clazz.getEnumConstants());
if (kxmName == null || kxmName.trim().isEmpty()) {
throw new IllegalCmdArgumentException(String.format("KeyExchange[%s]: Unspecified Mechanism, Valid %s",
scheme.name(), values));
}
try {
return Enum.valueOf(clazz, kxmName.trim());
} catch (IllegalArgumentException e) {
throw new IllegalCmdArgumentException(String.format("KeyExchange[%s]: Illegal Mechanism %s, Valid %s",
scheme.name(), kxmName.trim(), values));
}
}
@Override
public final String toString() {
return SharedUtil.toString(this, scheme);
}
/**
* extension of WrapCryptoContextRepositoryWrapper class to intercept and report calls
*/
protected static final class AppWrapCryptoContextRepository extends WrapCryptoContextRepositoryWrapper {
/**
* @param appCtx application context
* @param entityId entity identity
* @param scheme key exchange scheme
*/
public AppWrapCryptoContextRepository(final AppContext appCtx, final String entityId, final KeyExchangeScheme scheme) {
super(new SimpleWrapCryptoContextRepository(entityId, scheme));
this.appCtx = appCtx;
}
@Override
public void addCryptoContext(final byte[] wrapdata, final ICryptoContext cryptoContext) {
appCtx.info(String.format("%s: addCryptoContext(%s %s)", this, SharedUtil.getWrapDataInfo(wrapdata), SharedUtil.toString(cryptoContext)));
super.addCryptoContext(wrapdata, cryptoContext);
}
@Override
public ICryptoContext getCryptoContext(final byte[] wrapdata) {
appCtx.info(String.format("%s: getCryptoContext(%s)", this, SharedUtil.getWrapDataInfo(wrapdata)));
return super.getCryptoContext(wrapdata);
}
@Override
public void removeCryptoContext(final byte[] wrapdata) {
appCtx.info(String.format("%s: delCryptoContext(%s)", this, SharedUtil.getWrapDataInfo(wrapdata)));
super.removeCryptoContext(wrapdata);
}
/** application context */
private final AppContext appCtx;
}
/**
* Lazy initialization of WrapCryptoContextRepositoryHandle for a given entity identity
*
* @param appCtx application context
* @param args command line arguments
* @return WrapCryptoContextRepositoryHandle instance
* @throws IllegalCmdArgumentException
*/
protected WrapCryptoContextRepositoryHandle getRepo(final AppContext appCtx, final CmdArguments args)
throws IllegalCmdArgumentException
{
synchronized (rep) {
WrapCryptoContextRepositoryHandle r = rep.get(args.getEntityId());
if (r == null)
rep.put(args.getEntityId(), r = new AppWrapCryptoContextRepository(appCtx, args.getEntityId(), getScheme()));
return r;
}
}
/** key exchange scheme */
protected final KeyExchangeScheme scheme;
/** mapping of key wrapping data to crypto context */
private final Map<String,WrapCryptoContextRepositoryHandle> rep = new HashMap<String,WrapCryptoContextRepositoryHandle>();
}
| 1,990 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/keyx/AsymmetricWrappedExchangeHandle.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.keyx;
import java.security.KeyPair;
import com.netflix.msl.keyx.AsymmetricWrappedExchange;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.util.AuthenticationUtils;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
/**
* <p>
* Asymmetric Wrapped Key Exchange handle class
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class AsymmetricWrappedExchangeHandle extends KeyExchangeHandle {
/**
* default constructor
*/
public AsymmetricWrappedExchangeHandle() {
super(KeyExchangeScheme.ASYMMETRIC_WRAPPED);
}
@Override
public KeyRequestData getKeyRequestData(final AppContext appCtx, final CmdArguments args)
throws IllegalCmdArgumentException
{
final AsymmetricWrappedExchange.RequestData.Mechanism m = getKeyExchangeMechanism(
AsymmetricWrappedExchange.RequestData.Mechanism.class, args.getKeyExchangeMechanism());
if (aweKeyPair == null) {
aweKeyPair = appCtx.generateAsymmetricWrappedExchangeKeyPair();
}
return new AsymmetricWrappedExchange.RequestData(DEFAULT_AWE_KEY_PAIR_ID, m, aweKeyPair.getPublic(), aweKeyPair.getPrivate());
}
@Override
public KeyExchangeFactory getKeyExchangeFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils) {
return new AsymmetricWrappedExchange(authutils);
}
/**
* Cached RSA Key Pair for asymmetric key wrap key exchange to avoid expensive key pair generation.
* This is an optimization specific to this application, to avoid annoying delays in generating
* 4096-bit RSA key pairs. Real-life implementations should not re-use key wrapping keys
* too many times.
*/
private KeyPair aweKeyPair = null;
/** default asymmetric key wrap exchange key pair id - the value should not matter */
private static final String DEFAULT_AWE_KEY_PAIR_ID = "default_awe_key_id";
}
| 1,991 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/keyx/SimpleWrapCryptoContextRepository.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.keyx;
import java.nio.ByteBuffer;
import java.util.LinkedHashMap;
import java.util.Map;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.WrapCryptoContextRepository;
import mslcli.common.util.SharedUtil;
import mslcli.common.util.WrapCryptoContextRepositoryHandle;
/**
* <p>
* Memory-backed Wrap Crypto Context Repository.
* Instance is specific to entity ID and key exchange scheme.
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class SimpleWrapCryptoContextRepository implements WrapCryptoContextRepositoryHandle {
/** mappings between wrapping key blob and crypto context */
private final Map<ByteBuffer,ICryptoContext> repository = new LinkedHashMap<ByteBuffer,ICryptoContext>();
/** entity identity of this repository */
protected final String entityId;
/** key exchange scheme of this repository */
protected final KeyExchangeScheme scheme;
/**
* Ctor
* @param entityId entity ID
* @param scheme key exchange scheme
*/
public SimpleWrapCryptoContextRepository(final String entityId, final KeyExchangeScheme scheme) {
this.entityId = entityId;
this.scheme = scheme;
}
/**
* @see com.netflix.msl.keyx.WrapCryptoContextRepository#addCryptoContext(byte[],ICryptoContext)
*/
@Override
public synchronized void addCryptoContext(final byte[] wrapdata, final ICryptoContext cryptoContext) {
repository.put(ByteBuffer.wrap(wrapdata), cryptoContext);
}
/**
* @see com.netflix.msl.keyx.WrapCryptoContextRepository#getCryptoContext(byte[])
*/
@Override
public synchronized ICryptoContext getCryptoContext(final byte[] wrapdata) {
return repository.get(ByteBuffer.wrap(wrapdata));
}
/**
* @see com.netflix.msl.keyx.WrapCryptoContextRepository#removeCryptoContext(byte[])
*/
@Override
public synchronized void removeCryptoContext(final byte[] wrapdata) {
repository.remove(ByteBuffer.wrap(wrapdata));
}
/**
* @see mslcli.common.util.WrapCryptoContextRepositoryHandle#getLastWrapdata()
*/
@Override
public synchronized byte[] getLastWrapdata() {
ByteBuffer bb1 = null;
for (ByteBuffer bb : repository.keySet()) {
bb1 = bb;
}
return (bb1 != null) ? bb1.array() : null;
}
@Override
public String toString() {
return SharedUtil.toString(this, entityId, scheme);
}
}
| 1,992 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/keyx/SymmetricWrappedExchangeHandle.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.keyx;
import java.security.KeyPair;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.keyx.SymmetricWrappedExchange;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.util.AuthenticationUtils;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
/**
* <p>
* Symmetric Wrapped Key Exchange handle class
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class SymmetricWrappedExchangeHandle extends KeyExchangeHandle {
/**
* default constructor
*/
public SymmetricWrappedExchangeHandle() {
super(KeyExchangeScheme.SYMMETRIC_WRAPPED);
}
@Override
public KeyRequestData getKeyRequestData(final AppContext appCtx, final CmdArguments args)
throws ConfigurationException, IllegalCmdArgumentException, MslKeyExchangeException
{
final SymmetricWrappedExchange.KeyId keyId = getKeyExchangeMechanism(
SymmetricWrappedExchange.KeyId.class, args.getKeyExchangeMechanism());
return new SymmetricWrappedExchange.RequestData(keyId);
}
@Override
public KeyExchangeFactory getKeyExchangeFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils) {
return new SymmetricWrappedExchange(authutils);
}
}
| 1,993 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/keyx/JsonWebKeyLadderExchangeHandle.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.keyx;
import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.keyx.JsonWebKeyLadderExchange;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.WrapCryptoContextRepository;
import com.netflix.msl.util.AuthenticationUtils;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.WrapCryptoContextRepositoryHandle;
/**
* <p>
* Json Web key Ladder Key Exchange Handle class
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class JsonWebKeyLadderExchangeHandle extends KeyExchangeHandle {
/**
* default constructor
*/
public JsonWebKeyLadderExchangeHandle() {
super(KeyExchangeScheme.JWK_LADDER);
}
@Override
public KeyRequestData getKeyRequestData(final AppContext appCtx, final CmdArguments args)
throws ConfigurationException, IllegalCmdArgumentException, MslKeyExchangeException
{
final JsonWebKeyLadderExchange.Mechanism m = getKeyExchangeMechanism(
JsonWebKeyLadderExchange.Mechanism.class, args.getKeyExchangeMechanism());
final byte[] wrapdata;
if (m == JsonWebKeyLadderExchange.Mechanism.WRAP) {
wrapdata = getRepo(appCtx, args).getLastWrapdata();
if (wrapdata == null)
throw new IllegalCmdArgumentException(String.format("No Key Wrapping Data Found for {%s %s}", getScheme().name(), m));
} else {
wrapdata = null;
}
return new JsonWebKeyLadderExchange.RequestData(m, wrapdata);
}
@Override
public KeyExchangeFactory getKeyExchangeFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils)
throws ConfigurationException, IllegalCmdArgumentException
{
return new JsonWebKeyLadderExchange(getRepo(appCtx, args), authutils);
}
}
| 1,994 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/userauth/UserAuthenticationHandle.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.userauth;
import java.io.Console;
import java.util.Map;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslStore;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.SharedUtil;
/**
* <p>
* Common abstract class for plugin implementation of user authentication mechanisms
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public abstract class UserAuthenticationHandle {
/** user authentication scheme */
private final UserAuthenticationScheme scheme;
/**
* @param scheme user authentication scheme
*/
public UserAuthenticationHandle(final UserAuthenticationScheme scheme) {
this.scheme = scheme;
}
/**
* @return entity authentication scheme
*/
public final UserAuthenticationScheme getScheme() {
return scheme;
}
/**
* @param appCtx application context
* @param args command line arguments
* @param mslStore MSL store
* @return entity authentication data to be included into a message
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public abstract UserAuthenticationData getUserAuthenticationData(final AppContext appCtx, final CmdArguments args, final MslStore mslStore)
throws ConfigurationException, IllegalCmdArgumentException;
/**
* @param appCtx application context
* @param args command line arguments
* @param authutils authentication utilities
* @return entity authentication factory
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public abstract UserAuthenticationFactory getUserAuthenticationFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils)
throws ConfigurationException, IllegalCmdArgumentException;
/**
* @param appCtx application context
* @param args runtime arguments
* @return current user id
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
public String getUserId(final AppContext appCtx, final CmdArguments args)
throws ConfigurationException, IllegalCmdArgumentException
{
return args.getUserId();
}
/**
* @param args runtime arguments
* @param name handle-specific argument name, with "-ext.uah.scheme." prefix implied
* @return argument value
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
protected String getHandleArg(final CmdArguments args, final String name)
throws ConfigurationException, IllegalCmdArgumentException
{
return _getHandleArg(args, name, false);
}
/**
* @param args runtime arguments
* @param name handle-specific argument name, with "-ext.uah.scheme." prefix implied
* @return argument value
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
protected String getHandlePwdArg(final CmdArguments args, final String name)
throws ConfigurationException, IllegalCmdArgumentException
{
return _getHandleArg(args, name, true);
}
/**
* @param args runtime arguments
* @param name handle-specific argument name, with "-ext.uah.scheme." prefix implied
* @param isPassword true if the argument is password, so its value should not be echoed
* @return argument value
* @throws ConfigurationException
* @throws IllegalCmdArgumentException
*/
private String _getHandleArg(final CmdArguments args, final String name, final boolean isPassword)
throws ConfigurationException, IllegalCmdArgumentException
{
if (args == null)
throw new IllegalArgumentException(String.format("%s: NULL arguments", this));
if (name == null || name.length() == 0)
throw new IllegalArgumentException(String.format("%s: NULL or empty property name", this));
final String prefix = "uah." + scheme.toString().toLowerCase();
final String value;
final Map<String,String> m = args.getExtensionProperties(prefix);
if (!m.isEmpty()) {
value = m.get(name);
if (value == null)
throw new IllegalCmdArgumentException(String.format("%s: Missing Extension Property \"%s.%s\" - %s", this, prefix, name, m.toString()));
} else if (args.isInteractive()) {
final Console cons = System.console();
if (cons != null) {
if (isPassword)
value = new String(cons.readPassword("%s.%s> ", prefix, name));
else
value = cons.readLine("%s.%s> ", prefix, name);
} else {
throw new IllegalCmdArgumentException(String.format("%s: Cannot get Console", this));
}
} else {
throw new IllegalCmdArgumentException(String.format("%s: No support in non-interactive mode and without \"%s.%s\" extension property",
this, prefix, name));
}
return value;
}
@Override
public final String toString() {
return SharedUtil.toString(this, scheme);
}
}
| 1,995 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/userauth/SimpleEmailPasswordStore.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.userauth;
import java.util.HashMap;
import java.util.Map;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.EmailPasswordStore;
import mslcli.common.tokens.SimpleUser;
import mslcli.common.util.SharedUtil;
/**
* <p>Memory-backed user email/password store.</p>
*
* @author Vadim Spector <[email protected]>
*/
public class SimpleEmailPasswordStore implements EmailPasswordStore {
/**
* <p>Create a new email/password store that will authenticate the provided
* users.</p>
*
* @param emailPasswords map of email addresses onto passwords.
*/
public SimpleEmailPasswordStore(final Map<String,String> emailPasswords) {
if (emailPasswords == null) {
throw new IllegalArgumentException("NULL emal-password map");
}
this.emailPasswords.putAll(emailPasswords);
}
/* (non-Javadoc)
* @see com.netflix.msl.userauth.EmailPasswordStore#isUser(java.lang.String, java.lang.String)
*/
@Override
public MslUser isUser(final String email, final String password) {
final String expectedPassword = emailPasswords.get(email);
if (expectedPassword == null || !expectedPassword.equals(password))
return null;
return new SimpleUser(email);
}
@Override
public String toString() {
return SharedUtil.toString(this);
}
/** Email/password database. */
private final Map<String,String> emailPasswords = new HashMap<String,String>();
}
| 1,996 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/userauth/EmailPasswordUserAuthenticationHandle.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.userauth;
import com.netflix.msl.userauth.EmailPasswordAuthenticationData;
import com.netflix.msl.userauth.EmailPasswordAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslStore;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.util.AppContext;
import mslcli.common.Pair;
import mslcli.common.util.ConfigurationException;
/**
* <p>
* Plugin implementation for email-password user authentication functionality
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class EmailPasswordUserAuthenticationHandle extends UserAuthenticationHandle {
/**
* default ctor
*/
public EmailPasswordUserAuthenticationHandle() {
super(UserAuthenticationScheme.EMAIL_PASSWORD);
}
@Override
public UserAuthenticationData getUserAuthenticationData(final AppContext appCtx, final CmdArguments args, final MslStore mslStore)
throws ConfigurationException, IllegalCmdArgumentException
{
final String userId = args.getUserId();
if (userId == null || userId.trim().length() == 0)
return null;
final boolean interactive = args.isInteractive();
try {
final Pair<String,String> ep = appCtx.getProperties().getEmailPassword(userId);
return new EmailPasswordAuthenticationData(ep.x, ep.y);
} catch (ConfigurationException e) {
final String email = getHandleArg(args, "email");
final String pwd = getHandlePwdArg(args, "password");
return new EmailPasswordAuthenticationData(email, pwd);
}
}
@Override
public UserAuthenticationFactory getUserAuthenticationFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils)
throws ConfigurationException, IllegalCmdArgumentException
{
return new EmailPasswordAuthenticationFactory(appCtx.getEmailPasswordStore(), authutils);
}
}
| 1,997 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/tokens/SimpleUser.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.tokens;
import com.netflix.msl.tokens.MslUser;
import mslcli.common.util.SharedUtil;
/**
* <p>A MSL user that is just the user ID.</p>
*
* @author Vadim Spector <[email protected]>
*/
public class SimpleUser implements MslUser {
/**
* <p>Create a new MSL user with the given user ID.</p>
*
* @param userId the user ID.
*/
public SimpleUser(final String userId) {
this.userId = userId;
}
/* (non-Javadoc)
* @see com.netflix.msl.tokens.MslUser#getEncoded()
*/
@Override
public String getEncoded() {
return userId;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return SharedUtil.toString(this, userId);
}
/** User string representation. */
private final String userId;
}
| 1,998 |
0 |
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common
|
Create_ds/msl/examples/mslcli/client/src/main/java/mslcli/common/entityauth/PresharedEntityAuthenticationHandle.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.common.entityauth;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.entityauth.PresharedAuthenticationData;
import com.netflix.msl.entityauth.PresharedAuthenticationFactory;
import com.netflix.msl.util.AuthenticationUtils;
import mslcli.common.CmdArguments;
import mslcli.common.IllegalCmdArgumentException;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
/**
* <p>
* Plugin implementation for generating pre-shared keys entity authentication data and entity authentication factory
* </p>
*
* @author Vadim Spector <[email protected]>
*/
public class PresharedEntityAuthenticationHandle extends EntityAuthenticationHandle {
/**
* ctor
*/
public PresharedEntityAuthenticationHandle() {
super(EntityAuthenticationScheme.PSK);
}
@Override
public EntityAuthenticationData getEntityAuthenticationData(final AppContext appCtx, final CmdArguments args)
throws IllegalCmdArgumentException
{
return new PresharedAuthenticationData(args.getEntityId());
}
@Override
public EntityAuthenticationFactory getEntityAuthenticationFactory(final AppContext appCtx, final CmdArguments args, final AuthenticationUtils authutils)
throws ConfigurationException, IllegalCmdArgumentException
{
return new PresharedAuthenticationFactory(appCtx.getPresharedKeyStore(), authutils);
}
}
| 1,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.