index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/ExcludeMetricPredicate.java | /*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.airbnb.metrics;
import com.yammer.metrics.core.Metric;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricPredicate;
import org.apache.log4j.Logger;
import java.util.regex.Pattern;
/**
*
*/
public class ExcludeMetricPredicate implements MetricPredicate {
private final Logger logger = Logger.getLogger(getClass());
final String excludeRegex;
final Pattern pattern;
public ExcludeMetricPredicate(String excludeRegex) {
this.excludeRegex = excludeRegex;
this.pattern = Pattern.compile(excludeRegex);
}
@Override
public boolean matches(MetricName name, Metric metric) {
String n = MetricNameFormatter.format(name);
boolean excluded = pattern.matcher(n).matches();
if (excluded) {
if (logger.isTraceEnabled()) {
logger.trace("Metric " + n + " is excluded");
}
}
return !excluded;
}
}
| 9,800 |
0 | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/StatsDReporter.java | /*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.airbnb.metrics;
import com.timgroup.statsd.StatsDClient;
import com.yammer.metrics.core.*;
import com.yammer.metrics.reporting.AbstractPollingReporter;
import com.yammer.metrics.stats.Snapshot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.EnumSet;
import java.util.Map;
import java.util.TreeMap;
import static com.airbnb.metrics.Dimension.*;
/**
*
*/
public class StatsDReporter extends AbstractPollingReporter implements MetricProcessor<Long> {
static final Logger log = LoggerFactory.getLogger(StatsDReporter.class);
public static final String REPORTER_NAME = "kafka-statsd-metrics";
private final StatsDClient statsd;
private final Clock clock;
private final EnumSet<Dimension> dimensions;
private MetricPredicate metricPredicate;
private boolean isTagEnabled;
private Parser parser;
public StatsDReporter(MetricsRegistry metricsRegistry,
StatsDClient statsd,
EnumSet<Dimension> metricDimensions) {
this(metricsRegistry, statsd, REPORTER_NAME, MetricPredicate.ALL, metricDimensions, true);
}
public StatsDReporter(MetricsRegistry metricsRegistry,
StatsDClient statsd,
MetricPredicate metricPredicate,
EnumSet<Dimension> metricDimensions,
boolean isTagEnabled) {
this(metricsRegistry, statsd, REPORTER_NAME, metricPredicate, metricDimensions, isTagEnabled);
}
public StatsDReporter(MetricsRegistry metricsRegistry,
StatsDClient statsd,
String reporterName,
MetricPredicate metricPredicate,
EnumSet<Dimension> metricDimensions,
boolean isTagEnabled) {
super(metricsRegistry, reporterName);
this.statsd = statsd; //exception in statsd is handled by default NO_OP_HANDLER (do nothing)
this.clock = Clock.defaultClock();
this.parser = null; //postpone set it because kafka doesn't start reporting any metrics.
this.dimensions = metricDimensions;
this.metricPredicate = metricPredicate;
this.isTagEnabled = isTagEnabled;
}
@Override
public void run() {
try {
final long epoch = clock.time() / 1000;
if (parser == null) {
createParser(getMetricsRegistry());
}
sendAllKafkaMetrics(epoch);
} catch (RuntimeException ex) {
log.error("Failed to print metrics to statsd", ex);
}
}
private void createParser(MetricsRegistry metricsRegistry) {
if (isTagEnabled) {
final boolean isMetricsTagged = isTagged(metricsRegistry.allMetrics());
if (isMetricsTagged) {
log.info("Kafka metrics are tagged");
parser = new ParserForTagInMBeanName();
} else {
parser = new ParserForNoTag();
}
} else {
parser = new ParserForNoTag();
}
}
//kafka.common.AppInfo is not reliable, sometimes, not correctly loaded.
public boolean isTagged(Map<MetricName, Metric> metrics) {
for (MetricName metricName : metrics.keySet()) {
if ("kafka.common:type=AppInfo,name=Version".equals(metricName.getMBeanName())
|| metricName.hasScope()) {
return true;
}
}
return false;
}
private void sendAllKafkaMetrics(long epoch) {
final Map<MetricName, Metric> allMetrics = new TreeMap<MetricName, Metric>(getMetricsRegistry().allMetrics());
for (Map.Entry<MetricName, Metric> entry : allMetrics.entrySet()) {
sendAMetric(entry.getKey(), entry.getValue(), epoch);
}
}
private void sendAMetric(MetricName metricName, Metric metric, long epoch) {
log.debug("MBeanName[{}], Group[{}], Name[{}], Scope[{}], Type[{}]",
metricName.getMBeanName(), metricName.getGroup(), metricName.getName(),
metricName.getScope(), metricName.getType());
if (metricPredicate.matches(metricName, metric) && metric != null) {
try {
parser.parse(metricName);
metric.processWith(this, metricName, epoch);
} catch (Exception ignored) {
log.error("Error printing regular metrics:", ignored);
}
}
}
@Override
public void processCounter(MetricName metricName, Counter counter, Long context) throws Exception {
statsd.gauge(parser.getName(), counter.count(), parser.getTags());
}
@Override
public void processMeter(MetricName metricName, Metered meter, Long epoch) {
send(meter);
}
@Override
public void processHistogram(MetricName metricName, Histogram histogram, Long context) throws Exception {
send((Summarizable) histogram);
send((Sampling) histogram);
}
@Override
public void processTimer(MetricName metricName, Timer timer, Long context) throws Exception {
send((Metered) timer);
send((Summarizable) timer);
send((Sampling) timer);
}
@Override
public void processGauge(MetricName metricName, Gauge<?> gauge, Long context) throws Exception {
final Object value = gauge.value();
final Boolean flag = isDoubleParsable(value);
if (flag == null) {
log.debug("Gauge can only record long or double metric, it is " + value.getClass());
} else if (flag.equals(true)) {
statsd.gauge(parser.getName(), new Double(value.toString()), parser.getTags());
} else {
statsd.gauge(parser.getName(), new Long(value.toString()), parser.getTags());
}
}
protected static final Dimension[] meterDims = {count, meanRate, rate1m, rate5m, rate15m};
protected static final Dimension[] summarizableDims = {min, max, mean, stddev};
protected static final Dimension[] SamplingDims = {median, p75, p95, p98, p99, p999};
private void send(Metered metric) {
double[] values = {metric.count(), metric.meanRate(), metric.oneMinuteRate(),
metric.fiveMinuteRate(), metric.fifteenMinuteRate()};
for (int i = 0; i < values.length; ++i) {
sendDouble(meterDims[i], values[i]);
}
}
protected void send(Summarizable metric) {
double[] values = {metric.min(), metric.max(), metric.mean(), metric.stdDev()};
for (int i = 0; i < values.length; ++i) {
sendDouble(summarizableDims[i], values[i]);
}
}
protected void send(Sampling metric) {
final Snapshot snapshot = metric.getSnapshot();
double[] values = {snapshot.getMedian(), snapshot.get75thPercentile(), snapshot.get95thPercentile(),
snapshot.get98thPercentile(), snapshot.get99thPercentile(), snapshot.get999thPercentile()};
for (int i = 0; i < values.length; ++i) {
sendDouble(SamplingDims[i], values[i]);
}
}
private void sendDouble(Dimension dim, double value) {
if (dimensions.contains(dim)) {
statsd.gauge(parser.getName() + "." + dim.getDisplayName(), value, parser.getTags());
}
}
private Boolean isDoubleParsable(final Object o) {
if (o instanceof Float) {
return true;
} else if (o instanceof Double) {
return true;
} else if (o instanceof Byte) {
return false;
} else if (o instanceof Short) {
return false;
} else if (o instanceof Integer) {
return false;
} else if (o instanceof Long) {
return false;
} else if (o instanceof BigInteger) {
return false;
} else if (o instanceof BigDecimal) {
return true;
}
return null;
}
}
| 9,801 |
0 | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/Dimension.java | /*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.airbnb.metrics;
import java.util.EnumSet;
import java.util.Map;
import java.util.Properties;
/**
*
*/
public enum Dimension { //use name itself as suffix
count("count"),
meanRate("meanRate"),
rate1m("1MinuteRate"),
rate5m("5MinuteRate"),
rate15m("15MinuteRate"),
min("min"),
max("max"),
mean("mean"),
stddev("stddev"),
median("median"),
p75("p75"),
p95("p95"),
p98("p98"),
p99("p99"),
p999("p999");
final String displayName;
public String getDisplayName() {
return displayName;
}
Dimension(String defaultValue) {
this.displayName = defaultValue;
}
public static EnumSet<Dimension> fromProperties(Properties p, String prefix) {
EnumSet<Dimension> df = EnumSet.allOf(Dimension.class);
for (Dimension k : Dimension.values()) {
String key = prefix + k.toString();
if (p.containsKey(key)) {
Boolean value = Boolean.parseBoolean(p.getProperty(key));
if (!value) {
df.remove(k);
}
}
}
return df;
}
public static EnumSet<Dimension> fromConfigs(Map<String, ?> configs, String prefix) {
EnumSet<Dimension> df = EnumSet.allOf(Dimension.class);
for (Dimension k : Dimension.values()) {
String key = prefix + k.toString();
if (configs.containsKey(key)) {
Boolean value = (Boolean) configs.get(key);
if (!value) {
df.remove(k);
}
}
}
return df;
}
}
| 9,802 |
0 | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/KafkaStatsDReporter.java | package com.airbnb.metrics;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.timgroup.statsd.StatsDClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KafkaStatsDReporter implements Runnable {
private static final Logger log = LoggerFactory.getLogger(KafkaStatsDReporter.class);
private final ScheduledExecutorService executor;
private final StatsDClient statsDClient;
private final StatsDMetricsRegistry registry;
public KafkaStatsDReporter(
StatsDClient statsDClient,
StatsDMetricsRegistry registry
) {
this.statsDClient = statsDClient;
this.registry = registry;
this.executor = new ScheduledThreadPoolExecutor(1);
}
public void start(
long period,
TimeUnit unit
) {
executor.scheduleWithFixedDelay(this, period, period, unit);
}
public void shutdown() throws InterruptedException {
executor.shutdown();
}
private void sendAllKafkaMetrics() {
registry.getAllMetricInfo().forEach(this::sendAMetric);
}
private void sendAMetric(MetricInfo metricInfo) {
String metricName = metricInfo.getName();
String tags = metricInfo.getTags();
final Object value = metricInfo.getMetric().value();
Double val = new Double(value.toString());
if (val == Double.NEGATIVE_INFINITY || val == Double.POSITIVE_INFINITY) {
val = 0D;
}
if (tags != null) {
statsDClient.gauge(metricName, val, tags);
} else {
statsDClient.gauge(metricName, val);
}
}
@Override
public void run() {
sendAllKafkaMetrics();
}
}
| 9,803 |
0 | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/metrics/MetricInfo.java | package com.airbnb.metrics;
import org.apache.kafka.common.Metric;
public class MetricInfo {
private final Metric metric;
private final String name;
private final String tags;
public MetricInfo(Metric metric, String name, String tags) {
this.metric = metric;
this.name = name;
this.tags = tags;
}
public Metric getMetric() {
return metric;
}
public String getName() {
return name;
}
public String getTags() {
return tags;
}
}
| 9,804 |
0 | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka/kafka09/StatsdMetricsReporter.java | /*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.airbnb.kafka.kafka09;
import com.airbnb.metrics.Dimension;
import com.airbnb.metrics.KafkaStatsDReporter;
import com.airbnb.metrics.MetricInfo;
import com.airbnb.metrics.StatsDMetricsRegistry;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;
import com.timgroup.statsd.StatsDClientException;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.metrics.KafkaMetric;
import org.apache.kafka.common.metrics.MetricsReporter;
import org.slf4j.LoggerFactory;
public class StatsdMetricsReporter implements MetricsReporter {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(StatsdMetricsReporter.class);
public static final String REPORTER_NAME = "kafka-statsd-metrics-0.5";
public static final String STATSD_REPORTER_ENABLED = "external.kafka.statsd.reporter.enabled";
public static final String STATSD_HOST = "external.kafka.statsd.host";
public static final String STATSD_PORT = "external.kafka.statsd.port";
public static final String STATSD_METRICS_PREFIX = "external.kafka.statsd.metrics.prefix";
public static final String POLLING_INTERVAL_SECS = "kafka.metrics.polling.interval.secs";
public static final String STATSD_DIMENSION_ENABLED = "external.kafka.statsd.dimension.enabled";
private static final String METRIC_PREFIX = "kafka.";
private static final int POLLING_PERIOD_IN_SECONDS = 10;
private boolean enabled;
private final AtomicBoolean running = new AtomicBoolean(false);
private String host;
private int port;
private String prefix;
private long pollingPeriodInSeconds;
private EnumSet<Dimension> metricDimensions;
private StatsDClient statsd;
private Map<String, KafkaMetric> kafkaMetrics;
StatsDMetricsRegistry registry;
KafkaStatsDReporter underlying = null;
public boolean isRunning() {
return running.get();
}
@Override
public void init(List<KafkaMetric> metrics) {
registry = new StatsDMetricsRegistry();
kafkaMetrics = new HashMap<String, KafkaMetric>();
if (enabled) {
startReporter(POLLING_PERIOD_IN_SECONDS);
} else {
log.warn("KafkaStatsDReporter is disabled");
}
for (KafkaMetric metric : metrics) {
metricChange(metric);
}
}
private String getMetricName(final KafkaMetric metric) {
MetricName metricName = metric.metricName();
return METRIC_PREFIX + metricName.group() + "." + metricName.name();
}
@Override
public void metricChange(final KafkaMetric metric) {
String name = getMetricName(metric);
StringBuilder strBuilder = new StringBuilder();
for (String key : metric.metricName().tags().keySet()) {
strBuilder.append(key).append(":").append(metric.metricName().tags().get(key)).append(",");
}
if (strBuilder.length() > 0) {
strBuilder.deleteCharAt(strBuilder.length() - 1);
}
registry.register(metric.metricName(), new MetricInfo(metric, name, strBuilder.toString()));
log.debug("metrics name: {}", name);
}
@Override
public void metricRemoval(KafkaMetric metric) {
registry.unregister(metric.metricName());
}
@Override
public void close() {
stopReporter();
}
@Override
public void configure(Map<String, ?> configs) {
enabled = configs.containsKey(STATSD_REPORTER_ENABLED) ?
Boolean.valueOf((String) configs.get(STATSD_REPORTER_ENABLED)) : false;
host = configs.containsKey(STATSD_HOST) ?
(String) configs.get(STATSD_HOST) : "localhost";
port = configs.containsKey(STATSD_PORT) ?
Integer.valueOf((String) configs.get(STATSD_PORT)) : 8125;
prefix = configs.containsKey(STATSD_METRICS_PREFIX) ?
(String) configs.get(STATSD_METRICS_PREFIX) : "";
pollingPeriodInSeconds = configs.containsKey(POLLING_INTERVAL_SECS) ?
Integer.valueOf((String) configs.get(POLLING_INTERVAL_SECS)) : 10;
metricDimensions = Dimension.fromConfigs(configs, STATSD_DIMENSION_ENABLED);
}
public void startReporter(long pollingPeriodInSeconds) {
if (pollingPeriodInSeconds <= 0) {
throw new IllegalArgumentException("Polling period must be greater than zero");
}
synchronized (running) {
if (running.get()) {
log.warn("KafkaStatsDReporter: {} is already running", REPORTER_NAME);
} else {
statsd = createStatsd();
underlying = new KafkaStatsDReporter(statsd, registry);
underlying.start(pollingPeriodInSeconds, TimeUnit.SECONDS);
log.info(
"Started KafkaStatsDReporter: {} with host={}, port={}, polling_period_secs={}, prefix={}",
REPORTER_NAME, host, port, pollingPeriodInSeconds, prefix
);
running.set(true);
}
}
}
StatsDClient createStatsd() {
try {
return new NonBlockingStatsDClient(prefix, host, port);
} catch (StatsDClientException ex) {
log.error("KafkaStatsDReporter cannot be started");
throw ex;
}
}
private void stopReporter() {
if (!enabled) {
log.warn("KafkaStatsDReporter is disabled");
} else {
synchronized (running) {
if (running.get()) {
try {
underlying.shutdown();
} catch (InterruptedException e) {
log.warn("Stop reporter exception: {}", e);
}
statsd.stop();
running.set(false);
log.info("Stopped KafkaStatsDReporter with host={}, port={}", host, port);
} else {
log.warn("KafkaStatsDReporter is not running");
}
}
}
}
}
| 9,805 |
0 | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka/kafka08/StatsdMetricsReporter.java | /*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.airbnb.kafka.kafka08;
import com.airbnb.metrics.Dimension;
import com.airbnb.metrics.ExcludeMetricPredicate;
import com.airbnb.metrics.StatsDReporter;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;
import com.timgroup.statsd.StatsDClientException;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.MetricPredicate;
import com.yammer.metrics.reporting.AbstractPollingReporter;
import kafka.metrics.KafkaMetricsReporter;
import kafka.utils.VerifiableProperties;
import org.slf4j.LoggerFactory;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
*
*/
public class StatsdMetricsReporter implements StatsdMetricsReporterMBean, KafkaMetricsReporter {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(StatsDReporter.class);
public static final String DEFAULT_EXCLUDE_REGEX = "(kafka\\.server\\.FetcherStats.*ConsumerFetcherThread.*)|(kafka\\.consumer\\.FetchRequestAndResponseMetrics.*)|(.*ReplicaFetcherThread.*)|(kafka\\.server\\.FetcherLagMetrics\\..*)|(kafka\\.log\\.Log\\..*)|(kafka\\.cluster\\.Partition\\..*)";
private boolean enabled;
private final AtomicBoolean running = new AtomicBoolean(false);
private String host;
private int port;
private String prefix;
private long pollingPeriodInSeconds;
private EnumSet<Dimension> metricDimensions;
private MetricPredicate metricPredicate;
private StatsDClient statsd;
private boolean isTagEnabled;
private AbstractPollingReporter underlying = null;
@Override
public String getMBeanName() {
return "kafka:type=" + getClass().getName();
}
public boolean isRunning() {
return running.get();
}
//try to make it compatible with kafka-statsd-metrics2
@Override
public synchronized void init(VerifiableProperties props) {
loadConfig(props);
if (enabled) {
log.info("Reporter is enabled and starting...");
startReporter(pollingPeriodInSeconds);
} else {
log.warn("Reporter is disabled");
}
}
private void loadConfig(VerifiableProperties props) {
enabled = props.getBoolean("external.kafka.statsd.reporter.enabled", false);
host = props.getString("external.kafka.statsd.host", "localhost");
port = props.getInt("external.kafka.statsd.port", 8125);
prefix = props.getString("external.kafka.statsd.metrics.prefix", "");
pollingPeriodInSeconds = props.getInt("kafka.metrics.polling.interval.secs", 10);
metricDimensions = Dimension.fromProperties(props.props(), "external.kafka.statsd.dimension.enabled.");
String excludeRegex = props.getString("external.kafka.statsd.metrics.exclude_regex", DEFAULT_EXCLUDE_REGEX);
if (excludeRegex != null && excludeRegex.length() != 0) {
metricPredicate = new ExcludeMetricPredicate(excludeRegex);
} else {
metricPredicate = MetricPredicate.ALL;
}
this.isTagEnabled = props.getBoolean("external.kafka.statsd.tag.enabled", true);
}
@Override
public void startReporter(long pollingPeriodInSeconds) {
if (pollingPeriodInSeconds <= 0) {
throw new IllegalArgumentException("Polling period must be greater than zero");
}
synchronized (running) {
if (running.get()) {
log.warn("Reporter is already running");
} else {
statsd = createStatsd();
underlying = new StatsDReporter(
Metrics.defaultRegistry(),
statsd,
metricPredicate,
metricDimensions,
isTagEnabled);
underlying.start(pollingPeriodInSeconds, TimeUnit.SECONDS);
log.info("Started Reporter with host={}, port={}, polling_period_secs={}, prefix={}",
host, port, pollingPeriodInSeconds, prefix);
running.set(true);
}
}
}
private StatsDClient createStatsd() {
try {
return new NonBlockingStatsDClient(
prefix, /* prefix to any stats; may be null or empty string */
host, /* common case: localhost */
port /* port */
);
} catch (StatsDClientException ex) {
log.error("Reporter cannot be started");
throw ex;
}
}
@Override
public void stopReporter() {
if (!enabled) {
log.warn("Reporter is disabled");
} else {
synchronized (running) {
if (running.get()) {
underlying.shutdown();
statsd.stop();
running.set(false);
log.info("Stopped Reporter with host={}, port={}", host, port);
} else {
log.warn("Reporter is not running");
}
}
}
}
}
| 9,806 |
0 | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka | Create_ds/kafka-statsd-metrics2/src/main/java/com/airbnb/kafka/kafka08/StatsdMetricsReporterMBean.java | /*
* Copyright (c) 2015. Airbnb.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.airbnb.kafka.kafka08;
import kafka.metrics.KafkaMetricsReporterMBean;
/**
* @see kafka.metrics.KafkaMetricsReporterMBean: the custom reporter needs to
* additionally implement an MBean trait that extends kafka.metrics.KafkaMetricsReporterMBean
* so that the registered MBean is compliant with the standard MBean convention.
*/
public interface StatsdMetricsReporterMBean extends KafkaMetricsReporterMBean {
}
| 9,807 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslKeyExchangeException.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* Thrown when a key exchange exception occurs within the Message Security
* Layer.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslKeyExchangeException extends MslException {
private static final long serialVersionUID = -1272784987270064773L;
/**
* Construct a new MSL key exchange exception with the specified error.
*
* @param error the error.
*/
public MslKeyExchangeException(final MslError error) {
super(error);
}
/**
* Construct a new MSL key exchange exception with the specified error and
* details.
*
* @param error the error.
* @param details the details text.
*/
public MslKeyExchangeException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL key exchange exception with the specified error,
* details, and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslKeyExchangeException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/**
* Construct a new MSL key exchange exception with the specified error and
* cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslKeyExchangeException(final MslError error, final Throwable cause) {
super(error, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslKeyExchangeException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslKeyExchangeException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public MslKeyExchangeException setUserIdToken(final UserIdToken userIdToken) {
super.setUserIdToken(userIdToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserAuthenticationData(com.netflix.msl.userauth.UserAuthenticationData)
*/
@Override
public MslKeyExchangeException setUserAuthenticationData(final UserAuthenticationData userAuthData) {
super.setUserAuthenticationData(userAuthData);
return this;
}
}
| 9,808 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslException.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* Thrown when an exception occurs within the Message Security Layer.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslException extends Exception {
private static final long serialVersionUID = -2444322310603180494L;
/**
* Construct a new MSL exception with the specified error.
*
* @param error the error.
*/
public MslException(final MslError error) {
super(error.getMessage());
this.error = error;
}
/**
* Construct a new MSL exception with the specified error and details.
*
* @param error the error.
* @param details the details text.
*/
public MslException(final MslError error, final String details) {
super(error.getMessage() + " [" + details + "]");
this.error = error;
}
/**
* Construct a new MSL exception with the specified error, details, and
* cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslException(final MslError error, final String details, final Throwable cause) {
super(error.getMessage() + " [" + details + "]", cause);
this.error = error;
}
/**
* Construct a new MSL exception with the specified error and cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslException(final MslError error, final Throwable cause) {
super(error.getMessage(), cause);
this.error = error;
}
/**
* Set the entity associated with the exception, using a master token. This
* does nothing if the entity is already set.
*
* @param masterToken entity associated with the error. May be null.
* @return this.
*/
public MslException setMasterToken(final MasterToken masterToken) {
if (getMasterToken() == null && getEntityAuthenticationData() == null)
this.masterToken = masterToken;
return this;
}
/**
* Set the entity associated with the exception, using entity
* authentication data. This does nothing if the entity is already set.
*
* @param entityAuthData entity associated with the error. May be null.
* @return this.
*/
public MslException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
if (getMasterToken() == null && getEntityAuthenticationData() == null)
this.entityAuthData = entityAuthData;
return this;
}
/**
* Set the user associated with the exception, using a user ID token. This
* does nothing if the user is already set.
*
* @param userIdToken user associated with the error. May be null.
* @return this.
*/
public MslException setUserIdToken(final UserIdToken userIdToken) {
if (getUserIdToken() == null && getUserAuthenticationData() == null)
this.userIdToken = userIdToken;
return this;
}
/**
* Set the user associated with the exception, using user authentication
* data. This does nothing if the user is already set.
*
* @param userAuthData user associated with the error. May be null.
* @return this.
*/
public MslException setUserAuthenticationData(final UserAuthenticationData userAuthData) {
if (getUserIdToken() == null && getUserAuthenticationData() == null)
this.userAuthData = userAuthData;
return this;
}
/**
* Set the message ID of the message associated with the exception. This
* does nothing if the message ID is already set.
*
* @param messageId message ID of the message associated with this error.
* @return this.
*/
public MslException setMessageId(final long messageId) {
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new IllegalArgumentException("Message ID " + messageId + " is outside the valid range.");
if (getMessageId() == null)
this.messageId = Long.valueOf(messageId);
return this;
}
/**
* @return the error.
*/
public MslError getError() {
return error;
}
/**
* Returns the master token of the entity associated with the exception.
* May be null if the entity is identified by entity authentication data or
* not applicable to the exception.
*
* @return the master token or null.
* @see #getEntityAuthenticationData()
*/
public MasterToken getMasterToken() {
if (masterToken != null)
return masterToken;
// We have to search through the stack in case there is a nested master
// token.
final Throwable cause = getCause();
if (cause != null && cause instanceof MslException) {
final MslException mslCause = (MslException)cause;
return mslCause.getMasterToken();
}
// No master token.
return null;
}
/**
* Returns the entity authentication data of the entity associated with the
* exception. May be null if the entity is identified by a master token or
* not applicable to the exception.
*
* @return the entity authentication data or null.
* @see #getMasterToken()
*/
public EntityAuthenticationData getEntityAuthenticationData() {
if (entityAuthData != null)
return entityAuthData;
// We have to search through the stack in case there is a nested entity
// authentication data.
final Throwable cause = getCause();
if (cause != null && cause instanceof MslException) {
final MslException mslCause = (MslException)cause;
return mslCause.getEntityAuthenticationData();
}
// No entity authentication data.
return null;
}
/**
* Returns the user ID token of the user associated with the exception. May
* be null if the user is identified by user authentication data or not
* applicable to the exception.
*
* @return the user ID token or null.
* @see #getUserAuthenticationData()
*/
public UserIdToken getUserIdToken() {
if (userIdToken != null)
return userIdToken;
// We have to search through the stack in case there is a nested user
// ID token.
final Throwable cause = getCause();
if (cause != null && cause instanceof MslException) {
final MslException mslCause = (MslException)cause;
return mslCause.getUserIdToken();
}
// No user ID token.
return null;
}
/**
* Returns the user authentication data of the user associated with the
* exception. May be null if the user is identified by a user ID token or
* not applicable to the exception.
*
* @return the user authentication data or null.
* @see #getUserIdToken()
*/
public UserAuthenticationData getUserAuthenticationData() {
if (userAuthData != null)
return userAuthData;
// We have to search through the stack in case there is a nested user
// authentication data.
final Throwable cause = getCause();
if (cause != null && cause instanceof MslException) {
final MslException mslCause = (MslException)cause;
return mslCause.getUserAuthenticationData();
}
// No user authentication data.
return null;
}
/**
* Returns the message ID of the message associated with the exception. May
* be null if there is no message associated or the exception was thrown
* before extracting the message ID.
*
* @return the message ID or null.
*/
public Long getMessageId() {
if (messageId != null)
return messageId;
// We have to search through the stack in case there is a nested
// message ID.
final Throwable cause = getCause();
if (cause != null && cause instanceof MslException) {
final MslException mslCause = (MslException)cause;
return mslCause.getMessageId();
}
// No message ID.
return null;
}
/** MSL error. */
private final MslError error;
/** Master token. */
private MasterToken masterToken = null;
/** Entity authentication data. */
private EntityAuthenticationData entityAuthData = null;
/** User ID token. */
private UserIdToken userIdToken = null;
/** User authentication data. */
private UserAuthenticationData userAuthData = null;
/** Message ID. */
private Long messageId = null;
}
| 9,809 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslMessageException.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
/**
* Thrown when a message exception occurs within the Message Security Layer.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslMessageException extends MslException {
private static final long serialVersionUID = 8022562525891870639L;
/**
* Construct a new MSL message exception with the specified error.
*
* @param error the error.
*/
public MslMessageException(final MslError error) {
super(error);
}
/**
* Construct a new MSL message exception with the specified error and
* details.
*
* @param error the error.
* @param details the details text.
*/
public MslMessageException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL message exception with the specified error, details,
* and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslMessageException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslMessageException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslMessageException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public MslMessageException setUserIdToken(final UserIdToken userIdToken) {
super.setUserIdToken(userIdToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMessageId(long)
*/
@Override
public MslMessageException setMessageId(final long messageId) {
super.setMessageId(messageId);
return this;
}
}
| 9,810 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslEncodingException.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* Thrown when an encoding exception occurs within the Message Security Layer.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslEncodingException extends MslException {
private static final long serialVersionUID = -2295976834635986944L;
/**
* Construct a new MSL encoding exception with the specified error.
*
* @param error the error.
*/
public MslEncodingException(final MslError error) {
super(error);
}
/**
* Construct a new MSL encoding exception with the specified error and
* details.
*
* @param error the error.
* @param details the details text.
*/
public MslEncodingException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL encoding exception with the specified error,
* details, and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslEncodingException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/**
* Construct a new MSL encoding exception with the specified error and
* cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslEncodingException(final MslError error, final Throwable cause) {
super(error, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslEncodingException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslEncodingException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public MslEncodingException setUserIdToken(final UserIdToken userIdToken) {
super.setUserIdToken(userIdToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserAuthenticationData(com.netflix.msl.userauth.UserAuthenticationData)
*/
@Override
public MslEncodingException setUserAuthenticationData(final UserAuthenticationData userAuthData) {
super.setUserAuthenticationData(userAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMessageId(long)
*/
@Override
public MslEncodingException setMessageId(final long messageId) {
super.setMessageId(messageId);
return this;
}
}
| 9,811 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslCryptoException.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
/**
* Thrown when a crypto exception occurs within the Message Security Layer.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslCryptoException extends MslException {
private static final long serialVersionUID = -7618578454440397528L;
/**
* Construct a new MSL crypto exception with the specified error.
*
* @param error the error.
*/
public MslCryptoException(final MslError error) {
super(error);
}
/**
* Construct a new MSL crypto exception with the specified error and
* details.
*
* @param error the error.
* @param details the details text.
*/
public MslCryptoException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL crypto exception with the specified error, details,
* and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslCryptoException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/**
* Construct a new MSL crypto exception with the specified error and cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslCryptoException(final MslError error, final Throwable cause) {
super(error, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslCryptoException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslCryptoException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
}
| 9,812 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslEntityAuthException.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
/**
* Thrown when an entity authentication exception occurs within the Message
* Security Layer.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslEntityAuthException extends MslException {
private static final long serialVersionUID = 5335550727677217303L;
/**
* Construct a new MSL entity authentication exception with the specified
* error.
*
* @param error the error.
*/
public MslEntityAuthException(final MslError error) {
super(error);
}
/**
* Construct a new MSL entity authentication exception with the specified
* error and details.
*
* @param error the error.
* @param details the details text.
*/
public MslEntityAuthException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL entity authentication exception with the specified
* error, details, and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslEntityAuthException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/**
* Construct a new MSL entity authentication exception with the specified
* error and cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslEntityAuthException(final MslError error, final Throwable cause) {
super(error, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslEntityAuthException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslEntityAuthException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
}
| 9,813 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslUserAuthException.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* Thrown when a user authentication exception occurs within the Message
* Security Layer.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslUserAuthException extends MslException {
private static final long serialVersionUID = 3836512629362408424L;
/**
* Construct a new MSL user authentication exception with the specified
* error.
*
* @param error the error.
*/
public MslUserAuthException(final MslError error) {
super(error);
}
/**
* Construct a new MSL user authentication exception with the specified
* error and details.
*
* @param error the error.
* @param details the details text.
*/
public MslUserAuthException(final MslError error, final String details) {
super(error, details);
}
/**
* Construct a new MSL user authentication exception with the specified
* error, details, and cause.
*
* @param error the error.
* @param details the details text.
* @param cause the cause.
*/
public MslUserAuthException(final MslError error, final String details, final Throwable cause) {
super(error, details, cause);
}
/**
* Construct a new MSL user authentication exception with the specified
* error and cause.
*
* @param error the error.
* @param cause the cause.
*/
public MslUserAuthException(final MslError error, final Throwable cause) {
super(error, cause);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslUserAuthException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserAuthenticationData(com.netflix.msl.userauth.UserAuthenticationData)
*/
@Override
public MslUserAuthException setUserAuthenticationData(final UserAuthenticationData userAuthData) {
super.setUserAuthenticationData(userAuthData);
return this;
}
}
| 9,814 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslUserIdTokenException.java | /**
* Copyright (c) 2013-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
/**
* Thrown when there is a problem with a user ID token, but the token was
* successfully parsed.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslUserIdTokenException extends MslException {
private static final long serialVersionUID = 8796880393236563071L;
/**
* Construct a new MSL user ID token exception with the specified error and
* user ID token.
*
* @param error the error.
* @param userIdToken the user ID token. May not be null.
*/
public MslUserIdTokenException(final MslError error, final UserIdToken userIdToken) {
super(error);
setUserIdToken(userIdToken);
}
/**
* Construct a new MSL user ID token exception with the specified error,
* user ID token, and details.
*
* @param error the error.
* @param userIdToken the user ID token. May not be null.
* @param details the details text.
*/
public MslUserIdTokenException(final MslError error, final UserIdToken userIdToken, final String details) {
super(error, details);
setUserIdToken(userIdToken);
}
/**
* Construct a new MSL user ID token exception with the specified error,
* user ID token, details, and cause.
*
* @param error the error.
* @param userIdToken the user ID token. May not be null.
* @param details the details text.
* @param cause the cause.
*/
public MslUserIdTokenException(final MslError error, final UserIdToken userIdToken, final String details, final Throwable cause) {
super(error, details, cause);
setUserIdToken(userIdToken);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMasterToken(com.netflix.msl.tokens.MasterToken)
*/
@Override
public MslUserIdTokenException setMasterToken(final MasterToken masterToken) {
super.setMasterToken(masterToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setEntityAuthenticationData(com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public MslUserIdTokenException setEntityAuthenticationData(final EntityAuthenticationData entityAuthData) {
super.setEntityAuthenticationData(entityAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMessageId(long)
*/
@Override
public MslUserIdTokenException setMessageId(final long messageId) {
super.setMessageId(messageId);
return this;
}
}
| 9,815 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslInternalException.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
/**
* Thrown when an exception occurs that should not happen except due to an
* internal error (e.g. incorrectly written code).
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslInternalException extends RuntimeException {
private static final long serialVersionUID = 5787827728910061805L;
/**
* Construct a new MSL internal exception with the specified detail
* message and cause.
*
* @param message the detail message.
* @param cause the cause.
*/
public MslInternalException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Construct a new MSL internal exception with the specified detail
* message.
*
* @param message the detail message.
*/
public MslInternalException(final String message) {
super(message);
}
}
| 9,816 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslError.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import java.util.HashSet;
import java.util.Set;
import com.netflix.msl.MslConstants.ResponseCode;
/**
* <p>Message Security Layer error codes and descriptions.</p>
*
* <p>Errors are defined with an internal and a response error code. The
* internal error code is specific to this implementation. The response error
* codes are sent in error messages to inform the remote entity, who should use
* it to decide on the correct error handling behavior.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslError {
/** Internal error code set. */
private static final Set<Integer> internalCodes = new HashSet<Integer>();
// 0 Message Security Layer
public static final MslError MSL_PARSE_ERROR = new MslError(0, ResponseCode.FAIL, "Error parsing MSL encodable.");
public static final MslError MSL_ENCODE_ERROR = new MslError(1, ResponseCode.FAIL, "Error encoding MSL encodable.");
public static final MslError ENVELOPE_HASH_MISMATCH = new MslError(2, ResponseCode.FAIL, "Computed hash does not match envelope hash.");
public static final MslError INVALID_PUBLIC_KEY = new MslError(3, ResponseCode.FAIL, "Invalid public key provided.");
public static final MslError INVALID_PRIVATE_KEY = new MslError(4, ResponseCode.FAIL, "Invalid private key provided.");
public static final MslError PLAINTEXT_ILLEGAL_BLOCK_SIZE = new MslError(5, ResponseCode.FAIL, "Plaintext is not a multiple of the block size.");
public static final MslError PLAINTEXT_BAD_PADDING = new MslError(6, ResponseCode.FAIL, "Plaintext contains incorrect padding.");
public static final MslError CIPHERTEXT_ILLEGAL_BLOCK_SIZE = new MslError(7, ResponseCode.FAIL, "Ciphertext is not a multiple of the block size.");
public static final MslError CIPHERTEXT_BAD_PADDING = new MslError(8, ResponseCode.FAIL, "Ciphertext contains incorrect padding.");
public static final MslError ENCRYPT_NOT_SUPPORTED = new MslError(9, ResponseCode.FAIL, "Encryption not supported.");
public static final MslError DECRYPT_NOT_SUPPORTED = new MslError(10, ResponseCode.FAIL, "Decryption not supported.");
public static final MslError ENVELOPE_KEY_ID_MISMATCH = new MslError(11, ResponseCode.FAIL, "Encryption envelope key ID does not match crypto context key ID.");
public static final MslError CIPHERTEXT_ENVELOPE_PARSE_ERROR = new MslError(12, ResponseCode.FAIL, "Error parsing ciphertext envelope.");
public static final MslError CIPHERTEXT_ENVELOPE_ENCODE_ERROR = new MslError(13, ResponseCode.FAIL, "Error encoding ciphertext envelope.");
public static final MslError SIGN_NOT_SUPPORTED = new MslError(14, ResponseCode.FAIL, "Sign not supported.");
public static final MslError VERIFY_NOT_SUPPORTED = new MslError(15, ResponseCode.FAIL, "Verify not suppoprted.");
public static final MslError SIGNATURE_ERROR = new MslError(16, ResponseCode.FAIL, "Signature not initialized or unable to process data/signature.");
public static final MslError HMAC_ERROR = new MslError(17, ResponseCode.FAIL, "Error computing HMAC.");
public static final MslError ENCRYPT_ERROR = new MslError(18, ResponseCode.FAIL, "Error encrypting plaintext.");
public static final MslError DECRYPT_ERROR = new MslError(19, ResponseCode.FAIL, "Error decrypting ciphertext.");
public static final MslError INSUFFICIENT_CIPHERTEXT = new MslError(20, ResponseCode.FAIL, "Insufficient ciphertext for decryption.");
public static final MslError SESSION_KEY_CREATION_FAILURE = new MslError(21, ResponseCode.FAIL, "Error when creating session keys.");
public static final MslError INVALID_SYMMETRIC_KEY = new MslError(24, ResponseCode.FAIL, "Invalid symmetric key.");
public static final MslError INVALID_ENCRYPTION_KEY = new MslError(25, ResponseCode.FAIL, "Invalid encryption key.");
public static final MslError INVALID_HMAC_KEY = new MslError(26, ResponseCode.FAIL, "Invalid HMAC key.");
public static final MslError WRAP_NOT_SUPPORTED = new MslError(27, ResponseCode.FAIL, "Wrap not supported.");
public static final MslError UNWRAP_NOT_SUPPORTED = new MslError(28, ResponseCode.FAIL, "Unwrap not supported.");
public static final MslError UNIDENTIFIED_JWK_TYPE = new MslError(29, ResponseCode.FAIL, "Unidentified JSON web key type.");
public static final MslError UNIDENTIFIED_JWK_USAGE = new MslError(30, ResponseCode.FAIL, "Unidentified JSON web key usage.");
public static final MslError UNIDENTIFIED_JWK_ALGORITHM = new MslError(31, ResponseCode.FAIL, "Unidentified JSON web key algorithm.");
public static final MslError WRAP_ERROR = new MslError(32, ResponseCode.FAIL, "Error wrapping plaintext.");
public static final MslError UNWRAP_ERROR = new MslError(33, ResponseCode.FAIL, "Error unwrapping ciphertext.");
public static final MslError INVALID_JWK = new MslError(34, ResponseCode.FAIL, "Invalid JSON web key.");
public static final MslError INVALID_JWK_KEYDATA = new MslError(35, ResponseCode.FAIL, "Invalid JSON web key keydata.");
public static final MslError UNSUPPORTED_JWK_ALGORITHM = new MslError(36, ResponseCode.FAIL, "Unsupported JSON web key algorithm.");
public static final MslError WRAP_KEY_CREATION_FAILURE = new MslError(37, ResponseCode.FAIL, "Error when creating wrapping key.");
public static final MslError INVALID_WRAP_CIPHERTEXT = new MslError(38, ResponseCode.FAIL, "Invalid wrap ciphertext.");
public static final MslError UNSUPPORTED_JWE_ALGORITHM = new MslError(39, ResponseCode.FAIL, "Unsupported JSON web encryption algorithm.");
public static final MslError JWE_ENCODE_ERROR = new MslError(40, ResponseCode.FAIL, "Error encoding JSON web encryption header.");
public static final MslError JWE_PARSE_ERROR = new MslError(41, ResponseCode.FAIL, "Error parsing JSON web encryption header.");
public static final MslError INVALID_ALGORITHM_PARAMS = new MslError(42, ResponseCode.FAIL, "Invalid algorithm parameters.");
public static final MslError JWE_ALGORITHM_MISMATCH = new MslError(43, ResponseCode.FAIL, "JSON web encryption header algorithms mismatch.");
public static final MslError KEY_IMPORT_ERROR = new MslError(44, ResponseCode.FAIL, "Error importing key.");
public static final MslError KEY_EXPORT_ERROR = new MslError(45, ResponseCode.FAIL, "Error exporting key.");
public static final MslError DIGEST_ERROR = new MslError(46, ResponseCode.FAIL, "Error in digest.");
public static final MslError UNSUPPORTED_KEY = new MslError(47, ResponseCode.FAIL, "Unsupported key type or algorithm.");
public static final MslError UNSUPPORTED_JWE_SERIALIZATION = new MslError(48, ResponseCode.FAIL, "Unsupported JSON web encryption serialization.");
public static final MslError INVALID_WRAPPING_KEY = new MslError(51, ResponseCode.FAIL, "Invalid wrapping key.");
public static final MslError UNIDENTIFIED_CIPHERTEXT_ENVELOPE = new MslError(52, ResponseCode.FAIL, "Unidentified ciphertext envelope version.");
public static final MslError UNIDENTIFIED_SIGNATURE_ENVELOPE = new MslError(53, ResponseCode.FAIL, "Unidentified signature envelope version.");
public static final MslError UNSUPPORTED_CIPHERTEXT_ENVELOPE = new MslError(54, ResponseCode.FAIL, "Unsupported ciphertext envelope version.");
public static final MslError UNSUPPORTED_SIGNATURE_ENVELOPE = new MslError(55, ResponseCode.FAIL, "Unsupported signature envelope version.");
public static final MslError UNIDENTIFIED_CIPHERSPEC = new MslError(56, ResponseCode.FAIL, "Unidentified cipher specification.");
public static final MslError UNIDENTIFIED_ALGORITHM = new MslError(57, ResponseCode.FAIL, "Unidentified algorithm.");
public static final MslError SIGNATURE_ENVELOPE_PARSE_ERROR = new MslError(58, ResponseCode.FAIL, "Error parsing signature envelope.");
public static final MslError SIGNATURE_ENVELOPE_ENCODE_ERROR = new MslError(59, ResponseCode.FAIL, "Error encoding signature envelope.");
public static final MslError INVALID_SIGNATURE = new MslError(60, ResponseCode.FAIL, "Invalid signature.");
public static final MslError DERIVEKEY_ERROR = new MslError(61, ResponseCode.FAIL, "Error deriving key.");
public static final MslError UNIDENTIFIED_JWK_KEYOP = new MslError(62, ResponseCode.FAIL, "Unidentified JSON web key key operation.");
public static final MslError GENERATEKEY_ERROR = new MslError(63, ResponseCode.FAIL, "Error generating key.");
public static final MslError INVALID_IV = new MslError(64, ResponseCode.FAIL, "Invalid initialization vector.");
public static final MslError INVALID_CIPHERTEXT = new MslError(65, ResponseCode.FAIL, "Invalid ciphertext.");
// 1 Master Token
public static final MslError MASTERTOKEN_UNTRUSTED = new MslError(1000, ResponseCode.ENTITY_REAUTH, "Master token is not trusted.");
public static final MslError MASTERTOKEN_KEY_CREATION_ERROR = new MslError(1001, ResponseCode.ENTITY_REAUTH, "Unable to construct symmetric keys from master token.");
public static final MslError MASTERTOKEN_EXPIRES_BEFORE_RENEWAL = new MslError(1002, ResponseCode.ENTITY_REAUTH, "Master token expiration timestamp is before the renewal window opens.");
public static final MslError MASTERTOKEN_SESSIONDATA_MISSING = new MslError(1003, ResponseCode.ENTITY_REAUTH, "No master token session data found.");
public static final MslError MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_RANGE = new MslError(1004, ResponseCode.ENTITY_REAUTH, "Master token sequence number is out of range.");
public static final MslError MASTERTOKEN_SERIAL_NUMBER_OUT_OF_RANGE = new MslError(1005, ResponseCode.ENTITY_REAUTH, "Master token serial number is out of range.");
public static final MslError MASTERTOKEN_TOKENDATA_INVALID = new MslError(1006, ResponseCode.ENTITY_REAUTH, "Invalid master token data.");
public static final MslError MASTERTOKEN_SIGNATURE_INVALID = new MslError(1007, ResponseCode.ENTITY_REAUTH, "Invalid master token signature.");
public static final MslError MASTERTOKEN_SESSIONDATA_INVALID = new MslError(1008, ResponseCode.ENTITY_REAUTH, "Invalid master token session data.");
public static final MslError MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC = new MslError(1009, ResponseCode.ENTITY_REAUTH, "Master token sequence number does not have the expected value.");
public static final MslError MASTERTOKEN_TOKENDATA_MISSING = new MslError(1010, ResponseCode.ENTITY_REAUTH, "No master token data found.");
public static final MslError MASTERTOKEN_TOKENDATA_PARSE_ERROR = new MslError(1011, ResponseCode.ENTITY_REAUTH, "Error parsing master token data.");
public static final MslError MASTERTOKEN_SESSIONDATA_PARSE_ERROR = new MslError(1012, ResponseCode.ENTITY_REAUTH, "Error parsing master token session data.");
public static final MslError MASTERTOKEN_IDENTITY_REVOKED = new MslError(1013, ResponseCode.ENTITY_REAUTH, "Master token entity identity is revoked.");
public static final MslError MASTERTOKEN_REJECTED_BY_APP = new MslError(1014, ResponseCode.ENTITY_REAUTH, "Master token is rejected by the application.");
public static final MslError MASTERTOKEN_ISSUERDATA_ENCODE_ERROR = new MslError(1015, ResponseCode.FAIL, "Master token issuer data encoding error.");
// 2 User ID Token
public static final MslError USERIDTOKEN_MASTERTOKEN_MISMATCH = new MslError(2000, ResponseCode.USER_REAUTH, "User ID token master token serial number does not match master token serial number.");
public static final MslError USERIDTOKEN_NOT_DECRYPTED = new MslError(2001, ResponseCode.USER_REAUTH, "User ID token is not decrypted or verified.");
public static final MslError USERIDTOKEN_MASTERTOKEN_NULL = new MslError(2002, ResponseCode.USER_REAUTH, "User ID token requires a master token.");
public static final MslError USERIDTOKEN_EXPIRES_BEFORE_RENEWAL = new MslError(2003, ResponseCode.USER_REAUTH, "User ID token expiration timestamp is before the renewal window opens.");
public static final MslError USERIDTOKEN_USERDATA_MISSING = new MslError(2004, ResponseCode.USER_REAUTH, "No user ID token user data found.");
public static final MslError USERIDTOKEN_MASTERTOKEN_NOT_FOUND = new MslError(2005, ResponseCode.USER_REAUTH, "User ID token is bound to an unknown master token.");
public static final MslError USERIDTOKEN_MASTERTOKEN_SERIAL_NUMBER_OUT_OF_RANGE = new MslError(2006, ResponseCode.USER_REAUTH, "User ID token master token serial number is out of range.");
public static final MslError USERIDTOKEN_SERIAL_NUMBER_OUT_OF_RANGE = new MslError(2007, ResponseCode.USER_REAUTH, "User ID token serial number is out of range.");
public static final MslError USERIDTOKEN_TOKENDATA_INVALID = new MslError(2008, ResponseCode.USER_REAUTH, "Invalid user ID token data.");
public static final MslError USERIDTOKEN_SIGNATURE_INVALID = new MslError(2009, ResponseCode.USER_REAUTH, "Invalid user ID token signature.");
public static final MslError USERIDTOKEN_USERDATA_INVALID = new MslError(2010, ResponseCode.USER_REAUTH, "Invalid user ID token user data.");
public static final MslError USERIDTOKEN_IDENTITY_INVALID = new MslError(2011, ResponseCode.USER_REAUTH, "Invalid user ID token user identity.");
public static final MslError RESERVED_2012 = new MslError(2012, ResponseCode.USER_REAUTH, "The entity is not associated with the user.");
public static final MslError USERIDTOKEN_USERAUTH_DATA_MISMATCH = new MslError(2015, ResponseCode.USER_REAUTH, "The user ID token and user authentication data user identities do not match.");
public static final MslError USERIDTOKEN_TOKENDATA_MISSING = new MslError(2016, ResponseCode.USER_REAUTH, "No user ID token data found.");
public static final MslError USERIDTOKEN_TOKENDATA_PARSE_ERROR = new MslError(2017, ResponseCode.USER_REAUTH, "Error parsing user ID token data.");
public static final MslError USERIDTOKEN_USERDATA_PARSE_ERROR = new MslError(2018, ResponseCode.USER_REAUTH, "Error parsing user ID token user data.");
public static final MslError USERIDTOKEN_REVOKED = new MslError(2019, ResponseCode.USER_REAUTH, "User ID token is revoked.");
public static final MslError USERIDTOKEN_REJECTED_BY_APP = new MslError(2020, ResponseCode.USERDATA_REAUTH, "User ID token is rejected by the application.");
// 3 Service Token
public static final MslError SERVICETOKEN_MASTERTOKEN_MISMATCH = new MslError(3000, ResponseCode.FAIL, "Service token master token serial number does not match master token serial number.");
public static final MslError SERVICETOKEN_USERIDTOKEN_MISMATCH = new MslError(3001, ResponseCode.FAIL, "Service token user ID token serial number does not match user ID token serial number.");
public static final MslError SERVICETOKEN_SERVICEDATA_INVALID = new MslError(3002, ResponseCode.FAIL, "Service token data invalid.");
public static final MslError SERVICETOKEN_MASTERTOKEN_NOT_FOUND = new MslError(3003, ResponseCode.FAIL, "Service token is bound to an unknown master token.");
public static final MslError SERVICETOKEN_USERIDTOKEN_NOT_FOUND = new MslError(3004, ResponseCode.FAIL, "Service token is bound to an unknown user ID token.");
public static final MslError SERVICETOKEN_MASTERTOKEN_SERIAL_NUMBER_OUT_OF_RANGE = new MslError(3005, ResponseCode.FAIL, "Service token master token serial number is out of range.");
public static final MslError SERVICETOKEN_USERIDTOKEN_SERIAL_NUMBER_OUT_OF_RANGE = new MslError(3006, ResponseCode.FAIL, "Service token user ID token serial number is out of range.");
public static final MslError SERVICETOKEN_TOKENDATA_INVALID = new MslError(3007, ResponseCode.FAIL, "Invalid service token data.");
public static final MslError SERVICETOKEN_SIGNATURE_INVALID = new MslError(3008, ResponseCode.FAIL, "Invalid service token signature.");
public static final MslError SERVICETOKEN_TOKENDATA_MISSING = new MslError(3009, ResponseCode.FAIL, "No service token data found.");
// 4 Entity Authentication
public static final MslError UNIDENTIFIED_ENTITYAUTH_SCHEME = new MslError(4000, ResponseCode.FAIL, "Unable to identify entity authentication scheme.");
public static final MslError ENTITYAUTH_FACTORY_NOT_FOUND = new MslError(4001, ResponseCode.FAIL, "No factory registered for entity authentication scheme.");
public static final MslError X509CERT_PARSE_ERROR = new MslError(4002, ResponseCode.ENTITYDATA_REAUTH, "Error parsing X.509 certificate data.");
public static final MslError X509CERT_ENCODE_ERROR = new MslError(4003, ResponseCode.ENTITYDATA_REAUTH, "Error encoding X.509 certificate data.");
public static final MslError X509CERT_VERIFICATION_FAILED = new MslError(4004, ResponseCode.ENTITYDATA_REAUTH, "X.509 certificate verification failed.");
public static final MslError ENTITY_NOT_FOUND = new MslError(4005, ResponseCode.FAIL, "Entity not recognized.");
public static final MslError INCORRECT_ENTITYAUTH_DATA = new MslError(4006, ResponseCode.FAIL, "Entity used incorrect entity authentication data type.");
public static final MslError RSA_PUBLICKEY_NOT_FOUND = new MslError(4007, ResponseCode.ENTITYDATA_REAUTH, "RSA public key not found.");
public static final MslError UNSUPPORTED_ENTITYAUTH_DATA = new MslError(4023, ResponseCode.FAIL, "Unsupported entity authentication data.");
public static final MslError ENTITY_REVOKED = new MslError(4025, ResponseCode.FAIL, "Entity is revoked.");
public static final MslError ENTITY_REJECTED_BY_APP = new MslError(4026, ResponseCode.ENTITYDATA_REAUTH, "Entity is rejected by the application.");
public static final MslError X509CERT_EXPIRED = new MslError(4028, ResponseCode.ENTITYDATA_REAUTH, "X.509 certificate is expired.");
public static final MslError X509CERT_NOT_YET_VALID = new MslError(4029, ResponseCode.ENTITYDATA_REAUTH, "X.509 certificate is not yet valid.");
public static final MslError X509CERT_INVALID = new MslError(4030, ResponseCode.ENTITYDATA_REAUTH, "X.509 certificate is invalid.");
public static final MslError RSA_PRIVATEKEY_NOT_FOUND = new MslError(4031, ResponseCode.ENTITYDATA_REAUTH, "RSA private key not found.");
public static final MslError ENTITYAUTH_MASTERTOKEN_NOT_DECRYPTED = new MslError(4032, ResponseCode.FAIL, "Entity authentication data master token is not decrypted or verified.");
public static final MslError ENTITYAUTH_SIGNATURE_INVALID = new MslError(4033, ResponseCode.ENTITYDATA_REAUTH, "Invalid entity authentication data siganture.");
public static final MslError ENTITYAUTH_CIPHERTEXT_INVALID = new MslError(4034, ResponseCode.ENTITYDATA_REAUTH, "Invalid entity authentication data ciphertext.");
public static final MslError ENTITYAUTH_VERIFICATION_FAILED = new MslError(4035, ResponseCode.ENTITYDATA_REAUTH, "Entity authentication data signature verification failed.");
public static final MslError ENTITYAUTH_MASTERTOKEN_INVALID = new MslError(4036, ResponseCode.FAIL, "Invalid entity authentication data master token.");
public static final MslError ECC_PUBLICKEY_NOT_FOUND = new MslError(4037, ResponseCode.ENTITYDATA_REAUTH, "ECC public key not found.");
public static final MslError ECC_PRIVATEKEY_NOT_FOUND = new MslError(4038, ResponseCode.ENTITYDATA_REAUTH, "ECC private key not found.");
// 5 User Authentication
public static final MslError UNIDENTIFIED_USERAUTH_SCHEME = new MslError(5003, ResponseCode.FAIL, "Unable to identify user authentication scheme.");
public static final MslError USERAUTH_FACTORY_NOT_FOUND = new MslError(5004, ResponseCode.FAIL, "No factory registered for user authentication scheme.");
public static final MslError EMAILPASSWORD_BLANK = new MslError(5005, ResponseCode.USERDATA_REAUTH, "Email or password is blank.");
public static final MslError EMAILPASSWORD_INCORRECT = new MslError(5007, ResponseCode.USERDATA_REAUTH, "Email or password is incorrect.");
public static final MslError UNSUPPORTED_USERAUTH_DATA = new MslError(5008, ResponseCode.FAIL, "Unsupported user authentication data.");
public static final MslError USERAUTH_USERIDTOKEN_INVALID = new MslError(5011, ResponseCode.USERDATA_REAUTH, "User authentication data user ID token is invalid.");
public static final MslError UNIDENTIFIED_USERAUTH_MECHANISM = new MslError(5013, ResponseCode.FAIL, "Unable to identify user authentication mechanism.");
public static final MslError UNSUPPORTED_USERAUTH_MECHANISM = new MslError(5014, ResponseCode.FAIL, "Unsupported user authentication mechanism.");
public static final MslError USERAUTH_MASTERTOKEN_MISSING = new MslError(5016, ResponseCode.USERDATA_REAUTH, "User authentication required master token is missing.");
public static final MslError USERAUTH_USERIDTOKEN_NOT_DECRYPTED = new MslError(5021, ResponseCode.USERDATA_REAUTH, "User authentication data user ID token is not decrypted or verified.");
public static final MslError USERAUTH_MASTERTOKEN_INVALID = new MslError(5024, ResponseCode.USERDATA_REAUTH, "User authentication data master token is invalid.");
public static final MslError USERAUTH_MASTERTOKEN_NOT_DECRYPTED = new MslError(5025, ResponseCode.USERDATA_REAUTH, "User authentication data master token is not decrypted or verified.");
public static final MslError USERAUTH_USERIDTOKEN_MISSING = new MslError(5030, ResponseCode.USERDATA_REAUTH, "User authentication required user ID token is missing.");
public static final MslError USERAUTH_ENTITY_MISMATCH = new MslError(5032, ResponseCode.USERDATA_REAUTH, "User authentication data does not match entity identity.");
public static final MslError USERAUTH_ENTITY_INCORRECT_DATA = new MslError(5033, ResponseCode.FAIL, "Entity used incorrect user authentication data type.");
public static final MslError USER_REJECTED_BY_APP = new MslError(5037, ResponseCode.USERDATA_REAUTH, "User is rejected by the application.");
public static final MslError USERIDTOKEN_IDENTITY_NOT_ASSOCIATED_WITH_ENTITY = new MslError(5040, ResponseCode.USERDATA_REAUTH, "The entity is not associated with the user.");
public static final MslError USERAUTH_ENTITYUSER_INCORRECT_DATA = new MslError(5041, ResponseCode.USERDATA_REAUTH, "Entity and user combination used incorrect user authentication data type.");
public static final MslError USERAUTH_VERIFICATION_FAILED = new MslError(5042, ResponseCode.USERDATA_REAUTH, "User authentication data signature verification failed.");
public static final MslError USERAUTH_USERIDTOKEN_REVOKE_CHECK_ERROR = new MslError(5043, ResponseCode.USERDATA_REAUTH, "User ID token could not be checked for revocation.");
// 6 Message
public static final MslError UNSUPPORTED_COMPRESSION = new MslError(6000, ResponseCode.FAIL, "Unsupported compression algorithm.");
public static final MslError COMPRESSION_ERROR = new MslError(6001, ResponseCode.FAIL, "Error compressing data.");
public static final MslError UNCOMPRESSION_ERROR = new MslError(6002, ResponseCode.FAIL, "Error uncompressing data.");
public static final MslError MESSAGE_ENTITY_NOT_FOUND = new MslError(6003, ResponseCode.FAIL, "Message header entity authentication data or master token not found.");
public static final MslError PAYLOAD_MESSAGE_ID_MISMATCH = new MslError(6004, ResponseCode.FAIL, "Payload chunk message ID does not match header message ID .");
public static final MslError PAYLOAD_SEQUENCE_NUMBER_MISMATCH = new MslError(6005, ResponseCode.FAIL, "Payload chunk sequence number does not match expected sequence number.");
public static final MslError PAYLOAD_VERIFICATION_FAILED = new MslError(6006, ResponseCode.FAIL, "Payload chunk payload signature verification failed.");
public static final MslError MESSAGE_DATA_MISSING = new MslError(6007, ResponseCode.FAIL, "No message data found.");
public static final MslError MESSAGE_FORMAT_ERROR = new MslError(6008, ResponseCode.FAIL, "Malformed message data.");
public static final MslError MESSAGE_VERIFICATION_FAILED = new MslError(6009, ResponseCode.FAIL, "Message header/error data signature verification failed.");
public static final MslError HEADER_DATA_MISSING = new MslError(6010, ResponseCode.FAIL, "No header data found.");
public static final MslError PAYLOAD_DATA_MISSING = new MslError(6011, ResponseCode.FAIL, "No payload data found in non-EOM payload chunk.");
public static final MslError PAYLOAD_DATA_CORRUPT = new MslError(6012, ResponseCode.FAIL, "Corrupt payload data found in non-EOM payload chunk.");
public static final MslError UNIDENTIFIED_COMPRESSION = new MslError(6013, ResponseCode.FAIL, "Unidentified compression algorithm.");
public static final MslError MESSAGE_EXPIRED = new MslError(6014, ResponseCode.EXPIRED, "Message expired and not renewable or missing key request data. Rejected.");
public static final MslError MESSAGE_ID_OUT_OF_RANGE = new MslError(6015, ResponseCode.FAIL, "Message ID is is out of range.");
public static final MslError INTERNAL_CODE_NEGATIVE = new MslError(6016, ResponseCode.FAIL, "Error header internal code is negative.");
public static final MslError UNEXPECTED_RESPONSE_MESSAGE_ID = new MslError(6017, ResponseCode.FAIL, "Unexpected response message ID. Possible replay.");
public static final MslError RESPONSE_REQUIRES_ENCRYPTION = new MslError(6018, ResponseCode.KEYX_REQUIRED, "Message response requires encryption.");
public static final MslError PAYLOAD_SEQUENCE_NUMBER_OUT_OF_RANGE = new MslError(6019, ResponseCode.FAIL, "Payload chunk sequence number is out of range.");
public static final MslError PAYLOAD_MESSAGE_ID_OUT_OF_RANGE = new MslError(6020, ResponseCode.FAIL, "Payload chunk message ID is out of range.");
public static final MslError MESSAGE_REPLAYED = new MslError(6021, ResponseCode.REPLAYED, "Non-replayable message replayed.");
public static final MslError INCOMPLETE_NONREPLAYABLE_MESSAGE = new MslError(6022, ResponseCode.FAIL, "Non-replayable message sent without a master token.");
public static final MslError HEADER_SIGNATURE_INVALID = new MslError(6023, ResponseCode.FAIL, "Invalid Header signature.");
public static final MslError HEADER_DATA_INVALID = new MslError(6024, ResponseCode.FAIL, "Invalid header data.");
public static final MslError PAYLOAD_INVALID = new MslError(6025, ResponseCode.FAIL, "Invalid payload.");
public static final MslError PAYLOAD_SIGNATURE_INVALID = new MslError(6026, ResponseCode.FAIL, "Invalid payload signature.");
public static final MslError RESPONSE_REQUIRES_MASTERTOKEN = new MslError(6027, ResponseCode.KEYX_REQUIRED, "Message response requires a master token.");
public static final MslError RESPONSE_REQUIRES_USERIDTOKEN = new MslError(6028, ResponseCode.USER_REAUTH, "Message response requires a user ID token.");
public static final MslError REQUEST_REQUIRES_USERAUTHDATA = new MslError(6029, ResponseCode.FAIL, "User-associated message requires user authentication data.");
public static final MslError UNEXPECTED_MESSAGE_SENDER = new MslError(6030, ResponseCode.FAIL, "Message sender is not the master token entity.");
public static final MslError NONREPLAYABLE_MESSAGE_REQUIRES_MASTERTOKEN = new MslError(6031, ResponseCode.FAIL, "Non-replayable message requires a master token.");
public static final MslError NONREPLAYABLE_ID_OUT_OF_RANGE = new MslError(6032, ResponseCode.FAIL, "Non-replayable message non-replayable ID is out of range.");
public static final MslError MESSAGE_SERVICETOKEN_MISMATCH = new MslError(6033, ResponseCode.FAIL, "Service token master token or user ID token serial number does not match the message token serial numbers.");
public static final MslError MESSAGE_PEER_SERVICETOKEN_MISMATCH = new MslError(6034, ResponseCode.FAIL, "Peer service token master token or user ID token serial number does not match the message peer token serial numbers.");
public static final MslError RESPONSE_REQUIRES_INTEGRITY_PROTECTION = new MslError(6035, ResponseCode.KEYX_REQUIRED, "Message response requires integrity protection.");
public static final MslError HANDSHAKE_DATA_MISSING = new MslError(6036, ResponseCode.FAIL, "Handshake message is not renewable or does not contain key request data.");
public static final MslError MESSAGE_RECIPIENT_MISMATCH = new MslError(6037, ResponseCode.FAIL, "Message recipient does not match local identity.");
public static final MslError MESSAGE_ENTITYDATABASED_VERIFICATION_FAILED = new MslError(6038, ResponseCode.ENTITYDATA_REAUTH, "Message header entity-based signature verification failed.");
public static final MslError MESSAGE_MASTERTOKENBASED_VERIFICATION_FAILED = new MslError(6039, ResponseCode.ENTITY_REAUTH, "Message header master token-based signature verification failed.");
public static final MslError MESSAGE_REPLAYED_UNRECOVERABLE = new MslError(6040, ResponseCode.ENTITY_REAUTH, "Non-replayable message replayed with a sequence number that is too far out of sync to recover.");
public static final MslError UNEXPECTED_LOCAL_MESSAGE_SENDER = new MslError(6041, ResponseCode.FAIL, "Message sender is equal to the local entity.");
public static final MslError UNENCRYPTED_MESSAGE_WITH_USERAUTHDATA = new MslError(6042, ResponseCode.FAIL, "User authentication data included in unencrypted message header.");
public static final MslError MESSAGE_SENDER_MISMATCH = new MslError(6043, ResponseCode.FAIL, "Message sender entity identity does not match expected identity.");
public static final MslError MESSAGE_EXPIRED_NOT_RENEWABLE = new MslError(6044, ResponseCode.EXPIRED, "Message expired and not renewable. Rejected.");
public static final MslError MESSAGE_EXPIRED_NO_KEYREQUEST_DATA = new MslError(6045, ResponseCode.EXPIRED, "Message expired and missing key request data. Rejected.");
// 7 Key Exchange
public static final MslError UNIDENTIFIED_KEYX_SCHEME = new MslError(7000, ResponseCode.FAIL, "Unable to identify key exchange scheme.");
public static final MslError KEYX_FACTORY_NOT_FOUND = new MslError(7001, ResponseCode.FAIL, "No factory registered for key exchange scheme.");
public static final MslError KEYX_REQUEST_NOT_FOUND = new MslError(7002, ResponseCode.FAIL, "No key request found matching header key response data.");
public static final MslError UNIDENTIFIED_KEYX_KEY_ID = new MslError(7003, ResponseCode.FAIL, "Unable to identify key exchange key ID.");
public static final MslError UNSUPPORTED_KEYX_KEY_ID = new MslError(7004, ResponseCode.FAIL, "Unsupported key exchange key ID.");
public static final MslError UNIDENTIFIED_KEYX_MECHANISM = new MslError(7005, ResponseCode.FAIL, "Unable to identify key exchange mechanism.");
public static final MslError UNSUPPORTED_KEYX_MECHANISM = new MslError(7006, ResponseCode.FAIL, "Unsupported key exchange mechanism.");
public static final MslError KEYX_RESPONSE_REQUEST_MISMATCH = new MslError(7007, ResponseCode.FAIL, "Key exchange response does not match request.");
public static final MslError KEYX_PRIVATE_KEY_MISSING = new MslError(7008, ResponseCode.FAIL, "Key exchange private key missing.");
public static final MslError UNKNOWN_KEYX_PARAMETERS_ID = new MslError(7009, ResponseCode.FAIL, "Key exchange parameters ID unknown or invalid.");
public static final MslError KEYX_MASTER_TOKEN_MISSING = new MslError(7010, ResponseCode.FAIL, "Master token required for key exchange is missing.");
public static final MslError KEYX_INVALID_PUBLIC_KEY = new MslError(7011, ResponseCode.FAIL, "Key exchange public key is invalid.");
public static final MslError KEYX_PUBLIC_KEY_MISSING = new MslError(7012, ResponseCode.FAIL, "Key exchange public key missing.");
public static final MslError KEYX_WRAPPING_KEY_MISSING = new MslError(7013, ResponseCode.FAIL, "Key exchange wrapping key missing.");
public static final MslError KEYX_WRAPPING_KEY_ID_MISSING = new MslError(7014, ResponseCode.FAIL, "Key exchange wrapping key ID missing.");
public static final MslError KEYX_INVALID_WRAPPING_KEY = new MslError(7015, ResponseCode.FAIL, "Key exchange wrapping key is invalid.");
public static final MslError KEYX_INCORRECT_DATA = new MslError(7016, ResponseCode.FAIL, "Entity used incorrect key exchange data type.");
public static final MslError KEYX_INCORRECT_MECHANISM = new MslError(7017, ResponseCode.FAIL, "Entity used incorrect key exchange mecahnism.");
public static final MslError KEYX_DERIVATION_KEY_MISSING = new MslError(7018, ResponseCode.FAIL, "Key exchange derivation key missing.");
public static final MslError KEYX_INVALID_ENCRYPTION_KEY = new MslError(7019, ResponseCode.FAIL, "Key exchange encryption key is invalid.");
public static final MslError KEYX_INVALID_HMAC_KEY = new MslError(7020, ResponseCode.FAIL, "Key exchange HMAC key is invalid.");
public static final MslError KEYX_INVALID_WRAPDATA = new MslError(7021, ResponseCode.FAIL, "Key exchange wrap data is invalid.");
public static final MslError UNSUPPORTED_KEYX_SCHEME = new MslError(7022, ResponseCode.FAIL, "Unsupported key exchange scheme.");
public static final MslError KEYX_IDENTITY_NOT_FOUND = new MslError(7023, ResponseCode.FAIL, "Key exchange identity not found.");
// 9 Internal Errors
public static final MslError INTERNAL_EXCEPTION = new MslError(9000, ResponseCode.TRANSIENT_FAILURE, "Internal exception.");
public static final MslError MSL_COMMS_FAILURE = new MslError(9001, ResponseCode.FAIL, "Error communicating with MSL entity.");
public static final MslError NONE = new MslError(9999, ResponseCode.FAIL, "Special unit test error.");
/** Internal error code base value. */
private static final int BASE = 100000;
/**
* Construct a MSL error with the specified internal and response error
* codes and message.
*
* @param internalCode internal error code.
* @param responseCode response error code.
* @param msg developer-consumable error message.
*/
protected MslError(final int internalCode, final ResponseCode responseCode, final String msg) {
// Check for duplicates.
synchronized (internalCodes) {
if (internalCodes.contains(internalCode))
throw new MslInternalException("Duplicate MSL error definition for error code " + internalCode + ".");
internalCodes.add(internalCode);
}
this.internalCode = MslError.BASE + internalCode;
this.responseCode = responseCode;
this.msg = msg;
}
/**
* @return the internal error code.
*/
public int getInternalCode() {
return internalCode;
}
/**
* @return the response error code.
*/
public ResponseCode getResponseCode() {
return responseCode;
}
/**
* @return the error message.
*/
public String getMessage() {
return msg;
}
/**
* @param o the reference object with which to compare.
* @return true if the internal code and response code are equal.
* @see #hashCode()
*/
@Override
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof MslError)) return false;
final MslError that = (MslError)o;
return this.internalCode == that.internalCode &&
this.responseCode == that.responseCode;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Integer.valueOf(internalCode).hashCode() ^ responseCode.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "MslError{" + internalCode + "," + responseCode.intValue() + "," + msg + "}";
}
/** Internal error code. */
private final int internalCode;
/** Response error code. */
private final ResponseCode responseCode;
/** Error message. */
private final String msg;
}
| 9,817 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslErrorResponseException.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
/**
* <p>Thrown when an exception occurs while attempting to create and send an
* automatically generated error response.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslErrorResponseException extends Exception {
private static final long serialVersionUID = 3844789699705189994L;
/**
* <p>Construct a new MSL error response exception with the specified detail
* message, cause, and the original exception thrown by the request that
* prompted an automatic error response.</p>
*
* <p>The detail message should describe the error that triggered the
* automatically generated error response.</p>
*
* @param message the detail message.
* @param cause the cause.
* @param requestCause the original request exception.
*/
public MslErrorResponseException(final String message, final Throwable cause, final Throwable requestCause) {
super(message, cause);
this.requestCause = requestCause;
}
/**
* @return the exception thrown by the request that prompted the error
* response.
*/
public Throwable getRequestCause() {
return requestCause;
}
/** The original exception thrown by the request. */
private final Throwable requestCause;
}
| 9,818 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslConstants.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import java.nio.charset.Charset;
import java.util.Set;
/**
* Message security layer constants.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class MslConstants {
/** RFC-4627 defines UTF-8 as the default encoding. */
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
/** Maximum long integer value (2^53 limited by JavaScript). */
public static final long MAX_LONG_VALUE = 9007199254740992L;
/**
* The maximum number of MSL messages (requests sent or responses received)
* to allow before giving up. Six exchanges, or twelve total messages,
* should be sufficient to capture all possible error recovery and
* handshake requirements in both trusted network and peer-to-peer modes.
*/
public static final int MAX_MESSAGES = 12;
/** Compression algorithm. */
public static enum CompressionAlgorithm {
// In order of most preferred to least preferred.
/** GZIP */
GZIP,
/** LZW */
LZW;
/**
* Returns the most preferred compression algorithm from the provided
* set of algorithms.
*
* @param algos the set of algorithms to choose from.
* @return the most preferred compression algorithm or {@code null} if
* the algorithm set is empty.
*/
public static CompressionAlgorithm getPreferredAlgorithm(final Set<CompressionAlgorithm> algos) {
// Enum.values() returns the values in declaration order which will
// be the preferred order as promised above.
final CompressionAlgorithm preferredAlgos[] = CompressionAlgorithm.values();
for (int i = 0; i < preferredAlgos.length && algos.size() > 0; ++i) {
final CompressionAlgorithm preferredAlgo = preferredAlgos[i];
if (algos.contains(preferredAlgo))
return preferredAlgo;
}
return null;
}
}
/** Encryption algorithms. */
public static enum EncryptionAlgo {
/** AES */
AES,
;
/**
* @param value the string value of the encryption algorithm.
* @return the encryption algorithm associated with the string value.
* @throws IllegalArgumentException if the value is unknown.
*/
public static EncryptionAlgo fromString(final String value) {
return EncryptionAlgo.valueOf(EncryptionAlgo.class, value);
}
/**
* Returns the string value of this encryption algorithm. This will be
* equal to the Java standard algorithm name and is suitable for use
* with the JCE interfaces.
*
* @return the Java standard algorithm name for this encryption
* algorithm.
*/
@Override
public String toString() {
return name();
}
}
/** Cipher specifications. */
public static enum CipherSpec {
/** AES/CBC/PKCS5Padding */
AES_CBC_PKCS5Padding,
/** AESWrap */
AESWrap,
/** RSA/ECB/PKCS1Padding */
RSA_ECB_PKCS1Padding,
;
/** AES/CBC/PKCS5Padding string value. */
private static final String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5Padding";
/** RSA/ECB/PCKS1Padding string value. */
private static final String RSA_ECB_PKCS1PADDING = "RSA/ECB/PKCS1Padding";
/**
* @param value the string value of the cipher specification.
* @return the cipher specification associated with the string value.
* @throws IllegalArgumentException if the value is unknown.
*/
public static CipherSpec fromString(final String value) {
if (AES_CBC_PKCS5PADDING.equals(value))
return AES_CBC_PKCS5Padding;
if (RSA_ECB_PKCS1PADDING.equals(value))
return RSA_ECB_PKCS1Padding;
return CipherSpec.valueOf(CipherSpec.class, value);
}
/**
* Returns the string value of this cipher specification. This will be
* equal to the Java standard algorithm name and is suitable for use
* with the JCE interfaces.
*
* @return the Java standard algortihm name for this cipher
* specification.
*/
@Override
public String toString() {
switch (this) {
case AES_CBC_PKCS5Padding:
return AES_CBC_PKCS5PADDING;
case RSA_ECB_PKCS1Padding:
return RSA_ECB_PKCS1PADDING;
default:
return name();
}
}
}
/** Signature algorithms. */
public static enum SignatureAlgo {
/** HmacSHA256 */
HmacSHA256,
/** SHA256withRSA */
SHA256withRSA,
/** AESCmac. */
AESCmac,
;
/**
* @param value the string value of the signature algorithm.
* @return the signature algorithm associated with the string value.
* @throws IllegalArgumentException if the value is unknown.
*/
public static SignatureAlgo fromString(final String value) {
return SignatureAlgo.valueOf(SignatureAlgo.class, value);
}
/**
* Returns the string value of this signature algorithm. This will be
* equal to the Java standard algorithm name and is suitable for use
* with the JCE interfaces.
*
* @return the Java standard algortihm name for this signature
* algorithm.
*/
@Override
public String toString() {
return name();
}
}
/** Error response codes. */
public static enum ResponseCode {
/** The message is erroneous and will continue to fail if retried. */
FAIL(1),
/** The message is expected to succeed if retried after a delay. */
TRANSIENT_FAILURE(2),
/** The message is expected to succeed post entity re-authentication. */
ENTITY_REAUTH(3),
/** The message is expected to succeed post user re-authentication. */
USER_REAUTH(4),
/** The message is expected to succeed post key exchange. */
KEYX_REQUIRED(5),
/** The message is expected to succeed with new entity authentication data. */
ENTITYDATA_REAUTH(6),
/** The message is expected to succeed with new user authentication data. */
USERDATA_REAUTH(7),
/** The message is expected to succeed if retried with a renewed master token or renewable message. */
EXPIRED(8),
/** The non-replayable message is expected to succeed if retried with the newest master token. */
REPLAYED(9),
/** The message is expected to succeed with new user authentication data containing a valid single-sign-on token. */
SSOTOKEN_REJECTED(10),
;
/**
* @return the response code corresponding to the integer value.
* @throws IllegalArgumentException if the integer value does not map
* onto a response code.
*/
public static ResponseCode valueOf(final int code) {
for (final ResponseCode value : ResponseCode.values()) {
if (value.intValue() == code)
return value;
}
throw new IllegalArgumentException("Unknown response code value " + code + ".");
}
/**
* Create a new response code with the specified integer value.
*
* @param code the integer value for the response code.
*/
private ResponseCode(final int code) {
this.code = code;
}
/**
* @return the integer value of the response code.
*/
public int intValue() {
return code;
}
/** The response code value. */
private final int code;
}
}
| 9,819 |
0 | Create_ds/msl/core/src/main/java/com/netflix | Create_ds/msl/core/src/main/java/com/netflix/msl/MslMasterTokenException.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* Thrown when there is a problem with a master token, but the token was
* successfully parsed.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslMasterTokenException extends MslException {
private static final long serialVersionUID = -3151662441952286016L;
/**
* Construct a new MSL master token exception with the specified error and
* master token.
*
* @param error the error.
* @param masterToken the master token. May be null.
*/
public MslMasterTokenException(final MslError error, final MasterToken masterToken) {
super(error);
setMasterToken(masterToken);
}
/**
* Construct a new MSL master token exception with the specified error and
* master token.
*
* @param error the error.
* @param masterToken the master token. May be null.
* @param cause the exception that triggered this exception being thrown
*/
public MslMasterTokenException(final MslError error, final MasterToken masterToken, final Throwable cause) {
super(error, cause);
setMasterToken(masterToken);
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public MslMasterTokenException setUserIdToken(final UserIdToken userIdToken) {
super.setUserIdToken(userIdToken);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setUserAuthenticationData(com.netflix.msl.userauth.UserAuthenticationData)
*/
@Override
public MslMasterTokenException setUserAuthenticationData(final UserAuthenticationData userAuthData) {
super.setUserAuthenticationData(userAuthData);
return this;
}
/* (non-Javadoc)
* @see com.netflix.msl.MslException#setMessageId(long)
*/
@Override
public MslMasterTokenException setMessageId(final long messageId) {
super.setMessageId(messageId);
return this;
}
}
| 9,820 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/NullCryptoContext.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
/**
* A crypto context where encryption/decryption are no-ops, signatures are
* empty, and verification always returns true.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class NullCryptoContext extends ICryptoContext {
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
return new byte[0];
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
return true;
}
}
| 9,821 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/CryptoCache.java | /**
* Copyright (c) 2013-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
/**
* <p>The crypto context cache provides a thread-local cache of cipher and
* signature objects.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class CryptoCache {
private static class ThreadLocalMap<T> extends ThreadLocal<Map<String, T>> {
@Override
protected Map<String, T> initialValue() {
return new HashMap<String, T>();
}
}
/** Cache of transforms onto ciphers. */
private static ThreadLocal<Map<String,Cipher>> cipherCache = new ThreadLocalMap<>();
/** Cache of algorithms onto signatures. */
private static ThreadLocal<Map<String,Signature>> signatureCache = new ThreadLocalMap<>();
/** Cache of algorithms onto message digests. */
private static ThreadLocal<Map<String,MessageDigest>> digestCache = new ThreadLocalMap<>();
/** Cache of algorithms onto MACs. */
private static ThreadLocal<Map<String,Mac>> macCache = new ThreadLocalMap<>();
/** Cache of algorithms onto key factories. */
private static ThreadLocal<Map<String,KeyFactory>> keyFactoryCache = new ThreadLocalMap<>();
/** Cache of algorithms onto key agreements. */
private static ThreadLocal<Map<String,KeyAgreement>> keyAgreementCache = new ThreadLocalMap<>();
/** Cache of algorithms onto key pair generators. */
private static ThreadLocal<Map<String,KeyPairGenerator>> keyPairGeneratorCache = new ThreadLocalMap<>();
/**
* Returns a {@code Cipher} object that implements the specified transform.
*
* @param transform encrypt/decrypt transform.
* @return the cipher instance.
* @throws NoSuchAlgorithmException if transformation is null, empty, in an
* invalid format, or if no Provider supports a CipherSpi
* implementation for the specified algorithm.
* @throws NoSuchPaddingException if transformation contains a padding
* scheme that is not available.
* @see #resetCipher(String)
*/
public static Cipher getCipher(final String transform) throws NoSuchAlgorithmException, NoSuchPaddingException {
final Map<String,Cipher> ciphers = cipherCache.get();
if (!ciphers.containsKey(transform)) {
final Cipher cipher = Cipher.getInstance(transform);
ciphers.put(transform, cipher);
}
return ciphers.get(transform);
}
/**
* Resets the {@code Cipher} object that implements the specified transform.
* This method must be called if the cipher throws an exception to ensure
* a clean cipher is returned from the next call to
* {@link #getCipher(String)}.
*
* @param transform encrypt/decrypt transform.
* @see #getCipher(String)
*/
public static void resetCipher(final String transform) {
final Map<String,Cipher> ciphers = cipherCache.get();
ciphers.remove(transform);
}
/**
* Returns a {@code Signature} object that implements the specified
* algorithm.
*
* @param algorithm the sign/verify algorithm.
* @return the signature instance.
* @throws NoSuchAlgorithmException if no Provider supports a Signature
* implementation for the specified algorithm.
*/
public static Signature getSignature(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,Signature> signatures = signatureCache.get();
if (!signatures.containsKey(algorithm)) {
final Signature signature = Signature.getInstance(algorithm);
signatures.put(algorithm, signature);
}
return signatures.get(algorithm);
}
/**
* Returns a {@code MessageDigest} object that implements the specified
* algorithm.
*
* @param algorithm the digest algorithm.
* @return the message digest instance.
* @throws NoSuchAlgorithmException if no Provider supports a MessageDigest
* implementation for the specified algorithm.
*/
public static MessageDigest getMessageDigest(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,MessageDigest> digests = digestCache.get();
if (!digests.containsKey(algorithm)) {
final MessageDigest digest = MessageDigest.getInstance(algorithm);
digests.put(algorithm, digest);
}
return digests.get(algorithm);
}
/**
* Returns a {@code Mac} object that implements the specified algorithm.
*
* @param algorithm the MAC algorithm.
* @return the MAC instance.
* @throws NoSuchAlgorithmException if no Provider supports a Mac
* implementation for the specified algorithm.
*/
public static Mac getMac(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,Mac> macs = macCache.get();
if (!macs.containsKey(algorithm)) {
final Mac mac = Mac.getInstance(algorithm);
macs.put(algorithm, mac);
}
return macs.get(algorithm);
}
/**
* Returns a {@code KeyFactory} object that implements the specified
* algorithm.
*
* @param algorithm the key factory algorithm.
* @return the key factory instance.
* @throws NoSuchAlgorithmException if no Provider supports a KeyFactory
* implementation for the specified algorithm.
*/
public static KeyFactory getKeyFactory(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,KeyFactory> factories = keyFactoryCache.get();
if (!factories.containsKey(algorithm)) {
final KeyFactory factory = KeyFactory.getInstance(algorithm);
factories.put(algorithm, factory);
}
return factories.get(algorithm);
}
/**
* Returns a {@code KeyAgreement} object that implements the specified
* algorithm.
*
* @param algorithm the key agreement algorithm.
* @return the key agreement instance.
* @throws NoSuchAlgorithmException if no Provider supports a KeyAgreement
* implementation for the specified algorithm.
*/
public static KeyAgreement getKeyAgreement(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,KeyAgreement> agreements = keyAgreementCache.get();
if (!agreements.containsKey(algorithm)) {
final KeyAgreement agreement = KeyAgreement.getInstance(algorithm);
agreements.put(algorithm, agreement);
}
return agreements.get(algorithm);
}
/**
* Returns a {@code KeyPairGenerator} object that implements the specified
* algorithm.
*
* @param algorithm the key pair generator algorithm.
* @return the key pair generator instance.
* @throws NoSuchAlgorithmException if no Provider supports a
* KeyPairGenerator implementation for the specified algorithm.
*/
public static KeyPairGenerator getKeyPairGenerator(final String algorithm) throws NoSuchAlgorithmException {
final Map<String,KeyPairGenerator> generators = keyPairGeneratorCache.get();
if (!generators.containsKey(algorithm)) {
final KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm);
generators.put(algorithm, generator);
}
return generators.get(algorithm);
}
}
| 9,822 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/ClientMslCryptoContext.java | /**
* Copyright (c) 2013-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
/**
* This class should be used by trusted network clients for the primary crypto
* context used for master tokens and user ID tokens. It always fails to verify
* and its other operations are no-ops.
*
* @author Wesley Miaw <wmiaw@netflix.com>
* @see com.netflix.msl.util.MslContext#getMslCryptoContext()
*/
public class ClientMslCryptoContext extends ICryptoContext {
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
// This should never be called.
throw new MslInternalException("Wrap is unsupported by the MSL token crypto context.");
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
// This should never be called.
throw new MslInternalException("Unwrap is unsupported by the MSL token crypto context.");
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
return new byte[0];
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
return false;
}
}
| 9,823 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/AsymmetricCryptoContext.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
/**
* An asymmetric crypto context performs encrypt/decrypt and sign/verify using
* a public/private key pair. Wrap/unwrap are unsupported.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class AsymmetricCryptoContext extends ICryptoContext {
/** Null transform or algorithm. */
protected static final String NULL_OP = "nullOp";
/**
* <p>Create a new asymmetric crypto context using the provided public and
* private keys and named encrypt/decrypt transform and sign/verify
* algorithm.</p>
*
* <p>If there is no private key, decryption and signing is unsupported.</p>
*
* <p>If there is no public key, encryption and verification is
* unsupported.</p>
*
* <p>If {@code #NULL_OP} is specified for the transform then encrypt/
* decrypt operations will return the data unmodified even if the key is
* null. Otherwise the operation is unsupported if the key is null.</p>
*
* <p>If {@code #NULL_OP} is specified for the algorithm then sign/verify
* will return an empty signature and always pass verification even if the
* key is null. Otherwise the operation is unsupported if the key is
* null.</p>
*
* @param id the key pair identity.
* @param privateKey the private key used for signing. May be null.
* @param publicKey the public key used for verifying. May be null.
* @param transform encrypt/decrypt transform.
* @param params encrypt/decrypt algorithm parameters. May be null.
* @param algo sign/verify algorithm.
*/
protected AsymmetricCryptoContext(final String id, final PrivateKey privateKey, final PublicKey publicKey, final String transform, final AlgorithmParameterSpec params, final String algo) {
this.id = id;
this.privateKey = privateKey;
this.publicKey = publicKey;
this.transform = transform;
this.params = params;
this.algo = algo;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (NULL_OP.equals(transform))
return data;
if (publicKey == null)
throw new MslCryptoException(MslError.ENCRYPT_NOT_SUPPORTED, "no public key");
Throwable reset = null;
try {
// Encrypt plaintext.
final Cipher cipher = CryptoCache.getCipher(transform);
cipher.init(Cipher.ENCRYPT_MODE, publicKey, params);
final byte[] ciphertext = cipher.doFinal(data);
// Return encryption envelope byte representation.
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(id, null, ciphertext);
return envelope.toMslEncoding(encoder, format);
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_BAD_PADDING, "not expected when encrypting", e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final MslEncoderException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_ENCODE_ERROR, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(transform);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
if (NULL_OP.equals(transform))
return data;
if (privateKey == null)
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED, "no private key");
Throwable reset = null;
try {
// Reconstitute encryption envelope.
final MslObject encryptionEnvelopeMo = encoder.parseObject(data);
final MslCiphertextEnvelope encryptionEnvelope = new MslCiphertextEnvelope(encryptionEnvelopeMo, MslCiphertextEnvelope.Version.V1);
// Decrypt ciphertext.
final Cipher cipher = CryptoCache.getCipher(transform);
cipher.init(Cipher.DECRYPT_MODE, privateKey, params);
return cipher.doFinal(encryptionEnvelope.getCiphertext());
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PRIVATE_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_BAD_PADDING, e);
} catch (final MslEncoderException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR, e);
} catch (final MslEncodingException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR, e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(transform);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.WRAP_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.UNWRAP_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (NULL_OP.equals(algo))
return new byte[0];
if (privateKey == null)
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED, "no private key.");
try {
final Signature sig = CryptoCache.getSignature(algo);
sig.initSign(privateKey);
sig.update(data);
final byte[] signature = sig.sign();
// Return the signature envelope byte representation.
return new MslSignatureEnvelope(signature).getBytes(encoder, format);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid signature algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_PRIVATE_KEY, e);
} catch (final SignatureException e) {
throw new MslCryptoException(MslError.SIGNATURE_ERROR, e);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.SIGNATURE_ENVELOPE_ENCODE_ERROR, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
if (NULL_OP.equals(algo))
return true;
if (publicKey == null)
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED, "no public key.");
try {
// Reconstitute the signature envelope.
final MslSignatureEnvelope envelope = MslSignatureEnvelope.parse(signature, encoder);
final Signature sig = CryptoCache.getSignature(algo);
sig.initVerify(publicKey);
sig.update(data);
return sig.verify(envelope.getSignature());
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid signature algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, e);
} catch (final SignatureException e) {
throw new MslCryptoException(MslError.SIGNATURE_ERROR, e);
} catch (final MslEncodingException e) {
throw new MslCryptoException(MslError.SIGNATURE_ENVELOPE_PARSE_ERROR, e);
}
}
/** Key pair identity. */
protected final String id;
/** Encryption/decryption cipher. */
protected final PrivateKey privateKey;
/** Sign/verify signature. */
protected final PublicKey publicKey;
/** Encryption/decryption transform. */
private final String transform;
/** Encryption/decryption algorithm parameters. */
private final AlgorithmParameterSpec params;
/** Sign/verify algorithm. */
private final String algo;
}
| 9,824 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/EccCryptoContext.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
* An ECC crypto context performs ECIES encryption/decryption or SHA-1 with
* ECDSA sign/verify using a public/private ECC key pair.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class EccCryptoContext extends AsymmetricCryptoContext {
/** ECC crypto context mode. .*/
public static enum Mode {
ENCRYPT_DECRYPT,
SIGN_VERIFY
};
/**
* <p>Create a new ECC crypto context using the provided public and private
* keys.</p>
*
* <p>If there is no private key, decryption and signing is unsupported.</p>
*
* <p>If there is no public key, encryption and verification is
* unsupported.</p>
*
* @param id the key pair identity.
* @param privateKey the private key used for signing. May be null.
* @param publicKey the public key used for verifying. May be null.
* @param mode crypto context mode.
*/
public EccCryptoContext(final String id, final PrivateKey privateKey, final PublicKey publicKey, final Mode mode) {
super(id, privateKey, publicKey, Mode.ENCRYPT_DECRYPT.equals(mode) ? "ECIES" : NULL_OP, null, Mode.SIGN_VERIFY.equals(mode) ? "SHA256withECDSA" : NULL_OP);
}
}
| 9,825 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/SessionCryptoContext.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import javax.crypto.SecretKey;
import com.netflix.msl.MslError;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* This is a convenience class for constructing a symmetric crypto context from
* a MSL session master token.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class SessionCryptoContext extends SymmetricCryptoContext {
/**
* <p>Construct a new session crypto context from the provided master
* token.</p>
*
* @param ctx MSL context.
* @param masterToken the master token.
* @throws MslMasterTokenException if the master token is not trusted.
*/
public SessionCryptoContext(final MslContext ctx, final MasterToken masterToken) throws MslMasterTokenException {
this(ctx, masterToken, masterToken.getIdentity(), masterToken.getEncryptionKey(), masterToken.getSignatureKey());
if (!masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
}
/**
* <p>Construct a new session crypto context from the provided master token.
* The entity identity and keys are assumed to be the same as what is
* inside the master token, which may be untrusted.</p>
*
* @param ctx MSL context.
* @param masterToken master token. May be untrusted.
* @param identity entity identity. May be {@code null}.
* @param encryptionKey encryption key.
* @param hmacKey HMAC key.
*/
public SessionCryptoContext(final MslContext ctx, final MasterToken masterToken, final String identity, final SecretKey encryptionKey, final SecretKey hmacKey) {
super(ctx, (identity != null) ? identity + "_" + masterToken.getSequenceNumber() : Long.toString(masterToken.getSequenceNumber()), encryptionKey, hmacKey, null);
}
}
| 9,826 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/JsonWebEncryptionCryptoContext.java | /**
* Copyright (c) 2013-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslArray;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslEncoderUtils;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.MslContext;
/**
* <p>This key exchange crypto context provides an implementation of the JSON
* web encryption algorithm as defined in
* <a href="http://tools.ietf.org/html/draft-ietf-mose-json-web-encryption-08">JSON Web Encryption</a>.
* It supports a limited subset of the algorithms.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class JsonWebEncryptionCryptoContext extends ICryptoContext {
/** Encoding charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/** JSON key recipients. */
private static final String KEY_RECIPIENTS = "recipients";
/** JSON key header. */
private static final String KEY_HEADER = "header";
/** JSON key encrypted key. */
private static final String KEY_ENCRYPTED_KEY = "encrypted_key";
/** JSON key integrity value. */
private static final String KEY_INTEGRITY_VALUE = "integrity_value";
/** JSON key initialization vector. */
private static final String KEY_INITIALIZATION_VECTOR = "initialization_vector";
/** JSON key ciphertext. */
private static final String KEY_CIPHERTEXT = "ciphertext";
/** JSON key wrap algorithm. */
private static final String KEY_ALGORITHM = "alg";
/** JSON key encryption algorithm. */
private static final String KEY_ENCRYPTION = "enc";
/** AES-128 GCM authentication tag length in bits. */
private static final int A128_GCM_AT_LENGTH = 128;
/** AES-128 GCM key length in bytes. */
private static final int A128_GCM_KEY_LENGTH = 16;
/** AES-128 GCM initialization vector length in bytes. */
private static final int A128_GCM_IV_LENGTH = 12;
/** AES-256 GCM authentication tag length in bits. */
private static final int A256_GCM_AT_LENGTH = 128;
/** AES-256 GCM key length in bytes. */
private static final int A256_GCM_KEY_LENGTH = 32;
/** AES-256 GCM initialization vector length in bytes. */
private static final int A256_GCM_IV_LENGTH = 12;
/** Supported content encryption key encryption algorithms. */
private static enum Algorithm {
/** RSAES-OAEP */
RSA_OAEP("RSA-OAEP"),
/** AES-128 Key Wrap */
A128KW("A128KW");
/**
* @param name JSON Web Encryption algorithm name.
*/
private Algorithm(final String name) {
this.name = name;
}
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return name;
}
/**
* @param name JSON Web Encryption algorithm name.
* @return the algorithm.
* @throws IllegalArgumentException if the algorithm name is unknown.
*/
public static Algorithm fromString(final String name) {
for (final Algorithm algo : values()) {
if (algo.toString().equals(name))
return algo;
}
throw new IllegalArgumentException("Algorithm " + name + " is unknown.");
}
/** JSON Web Encryption algorithm name. */
private final String name;
}
/**
* The Content Encryption Key crypto context is used to encrypt/decrypt the
* randomly generated content encryption key.
*/
public static abstract class CekCryptoContext extends ICryptoContext {
/**
* Create a new content encryption key crypto context with the
* specified content encryption key encryption algorithm.
*
* @param algo content encryption key encryption algorithm.
*/
protected CekCryptoContext(final Algorithm algo) {
this.algo = algo;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.WRAP_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.UNWRAP_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED);
}
/**
* @return the content encryption key encryption algorithm.
*/
Algorithm getAlgorithm() {
return algo;
}
/** Content encryption key encryption algorithm. */
private final Algorithm algo;
}
/**
* RSA-OAEP encrypt/decrypt of the content encryption key.
*/
public static class RsaOaepCryptoContext extends CekCryptoContext {
/** RSA-OAEP cipher transform. */
private static final String RSA_OAEP_TRANSFORM = "RSA/ECB/OAEPPadding";
/**
* <p>Create a new RSA crypto context for encrypt/decrypt using the
* provided public and private keys. All other operations are
* unsupported.</p>
*
* <p>If there is no private key decryption is unsupported.</p>
*
* <p>If there is no public key encryption is unsupported.</p>
*
* @param privateKey the private key. May be null.
* @param publicKey the public key. May be null.
*/
public RsaOaepCryptoContext(final PrivateKey privateKey, final PublicKey publicKey) {
super(Algorithm.RSA_OAEP);
this.privateKey = privateKey;
this.publicKey = publicKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (publicKey == null)
throw new MslCryptoException(MslError.ENCRYPT_NOT_SUPPORTED, "no public key");
Throwable reset = null;
try {
// Encrypt plaintext.
final Cipher cipher = CryptoCache.getCipher(RSA_OAEP_TRANSFORM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey, OAEPParameterSpec.DEFAULT);
return cipher.doFinal(data);
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_BAD_PADDING, "not expected when encrypting", e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(RSA_OAEP_TRANSFORM);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
if (privateKey == null)
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED, "no private key");
Throwable reset = null;
try {
// Decrypt ciphertext.
final Cipher cipher = CryptoCache.getCipher(RSA_OAEP_TRANSFORM);
cipher.init(Cipher.DECRYPT_MODE, privateKey, OAEPParameterSpec.DEFAULT);
return cipher.doFinal(data);
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PRIVATE_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_BAD_PADDING, e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(RSA_OAEP_TRANSFORM);
}
}
/** Encryption/decryption cipher. */
protected final PrivateKey privateKey;
/** Sign/verify signature. */
protected final PublicKey publicKey;
}
/**
* AES key wrap encrypt/decrypt of the content encryption key.
*/
public static class AesKwCryptoContext extends CekCryptoContext {
/** AES key wrap cipher transform. */
private static final String A128_KW_TRANSFORM = "AESWrap";
/**
* Create a new AES key wrap crypto context with the provided secret
* key.
*
* @param key AES secret key.
*/
public AesKwCryptoContext(final SecretKey key) {
super(Algorithm.A128KW);
if (!key.getAlgorithm().equals(JcaAlgorithm.AESKW))
throw new IllegalArgumentException("Secret key must be an " + JcaAlgorithm.AESKW + " key.");
this.key = key;
this.cryptoContext = null;
}
/**
* Create a new AES key wrap crypto context backed by the provided
* AES crypto context.
*
* @param cryptoContext AES crypto context.
*/
public AesKwCryptoContext(final ICryptoContext cryptoContext) {
super(Algorithm.A128KW);
this.key = null;
this.cryptoContext = cryptoContext;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
// If a secret key is provided use it.
if (key != null) {
try {
// Encrypt plaintext.
final Cipher cipher = CryptoCache.getCipher(A128_KW_TRANSFORM);
cipher.init(Cipher.WRAP_MODE, key);
// TODO: The key spec algorithm should be based on the JWE
// encryption algorithm. Right now that is always AES-GCM.
final Key secretKey = new SecretKeySpec(data, "AES");
return cipher.wrap(secretKey);
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Invalid content encryption key provided.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
}
}
// Otherwise use the backing crypto context.
return cryptoContext.wrap(data, encoder, format);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
// If a secret key is provided use it.
if (key != null) {
try {
// Decrypt ciphertext.
final Cipher cipher = CryptoCache.getCipher(A128_KW_TRANSFORM);
cipher.init(Cipher.UNWRAP_MODE, key);
return cipher.unwrap(data, "AES", Cipher.SECRET_KEY).getEncoded();
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
}
}
// Otherwise use the backing crypto context.
return cryptoContext.unwrap(data, encoder);
}
/** AES secret key. */
private final SecretKey key;
/** AES crypto context. */
private final ICryptoContext cryptoContext;
}
/** Supported plaintext encryption algorithms. */
public static enum Encryption {
/** AES-128 GCM */
A128GCM,
/** AES-256 GCM */
A256GCM,
}
/** Support serialization formats. */
public static enum Format {
/**
* <a href="http://tools.ietf.org/html/draft-mones-mose-jwe-json-serialization-04">JSON Web Encryption JSON Serialization (JWE-JS)</a>
*/
JWE_JS,
/**
* <a href="http://tools.ietf.org/html/draft-ietf-mose-json-web-encryption-08">JSON Web Encryption Compact Serialization</a>
*/
JWE_CS
}
/**
* Create a new JSON web encryption crypto context with the provided
* content encryption key crypto context and specified plaintext encryption
* algorithm.
*
* @param ctx MSL context.
* @param cryptoContext content encryption key crypto context.
* @param enc plaintext encryption algorithm.
* @param format serialization format.
*/
public JsonWebEncryptionCryptoContext(final MslContext ctx, final CekCryptoContext cryptoContext, final Encryption enc, final Format format) {
this.ctx = ctx;
this.cekCryptoContext = cryptoContext;
this.algo = cryptoContext.getAlgorithm();
this.enc = enc;
this.format = format;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.ENCRYPT_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
// Create the header.
final byte[] header;
try {
final MslObject headerMo = encoder.createObject();
headerMo.put(KEY_ALGORITHM, algo.toString());
headerMo.put(KEY_ENCRYPTION, enc.name());
header = encoder.encodeObject(headerMo, MslEncoderFormat.JSON);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.JWE_ENCODE_ERROR, e);
}
// Determine algorithm byte lengths.
final int keylen, ivlen, atlen;
if (Encryption.A128GCM.equals(enc)) {
keylen = A128_GCM_KEY_LENGTH;
ivlen = A128_GCM_IV_LENGTH;
atlen = A128_GCM_AT_LENGTH;
} else if (Encryption.A256GCM.equals(enc)) {
keylen = A256_GCM_KEY_LENGTH;
ivlen = A256_GCM_IV_LENGTH;
atlen = A256_GCM_AT_LENGTH;
} else {
throw new MslCryptoException(MslError.UNSUPPORTED_JWE_ALGORITHM, enc.name());
}
// Generate the key and IV.
final Random random = ctx.getRandom();
final byte[] key = new byte[keylen];
random.nextBytes(key);
final KeyParameter cek = new KeyParameter(key);
final byte[] iv = new byte[ivlen];
random.nextBytes(iv);
// Encrypt the CEK.
final byte[] ecek = cekCryptoContext.encrypt(cek.getKey(), encoder, MslEncoderFormat.JSON);
// Base64-encode the data.
final String headerB64 = MslEncoderUtils.b64urlEncode(header);
final String ecekB64 = MslEncoderUtils.b64urlEncode(ecek);
final String ivB64 = MslEncoderUtils.b64urlEncode(iv);
// Create additional authenticated data.
final String aad = headerB64 + "." + ecekB64 + "." + ivB64;
// TODO: AES-GCM is not available via the JCE.
//
// Create and initialize the cipher for encryption.
final GCMBlockCipher plaintextCipher = new GCMBlockCipher(new AESEngine());
final AEADParameters params = new AEADParameters(cek, atlen, iv, aad.getBytes(UTF_8));
plaintextCipher.init(true, params);
// Encrypt the plaintext.
final byte[] ciphertextATag;
try {
final int clen = plaintextCipher.getOutputSize(data.length);
ciphertextATag = new byte[clen];
// Encrypt the plaintext and get the resulting ciphertext length
// which will be used for the authentication tag offset.
final int offset = plaintextCipher.processBytes(data, 0, data.length, ciphertextATag, 0);
// Append the authentication tag.
plaintextCipher.doFinal(ciphertextATag, offset);
} catch (final IllegalStateException e) {
throw new MslCryptoException(MslError.WRAP_ERROR, e);
} catch (final InvalidCipherTextException e) {
throw new MslInternalException("Invalid ciphertext not expected when encrypting.", e);
}
// Split the result into the ciphertext and authentication tag.
final byte[] ciphertext = Arrays.copyOfRange(ciphertextATag, 0, ciphertextATag.length - atlen/Byte.SIZE);
final byte[] at = Arrays.copyOfRange(ciphertextATag, ciphertext.length, ciphertextATag.length);
// Base64-encode the ciphertext and authentication tag.
final String ciphertextB64 = MslEncoderUtils.b64urlEncode(ciphertext);
final String atB64 = MslEncoderUtils.b64urlEncode(at);
// Envelope the data.
switch (this.format) {
case JWE_CS:
{
final String serialization = aad + "." + ciphertextB64 + "." + atB64;
return serialization.getBytes(UTF_8);
}
case JWE_JS:
{
try {
// Create recipients array.
final MslArray recipients = encoder.createArray();
final MslObject recipient = encoder.createObject();
recipient.put(KEY_HEADER, headerB64);
recipient.put(KEY_ENCRYPTED_KEY, ecekB64);
recipient.put(KEY_INTEGRITY_VALUE, atB64);
recipients.put(-1, recipient);
// Create JSON serialization.
final MslObject serialization = encoder.createObject();
serialization.put(KEY_RECIPIENTS, recipients);
serialization.put(KEY_INITIALIZATION_VECTOR, ivB64);
serialization.put(KEY_CIPHERTEXT, ciphertextB64);
return encoder.encodeObject(serialization, MslEncoderFormat.JSON);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.JWE_ENCODE_ERROR, e);
}
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_JWE_SERIALIZATION, format.name());
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
// Parse the serialization.
final String serialization = new String(data, UTF_8);
final String headerB64, ecekB64, ivB64;
final byte[] ciphertext, at;
if (data[0] == '{') {
try {
final MslObject serializationMo = encoder.parseObject(data);
ivB64 = serializationMo.getString(KEY_INITIALIZATION_VECTOR);
ciphertext = MslEncoderUtils.b64urlDecode(serializationMo.getString(KEY_CIPHERTEXT));
// TODO: For now, we only support one recipient.
final MslArray recipients = serializationMo.getMslArray(KEY_RECIPIENTS);
if (recipients.size() < 1)
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, serialization);
final MslObject recipient = recipients.getMslObject(0, encoder);
headerB64 = recipient.getString(KEY_HEADER);
ecekB64 = recipient.getString(KEY_ENCRYPTED_KEY);
at = MslEncoderUtils.b64urlDecode(recipient.getString(KEY_INTEGRITY_VALUE));
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, serialization, e);
}
} else {
// Separate the compact serialization.
final String[] parts = serialization.split("\\.");
if (parts.length != 5)
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, serialization);
// Extract the data from the serialization.
headerB64 = parts[0];
ecekB64 = parts[1];
ivB64 = parts[2];
ciphertext = MslEncoderUtils.b64urlDecode(parts[3]);
at = MslEncoderUtils.b64urlDecode(parts[4]);
}
// Decode header, encrypted content encryption key, and IV.
final byte[] headerBytes = MslEncoderUtils.b64urlDecode(headerB64);
final byte[] ecek = MslEncoderUtils.b64urlDecode(ecekB64);
final byte[] iv = MslEncoderUtils.b64urlDecode(ivB64);
// Verify data.
if (headerBytes == null || headerBytes.length == 0 ||
ecek == null || ecek.length == 0 ||
iv == null || iv.length == 0 ||
ciphertext == null || ciphertext.length == 0 ||
at == null || at.length == 0)
{
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, serialization);
}
// Reconstruct and parse the header.
final String header = new String(headerBytes, UTF_8);
final Algorithm algo;
final Encryption enc;
try {
final MslObject headerMo = encoder.parseObject(headerBytes);
final String algoName = headerMo.getString(KEY_ALGORITHM);
try {
algo = Algorithm.fromString(algoName);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, algoName, e);
}
final String encName = headerMo.getString(KEY_ENCRYPTION);
try {
enc = Encryption.valueOf(encName);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, encName, e);
}
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.JWE_PARSE_ERROR, header, e);
}
// Confirm header matches.
if (!this.algo.equals(algo) || !this.enc.equals(enc))
throw new MslCryptoException(MslError.JWE_ALGORITHM_MISMATCH, header);
// Decrypt the CEK.
final KeyParameter cek;
try {
final byte[] cekBytes = cekCryptoContext.decrypt(ecek, encoder);
cek = new KeyParameter(cekBytes);
} catch (final ArrayIndexOutOfBoundsException e) {
// Thrown if the encrypted content encryption key is an invalid
// length.
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
}
// Create additional authenticated data.
final String aad = headerB64 + "." + ecekB64 + "." + ivB64;
// Determine algorithm byte lengths.
final int keylen, atlen;
if (Encryption.A128GCM.equals(enc)) {
keylen = A128_GCM_KEY_LENGTH;
atlen = A128_GCM_AT_LENGTH;
} else if (Encryption.A256GCM.equals(enc)) {
keylen = A256_GCM_KEY_LENGTH;
atlen = A256_GCM_AT_LENGTH;
} else {
throw new MslCryptoException(MslError.UNSUPPORTED_JWE_ALGORITHM, enc.name());
}
// Verify algorithm parameters.
if (cek.getKey().length != keylen)
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, "content encryption key length: " + cek.getKey().length);
if (at.length != atlen / Byte.SIZE)
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, "authentication tag length: " + at.length);
// TODO: AES-GCM is not available via the JCE.
//
// Create and initialize the cipher for decryption.
final GCMBlockCipher plaintextCipher = new GCMBlockCipher(new AESEngine());
final AEADParameters params = new AEADParameters(cek, atlen, iv, aad.getBytes(UTF_8));
plaintextCipher.init(false, params);
// Decrypt the ciphertext.
try {
// Reconstruct the ciphertext and authentication tag.
final byte[] ciphertextAtag = Arrays.copyOf(ciphertext, ciphertext.length + at.length);
System.arraycopy(at, 0, ciphertextAtag, ciphertext.length, at.length);
final int plen = plaintextCipher.getOutputSize(ciphertextAtag.length);
final byte[] plaintext = new byte[plen];
// Decrypt the ciphertext and get the resulting plaintext length
// which will be used for the authentication tag offset.
final int offset = plaintextCipher.processBytes(ciphertextAtag, 0, ciphertextAtag.length, plaintext, 0);
// Verify the authentication tag.
plaintextCipher.doFinal(plaintext, offset);
return plaintext;
} catch (final IllegalStateException e) {
throw new MslCryptoException(MslError.UNWRAP_ERROR, e);
} catch (final InvalidCipherTextException e) {
throw new MslCryptoException(MslError.UNWRAP_ERROR, e);
} catch (final ArrayIndexOutOfBoundsException e) {
// Thrown if the ciphertext is an invalid length.
throw new MslCryptoException(MslError.UNWRAP_ERROR, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED);
}
/** MSL context. */
private final MslContext ctx;
/** Content encryption key crypto context. */
private final ICryptoContext cekCryptoContext;
/** Wrap algorithm. */
private final Algorithm algo;
/** Encryption algorithm. */
private final Encryption enc;
/** Serialization format. */
private final Format format;
}
| 9,827 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/ICryptoContext.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.msg.ErrorHeader;
/**
* A generic cryptographic context suitable for encryption/decryption,
* wrap/unwrap, and sign/verify operations.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class ICryptoContext {
/**
* Encrypts some data.
*
* @param data the plaintext.
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the ciphertext.
* @throws MslCryptoException if there is an error encrypting the data.
*/
public abstract byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException;
/**
* Decrypts some data.
*
* @param data the ciphertext.
* @param encoder MSL encoder factory.
* @return the plaintext.
* @throws MslCryptoException if there is an error decrypting the data.
*/
public abstract byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException;
/**
* Wraps some data.
*
* @param data the plaintext.
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the wrapped data.
* @throws MslCryptoException if there is an error wrapping the data.
*/
public abstract byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException;
/**
* Unwraps some data.
*
* @param data the wrapped data.
* @param encoder MSL encoder factory.
* @return the plaintext.
* @throws MslCryptoException if there is an error unwrapping the data.
*/
public abstract byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException;
/**
* Computes the signature for some data. The signature may not be a
* signature proper, but the name suits the concept.
*
* @param data the data.
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the signature.
* @throws MslCryptoException if there is an error computing the signature.
*/
public abstract byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException;
/**
* Computes the signature for some data. This form of the sign method
* accepts an additional MSL ErrorHeader object that can be used as
* operational context when signing errors. The default implementation
* below ignores that parameter, but subclasses can provide an override.
*
* @param data the data.
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @param errorHeader MSL ErrorHeader instance
* @return the signature.
* @throws MslCryptoException if there is an error computing the signature.
*/
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format, ErrorHeader errorHeader) throws MslCryptoException {
return sign(data, encoder, format);
}
/**
* Verifies the signature for some data. The signature may not be a
* signature proper, but the name suits the concept.
*
* @param data the data.
* @param signature the signature.
* @param encoder MSL encoder factory.
* @return true if the data is verified, false if validation fails.
* @throws MslCryptoException if there is an error verifying the signature.
*/
public abstract boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException;
}
| 9,828 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/RsaCryptoContext.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.spec.OAEPParameterSpec;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.util.MslContext;
/**
* <p>An RSA crypto context supports RSA/ECB/OAEPPadding or RSA/ECB/PKCS#1
* encryption/decryption, or SHA-256 with RSA sign/verify.</p>
*
* <p>The {@link OAEPParameterSpec#DEFAULT} parameters are used for OAEP
* encryption and decryption.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class RsaCryptoContext extends AsymmetricCryptoContext {
/** RSA crypto context algorithm. .*/
public static enum Mode {
/** RSA-OAEP encrypt/decrypt */
ENCRYPT_DECRYPT_OAEP,
/** RSA PKCS#1 encrypt/decrypt */
ENCRYPT_DECRYPT_PKCS1,
/** RSA-KEM wrap/unwrap */
WRAP_UNWRAP,
/** RSA-SHA256 sign/verify */
SIGN_VERIFY
};
/**
* <p>Create a new RSA crypto context for encrypt/decrypt and sign/verify
* using the provided public and private keys. The crypto context algorithm
* identifies the operations to enable. All other operations are no-ops and
* return the data unmodified.</p>
*
* <p>If there is no private key, decryption and signing is unsupported.</p>
*
* <p>If there is no public key, encryption and verification is
* unsupported.</p>
*
* @param ctx MSL context.
* @param id the key pair identity.
* @param privateKey the private key. May be null.
* @param publicKey the public key. May be null.
* @param algo crypto context algorithm.
*/
public RsaCryptoContext(final MslContext ctx, final String id, final PrivateKey privateKey, final PublicKey publicKey, final Mode algo) {
super(id, privateKey, publicKey,
Mode.ENCRYPT_DECRYPT_PKCS1.equals(algo) ? "RSA/ECB/PKCS1Padding" : (Mode.ENCRYPT_DECRYPT_OAEP.equals(algo) ? "RSA/ECB/OAEPPadding" : NULL_OP),
Mode.ENCRYPT_DECRYPT_OAEP.equals(algo) ? OAEPParameterSpec.DEFAULT : null,
Mode.SIGN_VERIFY.equals(algo) ? "SHA256withRSA" : NULL_OP);
if (algo == Mode.WRAP_UNWRAP)
throw new MslInternalException("Wrap/unwrap unsupported.");
}
}
| 9,829 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/MslSignatureEnvelope.java | /**
* Copyright (c) 2013-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import com.netflix.msl.MslConstants.SignatureAlgo;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>MSL signature envelopes contain all of the information necessary for
* verifying data using a known key.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslSignatureEnvelope {
/** Key version. */
private final static String KEY_VERSION = "version";
/** Key algorithm. */
private final static String KEY_ALGORITHM = "algorithm";
/** Key signature. */
private final static String KEY_SIGNATURE = "signature";
/** Versions. */
public static enum Version {
/**
* <p>Version 1.</p>
*
* {@code signature}
*
* <p>The signature is represented as raw bytes.</p>
*/
V1,
/**
* <p>Version 2.</p>
*
* {@code {
* "#mandatory" : [ "version", "algorithm", "signature" ],
* "version" : "number",
* "algorithm" : "string",
* "signature" : "binary"
* }} where:
* <ul>
* <li>{@code version} is the number '2'</li>
* <li>{@code algorithm} is one of the recognized signature algorithms</li>
* <li>{@code signature} is the signature</li>
* </ul>
*
* <p>Supported algorithms:
* <table>
* <tr><th>Algorithm</th><th>Description</th>
* <tr><td>HmacSHA256</td><td>HMAC w/SHA-256</td></tr>
* <tr><td>SHA256withRSA</td><td>RSA signature w/SHA-256</td></tr>
* <tr><td>AESCmac</td><td>AES CMAC</td></tr>
* </table></p>
*/
V2;
/**
* @param version the integer value of this version.
* @return the version identified by the integer value.
* @throws IllegalArgumentException if the version is unknown.
*/
public static Version valueOf(final int version) {
switch (version) {
case 1: return V1;
case 2: return V2;
default: throw new IllegalArgumentException("Unknown signature envelope version.");
}
}
/**
* @return the integer value of this version.
*/
public int intValue() {
switch (this) {
case V1: return 1;
case V2: return 2;
default: throw new MslInternalException("No integer value defined for version " + this + ".");
}
}
}
/**
* Create a new version 1 signature envelope with the provided signature.
*
* @param signature the signature.
*/
public MslSignatureEnvelope(final byte[] signature) {
this.version = Version.V1;
this.algorithm = null;
this.signature = signature;
}
/**
* Create a new version 2 signature envelope with the provided data.
*
* @param algorithm the signature algorithm.
* @param signature the signature.
*/
public MslSignatureEnvelope(final SignatureAlgo algorithm, final byte[] signature) {
this.version = Version.V2;
this.algorithm = algorithm;
this.signature = signature;
}
/**
* Create a new signature envelope for the specified version from the
* provided envelope bytes.
*
* @param ctx MSL context.
* @param envelope the raw envelope bytes.
* @param version the envelope version.
* @return the envelope.
* @throws MslCryptoException if there is an error processing the signature
* envelope.
* @throws MslEncodingException if there is an error parsing the envelope.
* @see #getBytes(MslEncoderFactory, MslEncoderFormat)
*/
public static MslSignatureEnvelope parse(final MslContext ctx, final byte[] envelope, final Version version) throws MslCryptoException, MslEncodingException {
// Parse envelope.
switch (version) {
case V1:
return new MslSignatureEnvelope(envelope);
case V2:
try {
// We expect the byte representation to be a MSL object.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject envelopeMo = encoder.parseObject(envelope);
// Verify version.
try {
final Version v = Version.valueOf(envelopeMo.getInt(KEY_VERSION));
if (!Version.V2.equals(v))
throw new MslCryptoException(MslError.UNSUPPORTED_SIGNATURE_ENVELOPE, "signature envelope " + envelopeMo);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_SIGNATURE_ENVELOPE, "signature envelope " + envelopeMo, e);
}
// Grab algorithm.
final SignatureAlgo algorithm;
try {
algorithm = SignatureAlgo.fromString(envelopeMo.getString(KEY_ALGORITHM));
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_ALGORITHM, "signature envelope " + envelopeMo, e);
}
// Grab signature.
final byte[] signature = envelopeMo.getBytes(KEY_SIGNATURE);
// Return the envelope.
return new MslSignatureEnvelope(algorithm, signature);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "signature envelope " + Base64.encode(envelope), e);
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_SIGNATURE_ENVELOPE, "signature envelope " + Base64.encode(envelope));
}
}
/**
* Create a new signature envelope from the provided envelope bytes.
*
* @param envelope the raw envelope bytes.
* @param encoder MSL encoder factory.
* @return the envelope.
* @throws MslCryptoException if there is an error processing the signature
* envelope.
* @throws MslEncodingException if there is an error parsing the envelope.
* @see #getBytes(MslEncoderFactory, MslEncoderFormat)
*/
public static MslSignatureEnvelope parse(final byte[] envelope, final MslEncoderFactory encoder) throws MslCryptoException, MslEncodingException {
// Attempt to convert this to a MSL object.
MslObject envelopeMo;
try {
// If this is a MSL object, we expect the byte representation to be
// decodable.
envelopeMo = encoder.parseObject(envelope);
} catch (final MslEncoderException e) {
envelopeMo = null;
}
// Determine the envelope version.
//
// If there is no MSL object, or there is no version field (as the
// binary signature may coincidentally parse into a MSL object), then
// this is a version 1 envelope.
Version version;
if (envelopeMo == null || !envelopeMo.has(KEY_VERSION)) {
version = Version.V1;
} else {
try {
version = Version.valueOf(envelopeMo.getInt(KEY_VERSION));
} catch (final MslEncoderException e) {
// There is a possibility that this is a version 1 envelope.
version = Version.V1;
} catch (final IllegalArgumentException e) {
// There is a possibility that this is a version 1 envelope.
version = Version.V1;
}
}
// Parse envelope.
switch (version) {
case V1:
return new MslSignatureEnvelope(envelope);
case V2:
try {
final SignatureAlgo algorithm = SignatureAlgo.fromString(envelopeMo.getString(KEY_ALGORITHM));
final byte[] signature = envelopeMo.getBytes(KEY_SIGNATURE);
return new MslSignatureEnvelope(algorithm, signature);
} catch (final MslEncoderException e) {
// It is extremely unlikely but possible that this is a
// version 1 envelope.
return new MslSignatureEnvelope(envelope);
} catch (final IllegalArgumentException e) {
// It is extremely unlikely but possible that this is a
// version 1 envelope.
return new MslSignatureEnvelope(envelope);
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_SIGNATURE_ENVELOPE, "signature envelope " + Base64.encode(envelope));
}
}
/**
* @return the signature algorithm. May be null.
*/
public SignatureAlgo getAlgorithm() {
return algorithm;
}
/**
* @return the signature.
*/
public byte[] getSignature() {
return signature;
}
/** Envelope version. */
private final Version version;
/** Algorithm. */
private final SignatureAlgo algorithm;
/** Signature. */
private final byte[] signature;
/**
* Returns the signature envelope in byte form.
*
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the byte representation of the signature envelope.
* @throws MslEncoderException if there is an error encoding the envelope.
* @throws MslInternalException if the envelope version is not supported.
*/
public byte[] getBytes(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
switch (version) {
case V1:
return signature;
case V2:
final MslObject mo = encoder.createObject();
mo.put(KEY_VERSION, version.intValue());
mo.put(KEY_ALGORITHM, algorithm.name());
mo.put(KEY_SIGNATURE, signature);
return encoder.encodeObject(mo, format);
default:
throw new MslInternalException("Signature envelope version " + version + " encoding unsupported.");
}
}
}
| 9,830 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/MslCiphertextEnvelope.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import com.netflix.msl.MslConstants.CipherSpec;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslEncodable;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.Base64;
/**
* MSL ciphertext envelopes contain all of the information necessary for
* decrypting ciphertext using a known key.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslCiphertextEnvelope implements MslEncodable {
/** Key version. */
private final static String KEY_VERSION = "version";
/** Key key ID. */
private final static String KEY_KEY_ID = "keyid";
/** Key cipherspec. */
private final static String KEY_CIPHERSPEC = "cipherspec";
/** Key initialization vector. */
private final static String KEY_IV = "iv";
/** Key ciphertext. */
private final static String KEY_CIPHERTEXT = "ciphertext";
/** Key SHA-256. */
private final static String KEY_SHA256 = "sha256";
/** Versions. */
public static enum Version {
/**
* <p>Version 1.</p>
*
* {@code {
* "#mandatory" : [ "keyid", "iv", "ciphertext", "sha256" ],
* "keyid" : "string",
* "iv" : "binary",
* "ciphertext" : "binary",
* "sha256" : "binary",
* }} where:
* <ul>
* <li>{@code keyid} is the encryption key ID</li>
* <li>{@code iv} is the initialization vector</li>
* <li>{@code ciphertext} is the ciphertext</li>
* <li>{@code sha256} is the SHA-256 of the encryption envelope</li>
* </ul>
*
* <p>The SHA-256 is computed over the concatenation of {@code key ID ||
* IV || ciphertext}.</p>
*/
V1,
/**
* <p>Version 2.</p>
*
* {@code {
* "#mandatory" : [ "version", "cipherspec", "ciphertext" ],
* "version" : "number",
* "cipherspec" : "string",
* "iv" : "binary",
* "ciphertext" : "binary",
* }} where:
* <ul>
* <li>{@code version} is the number '2'</li>
* <li>{@code cipherspec} is one of the recognized cipher specifications</li>
* <li>{@code iv} is the optional initialization vector</li>
* <li>{@code ciphertext} is the ciphertext</li>
* </ul>
*
* <p>Supported cipher specifications:
* <table>
* <tr><th>Cipher Spec</th><th>Description</th></tr>
* <tr><td>AES/CBC/PKCS5Padding</td><td>AES CBC w/PKCS#5 Padding</td></tr>
* </table></p>
*/
V2;
/**
* @param version the integer value of this version.
* @return the version identified by the integer value.
* @throws IllegalArgumentException if the version is unknown.
*/
public static Version valueOf(final int version) {
switch (version) {
case 1: return V1;
case 2: return V2;
default: throw new IllegalArgumentException("Unknown ciphertext envelope version " + version + ".");
}
}
/**
* @return the integer value of this version.
*/
public int intValue() {
switch (this) {
case V1: return 1;
case V2: return 2;
default: throw new MslInternalException("No integer value defined for version " + this + ".");
}
}
}
/**
* Determines the envelope version of the given MSL object.
*
* @param mo the MSL object.
* @return the envelope version.
* @throws MslCryptoException if the envelope version is not recognized.
*/
private static Version getVersion(final MslObject mo) throws MslCryptoException {
try {
final int v = mo.getInt(KEY_VERSION);
return Version.valueOf(v);
} catch (final MslEncoderException e) {
// If anything fails to parse, treat this as a version 1 envelope.
return Version.V1;
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_CIPHERTEXT_ENVELOPE, "ciphertext envelope " + mo, e);
}
}
/**
* Create a new version 1 ciphertext envelope with the provided data.
*
* @param keyId the key identifier.
* @param iv the initialization vector. May be null.
* @param ciphertext the ciphertext.
*/
public MslCiphertextEnvelope(final String keyId, final byte[] iv, final byte[] ciphertext) {
this.version = Version.V1;
this.keyId = keyId;
this.cipherSpec = null;
this.iv = iv;
this.ciphertext = ciphertext;
}
/**
* Create a new version 2 ciphertext envelope with the provided data.
*
* @param cipherSpec the cipher specification.
* @param iv the initialization vector. May be null.
* @param ciphertext the ciphertext.
*/
public MslCiphertextEnvelope(final CipherSpec cipherSpec, final byte[] iv, final byte[] ciphertext) {
this.version = Version.V2;
this.keyId = null;
this.cipherSpec = cipherSpec;
this.iv = iv;
this.ciphertext = ciphertext;
}
/**
* Create a new encryption envelope from the provided MSL object.
*
* @param mo the MSL object.
* @throws MslCryptoException if there is an error processing the
* encryption envelope.
* @throws MslEncodingException if there is an error parsing the data.
*/
public MslCiphertextEnvelope(final MslObject mo) throws MslCryptoException, MslEncodingException {
this(mo, getVersion(mo));
}
/**
* Create a new encryption envelope of the specified version from the
* provided MSL object.
*
* @param mo the MSL object.
* @param version the envelope version.
* @throws MslCryptoException if there is an error processing the
* encryption envelope.
* @throws MslEncodingException if there is an error parsing the data.
*/
public MslCiphertextEnvelope(final MslObject mo, final Version version) throws MslCryptoException, MslEncodingException {
// Parse envelope.
switch (version) {
case V1:
try {
this.version = Version.V1;
this.keyId = mo.getString(KEY_KEY_ID);
this.cipherSpec = null;
this.iv = (mo.has(KEY_IV)) ? mo.getBytes(KEY_IV) : null;
this.ciphertext = mo.getBytes(KEY_CIPHERTEXT);
mo.getBytes(KEY_SHA256);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "ciphertext envelope " + mo, e);
}
break;
case V2:
try {
final int v = mo.getInt(KEY_VERSION);
this.version = Version.valueOf(v);
if (!Version.V2.equals(this.version))
throw new MslCryptoException(MslError.UNIDENTIFIED_CIPHERTEXT_ENVELOPE, "ciphertext envelope " + mo.toString());
this.keyId = null;
try {
this.cipherSpec = CipherSpec.fromString(mo.getString(KEY_CIPHERSPEC));
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_CIPHERSPEC, "ciphertext envelope " + mo, e);
}
this.iv = (mo.has(KEY_IV)) ? mo.getBytes(KEY_IV) : null;
this.ciphertext = mo.getBytes(KEY_CIPHERTEXT);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "ciphertext envelope " + mo, e);
}
break;
default:
throw new MslCryptoException(MslError.UNSUPPORTED_CIPHERTEXT_ENVELOPE, "ciphertext envelope version " + version);
}
}
/**
* @return the encryption key ID. May be null.
*/
public String getKeyId() {
return keyId;
}
/**
* @return the ciphser specification. May be null.
*/
public CipherSpec getCipherSpec() {
return cipherSpec;
}
/**
* @return the initialization vector. May be null.
*/
public byte[] getIv() {
return iv;
}
/**
* @return the ciphertext.
*/
public byte[] getCiphertext() {
return ciphertext;
}
/** Envelope version. */
private final Version version;
/** Key identifier. */
private final String keyId;
/** Cipher specification. */
private CipherSpec cipherSpec;
/** Optional initialization vector. */
private final byte[] iv;
/** Ciphertext. */
private final byte[] ciphertext;
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
switch (version) {
case V1:
mo.put(KEY_KEY_ID, keyId);
if (iv != null) mo.put(KEY_IV, iv);
mo.put(KEY_CIPHERTEXT, ciphertext);
mo.put(KEY_SHA256, Base64.decode("AA=="));
break;
case V2:
mo.put(KEY_VERSION, version.intValue());
mo.put(KEY_CIPHERSPEC, cipherSpec.toString());
if (iv != null) mo.put(KEY_IV, iv);
mo.put(KEY_CIPHERTEXT, ciphertext);
break;
default:
throw new MslEncoderException("Ciphertext envelope version " + version + " encoding unsupported.");
}
return encoder.encodeObject(mo, format);
}
}
| 9,831 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/JcaAlgorithm.java | /**
* Copyright (c) 2013 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
/**
* <p>JCE standard algorithm name constants.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class JcaAlgorithm {
/** AES. */
public static final String AES = "AES";
/** HMAC-SHA256. */
public static final String HMAC_SHA256 = "HmacSHA256";
/** AES key wrap. */
public static final String AESKW = "AES";
/** CMAC. */
public static final String AES_CMAC = "AESCmac";
}
| 9,832 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/JsonWebKey.java | /**
* Copyright (c) 2013-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslArray;
import com.netflix.msl.io.MslEncodable;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslEncoderUtils;
import com.netflix.msl.io.MslObject;
/**
* This class implements the JSON web key structure as defined in
* <a href="http://tools.ietf.org/html/draft-ietf-mose-json-web-key-08">JSON Web Key</a>.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class JsonWebKey implements MslEncodable {
/** JSON key key type. */
private static final String KEY_TYPE = "kty";
/** JSON key usage. */
private static final String KEY_USAGE = "use";
/** JSON key key operations. */
private static final String KEY_KEY_OPS = "key_ops";
/** JSON key algorithm. */
private static final String KEY_ALGORITHM = "alg";
/** JSON key extractable. */
private static final String KEY_EXTRACTABLE = "extractable";
/** JSON key key ID. */
private static final String KEY_KEY_ID = "kid";
// RSA keys.
/** JSON key modulus. */
private static final String KEY_MODULUS = "n";
/** JSON key public exponent. */
private static final String KEY_PUBLIC_EXPONENT = "e";
/** JSON key private exponent. */
private static final String KEY_PRIVATE_EXPONENT = "d";
// Symmetric keys.
/** JSON key key. */
private static final String KEY_KEY = "k";
/** Supported key types. */
public static enum Type {
/** RSA */
rsa,
/** Octet Sequence */
oct,
}
/** Supported key usages. */
public static enum Usage {
/** Sign/verify. */
sig,
/** Encrypt/decrypt. */
enc,
/** Wrap/unwrap. */
wrap,
}
/** Supported key operations. */
public static enum KeyOp {
sign,
verify,
encrypt,
decrypt,
wrapKey,
unwrapKey,
deriveKey,
deriveBits
}
/** Supported key algorithms. */
public static enum Algorithm {
/** HMAC-SHA256 */
HS256("HS256"),
/** RSA PKCS#1 v1.5 */
RSA1_5("RSA1_5"),
/** RSA OAEP */
RSA_OAEP("RSA-OAEP"),
/** AES-128 Key Wrap */
A128KW("A128KW"),
/** AES-128 CBC */
A128CBC("A128CBC");
/**
* @param name JSON Web Algorithm name.
*/
private Algorithm(final String name) {
this.name = name;
}
/**
* @return the Java Cryptography Architecture standard algorithm name
* for this JSON Web Algorithm.
*/
public String getJcaAlgorithmName() {
switch (this) {
case HS256:
return "HmacSHA256";
case RSA1_5:
case RSA_OAEP:
return "RSA";
case A128KW:
case A128CBC:
return "AES";
default:
throw new MslInternalException("No JCA standard algorithm name defined for " + this + ".");
}
}
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return name;
}
/**
* @param name JSON Web Algorithm name.
* @return the algorithm.
* @throws IllegalArgumentException if the algorithm name is unknown.
*/
public static Algorithm fromString(final String name) {
for (final Algorithm algo : values()) {
if (algo.toString().equals(name))
return algo;
}
throw new IllegalArgumentException("Algorithm " + name + " is unknown.");
}
/** JSON Web Algorithm name. */
private final String name;
}
/**
* Returns the big integer in big-endian format without any leading sign
* bits.
*
* @param bi the big integer.
* @return the big integer in big-endian form.
*/
private static byte[] bi2bytes(final BigInteger bi) {
final byte[] bib = bi.toByteArray();
final int len = (int)Math.ceil((double)bi.bitLength() / Byte.SIZE);
return Arrays.copyOfRange(bib, bib.length - len, bib.length);
}
/**
* Create a new JSON web key for an RSA public/private key pair with the
* specified attributes. At least one of the public key or private key must
* be encoded.
*
* @param usage key usage. May be null.
* @param algo key algorithm. May be null.
* @param extractable true if the key is extractable.
* @param id key ID. May be null.
* @param publicKey RSA public key. May be null.
* @param privateKey RSA private key. May be null.
* @throws MslInternalException if both keys are null or the algorithm
* is incompatible.
*/
public JsonWebKey(final Usage usage, final Algorithm algo, final boolean extractable, final String id, final RSAPublicKey publicKey, final RSAPrivateKey privateKey) {
if (publicKey == null && privateKey == null)
throw new MslInternalException("At least one of the public key or private key must be provided.");
if (algo != null) {
switch (algo) {
case RSA1_5:
case RSA_OAEP:
break;
default:
throw new MslInternalException("The algorithm must be an RSA algorithm.");
}
}
this.type = Type.rsa;
this.usage = usage;
this.keyOps = null;
this.algo = algo;
this.extractable = extractable;
this.id = id;
this.keyPair = new KeyPair(publicKey, privateKey);
this.key = null;
this.secretKey = null;
}
/**
* Create a new JSON web key for a symmetric key with the specified
* attributes.
*
* @param usage key usage. May be null.
* @param algo key algorithm. May be null.
* @param extractable true if the key is extractable.
* @param id key ID. May be null.
* @param secretKey symmetric key.
* @throws MslInternalException if the usage or algorithm is incompatible.
*/
public JsonWebKey(final Usage usage, final Algorithm algo, final boolean extractable, final String id, final SecretKey secretKey) {
if (algo != null) {
switch (algo) {
case HS256:
case A128KW:
case A128CBC:
break;
default:
throw new MslInternalException("The algorithm must be a symmetric key algorithm.");
}
}
this.type = Type.oct;
this.usage = usage;
this.keyOps = null;
this.algo = algo;
this.extractable = extractable;
this.id = id;
this.keyPair = null;
this.key = secretKey.getEncoded();
this.secretKey = secretKey;
}
/**
* Create a new JSON web key for an RSA public/private key pair with the
* specified attributes. At least one of the public key or private key must
* be encoded.
*
* @param keyOps key operations. May be null.
* @param algo key algorithm. May be null.
* @param extractable true if the key is extractable.
* @param id key ID. May be null.
* @param publicKey RSA public key. May be null.
* @param privateKey RSA private key. May be null.
* @throws MslInternalException if both keys are null or the algorithm
* is incompatible.
*/
public JsonWebKey(final Set<KeyOp> keyOps, final Algorithm algo, final boolean extractable, final String id, final RSAPublicKey publicKey, final RSAPrivateKey privateKey) {
if (publicKey == null && privateKey == null)
throw new MslInternalException("At least one of the public key or private key must be provided.");
if (algo != null) {
switch (algo) {
case RSA1_5:
case RSA_OAEP:
break;
default:
throw new MslInternalException("The algorithm must be an RSA algorithm.");
}
}
this.type = Type.rsa;
this.usage = null;
this.keyOps = (keyOps != null) ? Collections.unmodifiableSet(keyOps) : null;
this.algo = algo;
this.extractable = extractable;
this.id = id;
this.keyPair = new KeyPair(publicKey, privateKey);
this.key = null;
this.secretKey = null;
}
/**
* Create a new JSON web key for a symmetric key with the specified
* attributes.
*
* @param keyOps key operations. May be null.
* @param algo key algorithm. May be null.
* @param extractable true if the key is extractable.
* @param id key ID. May be null.
* @param secretKey symmetric key.
* @throws MslInternalException if the usage or algorithm is incompatible.
*/
public JsonWebKey(final Set<KeyOp> keyOps, final Algorithm algo, final boolean extractable, final String id, final SecretKey secretKey) {
if (algo != null) {
switch (algo) {
case HS256:
case A128KW:
case A128CBC:
break;
default:
throw new MslInternalException("The algorithm must be a symmetric key algorithm.");
}
}
this.type = Type.oct;
this.usage = null;
this.keyOps = (keyOps != null) ? Collections.unmodifiableSet(keyOps) : null;
this.algo = algo;
this.extractable = extractable;
this.id = id;
this.keyPair = null;
this.key = secretKey.getEncoded();
this.secretKey = secretKey;
}
/**
* Create a new JSON web key from the provided MSL object.
*
* @param jsonMo JSON web key MSL object.
* @throws MslCryptoException if the key type is unknown.
* @throws MslEncodingException if there is an error parsing the data.
*/
public JsonWebKey(final MslObject jsonMo) throws MslCryptoException, MslEncodingException {
// Parse JSON object.
final String typeName, usageName, algoName;
final Set<String> keyOpsNames;
try {
typeName = jsonMo.getString(KEY_TYPE);
usageName = jsonMo.has(KEY_USAGE) ? jsonMo.getString(KEY_USAGE) : null;
if (jsonMo.has(KEY_KEY_OPS)) {
keyOpsNames = new HashSet<String>();
final MslArray ma = jsonMo.getMslArray(KEY_KEY_OPS);
for (int i = 0; i < ma.size(); ++i)
keyOpsNames.add(ma.getString(i));
} else {
keyOpsNames = null;
}
algoName = jsonMo.has(KEY_ALGORITHM) ? jsonMo.getString(KEY_ALGORITHM) : null;
extractable = jsonMo.has(KEY_EXTRACTABLE) ? jsonMo.getBoolean(KEY_EXTRACTABLE) : false;
id = jsonMo.has(KEY_KEY_ID) ? jsonMo.getString(KEY_KEY_ID) : null;
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "jwk " + jsonMo, e);
}
// Set values.
try {
type = Type.valueOf(typeName);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_JWK_TYPE, typeName, e);
}
try {
usage = (usageName != null) ? Usage.valueOf(usageName) : null;
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_JWK_USAGE, usageName, e);
}
if (keyOpsNames != null) {
final Set<KeyOp> keyOps = EnumSet.noneOf(KeyOp.class);
for (final String keyOpName : keyOpsNames) {
try {
keyOps.add(KeyOp.valueOf(keyOpName));
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_JWK_KEYOP, usageName, e);
}
}
this.keyOps = Collections.unmodifiableSet(keyOps);
} else {
this.keyOps = null;
}
try {
algo = (algoName != null) ? Algorithm.fromString(algoName) : null;
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.UNIDENTIFIED_JWK_ALGORITHM, algoName, e);
}
// Reconstruct keys.
try {
// Handle symmetric keys.
if (type == Type.oct) {
key = MslEncoderUtils.b64urlDecode(jsonMo.getString(KEY_KEY));
if (key == null || key.length == 0)
throw new MslCryptoException(MslError.INVALID_JWK_KEYDATA, "symmetric key is empty");
secretKey = (algo != null) ? new SecretKeySpec(key, algo.getJcaAlgorithmName()) : null;
keyPair = null;
}
// Handle public/private keys (RSA only).
else {
key = null;
final KeyFactory factory = CryptoCache.getKeyFactory("RSA");
// Grab the modulus.
final byte[] n = MslEncoderUtils.b64urlDecode(jsonMo.getString(KEY_MODULUS));
if (n == null || n.length == 0)
throw new MslCryptoException(MslError.INVALID_JWK_KEYDATA, "modulus is empty");
final BigInteger modulus = new BigInteger(1, n);
// Reconstruct the public key if it exists.
final PublicKey publicKey;
if (jsonMo.has(KEY_PUBLIC_EXPONENT)) {
final byte[] e = MslEncoderUtils.b64urlDecode(jsonMo.getString(KEY_PUBLIC_EXPONENT));
if (e == null || e.length == 0)
throw new MslCryptoException(MslError.INVALID_JWK_KEYDATA, "public exponent is empty");
final BigInteger exponent = new BigInteger(1, e);
final KeySpec pubkeySpec = new RSAPublicKeySpec(modulus, exponent);
publicKey = factory.generatePublic(pubkeySpec);
} else {
publicKey = null;
}
// Reconstruct the private key if it exists.
final PrivateKey privateKey;
if (jsonMo.has(KEY_PRIVATE_EXPONENT)) {
final byte[] d = MslEncoderUtils.b64urlDecode(jsonMo.getString(KEY_PRIVATE_EXPONENT));
if (d == null || d.length == 0)
throw new MslCryptoException(MslError.INVALID_JWK_KEYDATA, "private exponent is empty");
final BigInteger exponent = new BigInteger(1, d);
final KeySpec privkeySpec = new RSAPrivateKeySpec(modulus, exponent);
privateKey = factory.generatePrivate(privkeySpec);
} else {
privateKey = null;
}
// Make sure there is at least one key.
if (publicKey == null && privateKey == null)
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "no public or private key");
keyPair = new KeyPair(publicKey, privateKey);
secretKey = null;
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, e);
} catch (final NoSuchAlgorithmException e) {
throw new MslCryptoException(MslError.UNSUPPORTED_JWK_ALGORITHM, e);
} catch (final InvalidKeySpecException e) {
throw new MslCryptoException(MslError.INVALID_JWK_KEYDATA, e);
}
}
/**
* @return the key type.
*/
public Type getType() {
return type;
}
/**
* @return the permitted key usage or null if not specified.
*/
public Usage getUsage() {
return usage;
}
/**
* @return the permitted key operations or null if not specified.
*/
public Set<KeyOp> getKeyOps() {
return keyOps;
}
/**
* @return the key algorithm or null if not specified.
*/
public Algorithm getAlgorithm() {
return algo;
}
/**
* @return true if the key is allowed to be extracted.
*/
public boolean isExtractable() {
return extractable;
}
/**
* @return the key ID or null if not specified.
*/
public String getId() {
return id;
}
/**
* Returns the stored RSA key pair if the JSON web key type is RSA. The
* public or private key may be null if only one of the pair is stored in
* this JSON web key.
*
* @return the stored RSA key pair or null if the type is not RSA.
*/
public KeyPair getRsaKeyPair() {
return keyPair;
}
/**
* Returns the stored symmetric key if the JSON web key type is OCT and an
* algorithm was specified. Because Java {@code SecretKey} requires a known
* algorithm when it is constructed, the key material may be present when
* this method returns {@code null}.
*
* @return the stored symmetric key or null if the type is not OCT or no
* algorithm was specified.
* @see #getSecretKey(String)
*/
public SecretKey getSecretKey() {
return secretKey;
}
/**
* Returns the stored symmetric key if the JSON web key type is OCT. The
* returned key algorithm will be the one specified by the JSON web key
* algorithm. If no JSON web key algorithm was specified the provided
* algorithm will be used instead.
*
* @param algorithm the symmetric key algorithm to use if one was not
* specified in the JSON web key.
* @return the stored symmetric key or null if the type is not OCT.
* @throws MslCryptoException if the key cannot be constructed.
* @see #getSecretKey()
*/
public SecretKey getSecretKey(final String algorithm) throws MslCryptoException {
// Return the stored symmetric key if it already exists.
if (secretKey != null)
return secretKey;
// Otherwise construct the secret key.
if (key == null)
return null;
try {
return new SecretKeySpec(key, algorithm);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) {
try {
final MslObject mo = encoder.createObject();
// Encode key attributes.
mo.put(KEY_TYPE, type.name());
if (usage != null) mo.put(KEY_USAGE, usage.name());
if (keyOps != null) {
final MslArray keyOpsMa = encoder.createArray();
for (final KeyOp op : keyOps)
keyOpsMa.put(-1, op.name());
mo.put(KEY_KEY_OPS, keyOpsMa);
}
if (algo != null) mo.put(KEY_ALGORITHM, algo.toString());
mo.put(KEY_EXTRACTABLE, extractable);
if (id != null) mo.put(KEY_KEY_ID, id);
// Encode symmetric keys.
if (type == Type.oct) {
mo.put(KEY_KEY, MslEncoderUtils.b64urlEncode(key));
}
// Encode public/private keys (RSA only).
else {
final RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
final RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
// Encode modulus.
final BigInteger modulus = (publicKey != null) ? publicKey.getModulus() : privateKey.getModulus();
final byte[] n = bi2bytes(modulus);
mo.put(KEY_MODULUS, MslEncoderUtils.b64urlEncode(n));
// Encode public key.
if (publicKey != null) {
final BigInteger exponent = publicKey.getPublicExponent();
final byte[] e = bi2bytes(exponent);
mo.put(KEY_PUBLIC_EXPONENT, MslEncoderUtils.b64urlEncode(e));
}
// Encode private key.
if (privateKey != null) {
final BigInteger exponent = privateKey.getPrivateExponent();
final byte[] d = bi2bytes(exponent);
mo.put(KEY_PRIVATE_EXPONENT, MslEncoderUtils.b64urlEncode(d));
}
}
// Return the result.
//
// We will always encode as JSON.
return encoder.encodeObject(mo, MslEncoderFormat.JSON);
} catch (final MslEncoderException e) {
throw new MslInternalException("Error encoding " + this.getClass().getName() + ".", e);
}
}
/** Key type. */
private final Type type;
/** Key usages. */
private final Usage usage;
/** Key operations. */
private final Set<KeyOp> keyOps;
/** Key algorithm. */
private final Algorithm algo;
/** Extractable. */
private final boolean extractable;
/** Key ID. */
private final String id;
/** RSA key pair. May be null. */
private final KeyPair keyPair;
/** Symmetric key raw bytes. May be null. */
private final byte[] key;
/** Symmetric key. May be null. */
private final SecretKey secretKey;
}
| 9,833 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/crypto/SymmetricCryptoContext.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.crypto;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.macs.CMac;
import org.bouncycastle.crypto.params.KeyParameter;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslUtils;
/**
* A symmetric crypto context performs AES-128 encryption/decryption, AES-128
* key wrap/unwrap, and HMAC-SHA256 or AES-CMAC sign/verify.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class SymmetricCryptoContext extends ICryptoContext {
/** AES encryption cipher algorithm. */
private static final String AES_ALGO = "AES";
/** AES encryption cipher algorithm. */
private static final String AES_TRANSFORM = AES_ALGO + "/CBC/PKCS5Padding";
/** AES encryption initial value size in bytes. */
private static final int AES_IV_SIZE = 16;
/** HMAC SHA-256 algorithm. */
private static final String HMAC_SHA256_ALGO = "HmacSHA256";
/** AES key wrap cipher algorithm. */
private static final String AESKW_ALGO = "AES";
/** AES key wrap cipher transform. */
private static final String AESKW_TRANSFORM = AESKW_ALGO + "/ECB/NoPadding";
/** AES key wrap block size in bytes. */
private static final int AESKW_BLOCK_SIZE = 8;
/** Key wrap initial value. */
private static final byte[] AESKW_AIV = { (byte)0xA6, (byte)0xA6, (byte)0xA6, (byte)0xA6, (byte)0xA6, (byte)0xA6, (byte)0xA6, (byte)0xA6 };
/**
* @param bytes number of bytes to return.
* @param w the value.
* @return the specified number of most significant (big-endian) bytes of
* the value.
*/
private static byte[] msb(final int bytes, final byte[] w) {
final byte[] msb = new byte[bytes];
System.arraycopy(w, 0, msb, 0, bytes);
return msb;
}
/**
* @param bytes number of bytes to return.
* @param w the value.
* @return the specified number of least significant (big-endian) bytes of
* the value.
*/
private static byte[] lsb(final int bytes, final byte[] w) {
final int offset = w.length - bytes;
final byte[] lsb = new byte[bytes];
for (int i = 0; i < bytes; ++i)
lsb[i] = w[offset + i];
return lsb;
}
/**
* Modifies the provided byte array by XOR'ing it with the provided value.
* The byte array is processed in big-endian order.
*
* @param b 8-byte value that will be modified.
* @param t the 64-bit value to XOR the value with.
*/
private static void xor(final byte[] b, final long t) {
b[0] ^= t >>> 56;
b[1] ^= t >>> 48;
b[2] ^= t >>> 40;
b[3] ^= t >>> 32;
b[4] ^= t >>> 24;
b[5] ^= t >>> 16;
b[6] ^= t >>> 8;
b[7] ^= t;
}
/**
* <p>Create a new symmetric crypto context using the provided keys.</p>
*
* <p>If there is no encryption key, encryption and decryption is
* unsupported.</p>
*
* <p>If there is no signature key, signing and verification is
* unsupported.</p>
*
* <p>If there is no wrapping key, wrap and unwrap is unsupported.</p>
*
* @param ctx MSL context.
* @param id the key set identity.
* @param encryptionKey the key used for encryption/decryption.
* @param signatureKey the key used for HMAC or CMAC computation.
* @param wrappingKey the key used for wrap/unwrap. */
public SymmetricCryptoContext(final MslContext ctx, final String id, final SecretKey encryptionKey, final SecretKey signatureKey, final SecretKey wrappingKey) {
if (encryptionKey != null && !encryptionKey.getAlgorithm().equals(JcaAlgorithm.AES))
throw new IllegalArgumentException("Encryption key must be an " + JcaAlgorithm.AES + " key.");
if (signatureKey != null &&
!signatureKey.getAlgorithm().equals(JcaAlgorithm.HMAC_SHA256) &&
!signatureKey.getAlgorithm().equals(JcaAlgorithm.AES_CMAC))
{
throw new IllegalArgumentException("Encryption key must be an " + JcaAlgorithm.HMAC_SHA256 + " or " + JcaAlgorithm.AES_CMAC + " key.");
}
if (wrappingKey != null && !wrappingKey.getAlgorithm().equals(JcaAlgorithm.AESKW))
throw new IllegalArgumentException("Encryption key must be an " + JcaAlgorithm.AESKW + " key.");
this.ctx = ctx;
this.id = id;
this.encryptionKey = encryptionKey;
this.signatureKey = signatureKey;
this.wrappingKey = wrappingKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (encryptionKey == null)
throw new MslCryptoException(MslError.ENCRYPT_NOT_SUPPORTED, "no encryption/decryption key");
try {
// Generate IV.
final Random random = ctx.getRandom();
final byte[] iv = new byte[AES_IV_SIZE];
random.nextBytes(iv);
// Encrypt plaintext.
final byte[] ciphertext;
if (data.length != 0) {
final Cipher cipher = CryptoCache.getCipher(AES_TRANSFORM);
final AlgorithmParameterSpec params = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, params);
ciphertext = cipher.doFinal(data);
} else {
ciphertext = new byte[0];
}
// Return encryption envelope byte representation.
final MslCiphertextEnvelope envelope = new MslCiphertextEnvelope(id, iv, ciphertext);
return envelope.toMslEncoding(encoder, format);
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_ENCRYPTION_KEY, e);
} catch (final InvalidAlgorithmParameterException e) {
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
} catch (final BadPaddingException e) {
throw new MslCryptoException(MslError.PLAINTEXT_BAD_PADDING, "not expected when encrypting", e);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_ENCODE_ERROR, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
if (encryptionKey == null)
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED, "no encryption/decryption key");
try {
// Reconstitute encryption envelope.
final MslObject encryptionEnvelopeMo = encoder.parseObject(data);
final MslCiphertextEnvelope encryptionEnvelope = new MslCiphertextEnvelope(encryptionEnvelopeMo, MslCiphertextEnvelope.Version.V1);
// Decrypt ciphertext.
final byte[] ciphertext = encryptionEnvelope.getCiphertext();
if (ciphertext.length == 0)
return new byte[0];
final byte[] iv = encryptionEnvelope.getIv();
final Cipher cipher = CryptoCache.getCipher(AES_TRANSFORM);
final AlgorithmParameterSpec params = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, encryptionKey, params);
return cipher.doFinal(ciphertext);
} catch (final ArrayIndexOutOfBoundsException e) {
throw new MslCryptoException(MslError.INSUFFICIENT_CIPHERTEXT, e);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR, e);
} catch (final MslEncodingException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_ENVELOPE_PARSE_ERROR, e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_ENCRYPTION_KEY, e);
} catch (final InvalidAlgorithmParameterException e) {
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, e);
} catch (final BadPaddingException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_BAD_PADDING, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (wrappingKey == null)
throw new MslCryptoException(MslError.WRAP_NOT_SUPPORTED, "no wrap/unwrap key");
if (data.length % 8 != 0)
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "data.length " + data.length);
// Compute alternate initial value.
byte[] a = AESKW_AIV.clone();
final byte[] r = data.clone();
try {
final Cipher cipher = CryptoCache.getCipher(AESKW_TRANSFORM);
cipher.init(Cipher.ENCRYPT_MODE, wrappingKey);
// Initialize variables.
final int n = r.length / AESKW_BLOCK_SIZE;
// Calculate intermediate values.
for (int j = 0; j < 6; ++j) {
for (int i = 1; i <= n; ++i) {
byte[] r_i = Arrays.copyOfRange(r, (i - 1) * AESKW_BLOCK_SIZE, i * AESKW_BLOCK_SIZE);
final byte[] ar_i = Arrays.copyOf(a, a.length + r_i.length);
System.arraycopy(r_i, 0, ar_i, a.length, r_i.length);
final byte[] b = cipher.doFinal(ar_i);
a = msb(AESKW_BLOCK_SIZE, b);
final long t = (n * j) + i;
xor(a, t);
r_i = lsb(AESKW_BLOCK_SIZE, b);
System.arraycopy(r_i, 0, r, (i - 1) * AESKW_BLOCK_SIZE, AESKW_BLOCK_SIZE);
}
}
// Output results.
final byte[] c = new byte[a.length + r.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(r, 0, c, a.length, r.length);
return c;
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_WRAPPING_KEY, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is no padding", e);
} catch (final BadPaddingException e) {
throw new MslCryptoException(MslError.PLAINTEXT_BAD_PADDING, "not expected when encrypting", e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
if (wrappingKey == null)
throw new MslCryptoException(MslError.UNWRAP_NOT_SUPPORTED, "no wrap/unwrap key");
if (data.length % 8 != 0)
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, "data.length " + data.length);
try {
final Cipher cipher = CryptoCache.getCipher(AESKW_TRANSFORM);
cipher.init(Cipher.DECRYPT_MODE, wrappingKey);
byte[] a = Arrays.copyOf(data, AESKW_BLOCK_SIZE);
final byte[] r = Arrays.copyOfRange(data, a.length, data.length);
final int n = (data.length - AESKW_BLOCK_SIZE) / AESKW_BLOCK_SIZE;
// Calculate intermediate values.
for (int j = 5; j >= 0; --j) {
for (int i = n; i >= 1; --i) {
final long t = (n * j) + i;
xor(a, t);
byte[] r_i = Arrays.copyOfRange(r, (i - 1) * AESKW_BLOCK_SIZE, i * AESKW_BLOCK_SIZE);
final byte[] ar_i = Arrays.copyOf(a, a.length + r_i.length);
System.arraycopy(r_i, 0, ar_i, a.length, r_i.length);
final byte[] b = cipher.doFinal(ar_i);
a = msb(AESKW_BLOCK_SIZE, b);
r_i = lsb(AESKW_BLOCK_SIZE, b);
System.arraycopy(r_i, 0, r, (i - 1) * AESKW_BLOCK_SIZE, AESKW_BLOCK_SIZE);
}
}
// Output results.
if (MslUtils.safeEquals(a, AESKW_AIV) && r.length % AESKW_BLOCK_SIZE == 0)
return r;
throw new MslCryptoException(MslError.UNWRAP_ERROR, "initial value " + Arrays.toString(a));
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_WRAPPING_KEY, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, e);
} catch (final BadPaddingException e) {
throw new MslCryptoException(MslError.CIPHERTEXT_BAD_PADDING, e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (signatureKey == null)
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED, "No signature key.");
try {
// Compute the xMac.
final byte[] xmac;
if (signatureKey.getAlgorithm().equals(JcaAlgorithm.HMAC_SHA256)) {
final Mac mac = CryptoCache.getMac(HMAC_SHA256_ALGO);
mac.init(signatureKey);
xmac = mac.doFinal(data);
} else if (signatureKey.getAlgorithm().equals(JcaAlgorithm.AES_CMAC)) {
final CipherParameters params = new KeyParameter(signatureKey.getEncoded());
final BlockCipher aes = new AESEngine();
final CMac mac = new CMac(aes);
mac.init(params);
mac.update(data, 0, data.length);
xmac = new byte[mac.getMacSize()];
mac.doFinal(xmac, 0);
} else {
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED, "Unsupported algorithm.");
}
// Return the signature envelope byte representation.
return new MslSignatureEnvelope(xmac).getBytes(encoder, format);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid MAC algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_HMAC_KEY, e);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.SIGNATURE_ENVELOPE_ENCODE_ERROR, e);
}
}
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
if (signatureKey == null)
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED, "No signature key.");
try {
// Reconstitute the signature envelope.
final MslSignatureEnvelope envelope = MslSignatureEnvelope.parse(signature, encoder);
// Compute the xMac.
final byte[] xmac;
if (signatureKey.getAlgorithm().equals(JcaAlgorithm.HMAC_SHA256)) {
final Mac mac = CryptoCache.getMac(HMAC_SHA256_ALGO);
mac.init(signatureKey);
xmac = mac.doFinal(data);
} else if (signatureKey.getAlgorithm().equals(JcaAlgorithm.AES_CMAC)) {
final CipherParameters params = new KeyParameter(signatureKey.getEncoded());
final BlockCipher aes = new AESEngine();
final CMac mac = new CMac(aes);
mac.init(params);
mac.update(data, 0, data.length);
xmac = new byte[mac.getMacSize()];
mac.doFinal(xmac, 0);
} else {
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED, "Unsupported algorithm.");
}
// Compare the computed hash to the provided signature.
return MslUtils.safeEquals(xmac, envelope.getSignature());
} catch (final MslEncodingException e) {
throw new MslCryptoException(MslError.SIGNATURE_ENVELOPE_PARSE_ERROR, e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid MAC algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_HMAC_KEY, e);
}
}
/** MSL context. */
protected final MslContext ctx;
/** Key set identity. */
protected final String id;
/** Encryption/decryption key. */
protected final SecretKey encryptionKey;
/** Signature key. */
protected final SecretKey signatureKey;
/** Wrapping key. */
protected final SecretKey wrappingKey;
}
| 9,834 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/util/Base64.java | /**
* Copyright (c) 2016 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.util.regex.Pattern;
/**
* <p>Base64 encoder/decoder. Can be configured with a backing
* implementation.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class Base64 {
/** Whitespace regular expression. */
private static final String WHITESPACE_REGEX = "\\s";
/** Base64 validation regular expression. */
private static final Pattern BASE64_PATTERN = Pattern.compile("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$");
/**
* <p>Validates that a string is a valid Base64 encoding. This uses a
* regular expression to perform the check. The empty string is also
* considered valid. All whitespace is ignored.</p>
*
* @param s the string to validate.
* @return true if the string is a valid Base64 encoding.
*/
public static boolean isValidBase64(final String s) {
final String sanitized = s.replaceAll(WHITESPACE_REGEX, "");
return BASE64_PATTERN.matcher(sanitized).matches();
}
/**
* <p>A Base64 encoder/decoder implementation. Implementations must be
* thread-safe.</p>
*/
public static interface Base64Impl {
/**
* <p>Base64 encodes binary data.</p>
*
* @param b the binary data.
* @return the Base64-encoded binary data.
*/
public String encode(final byte[] b);
/**
* <p>Decodes a Base64-encoded string into its binary form.</p>
*
* @param s the Base64-encoded string.
* @return the binary data.
* @throws IllegalArgumentException if the argument is not a valid
* Base64-encoded string. The empty string is considered valid.
* @see Base64#isValidBase64(String)
*/
public byte[] decode(final String s);
}
/**
* Set the backing implementation.
*
* @param impl the backing implementation.
* @throws NullPointerException if the implementation is {@code null}.
*/
public static void setImpl(final Base64Impl impl) {
if (impl == null)
throw new NullPointerException("Base64 implementation cannot be null.");
Base64.impl = impl;
}
/**
* <p>Base64 encodes binary data.</p>
*
* @param b the binary data.
* @return the Base64-encoded binary data.
*/
public static String encode(final byte[] b) {
return impl.encode(b);
}
/**
* <p>Decodes a Base64-encoded string into its binary form.</p>
*
* @param s the Base64-encoded string.
* @return the binary data.
* @throws IllegalArgumentException if the argument is not a valid Base64-
* encoded string.
*/
public static byte[] decode(final String s) {
// Delegate validation of the argument to the implementation.
return impl.decode(s);
}
/** The backing implementation. */
private static Base64Impl impl = new Base64Secure();
}
| 9,835 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/util/Base64Jaxb.java | /**
* Copyright (c) 2016 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import javax.xml.bind.DatatypeConverter;
import com.netflix.msl.util.Base64.Base64Impl;
/**
* <p>Base64 encoder/decoder implementation that uses the JAXB {@link DatatypeConverter}
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class Base64Jaxb implements Base64Impl {
/* (non-Javadoc)
* @see com.netflix.msl.util.Base64.Base64Impl#encode(byte[])
*/
@Override
public String encode(final byte[] b) {
return DatatypeConverter.printBase64Binary(b);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.Base64.Base64Impl#decode(java.lang.String)
*/
@Override
public byte[] decode(final String s) {
if (!Base64.isValidBase64(s))
throw new IllegalArgumentException("Invalid Base64 encoded string: " + s);
return DatatypeConverter.parseBase64Binary(s);
}
}
| 9,836 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/util/MslUtils.java | /**
* Copyright (c) 2013-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.util.Random;
import com.netflix.msl.MslConstants;
/**
* Utility methods.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslUtils {
/**
* Safely compares two byte arrays to prevent timing attacks.
*
* @param a first array for the comparison.
* @param b second array for the comparison.
* @return true if the arrays are equal, false if they are not.
*/
public static boolean safeEquals(final byte[] a, final byte[] b) {
if (a.length != b.length)
return false;
int result = 0;
for (int i = 0; i < a.length; ++i)
result |= a[i] ^ b[i];
return result == 0;
}
/**
* Return true if the number is a non-negative power of two. Zero is
* considered a power of two and will return true.
*
* @param n the number to test.
* @return true if the number is a non-negative power of two.
*/
private static boolean isPowerOf2(final long n) {
// If the number is a power of two, a binary AND operation between
// the number and itself minus one will equal zero.
if (n < 0) return false;
if (n == 0) return true;
return (n & (n - 1)) == 0;
}
/**
* Returns a random number between zero and the maximum long value as
* defined by {@link MslConstants#MAX_LONG_VALUE}, inclusive.
*
* @param ctx MSL context.
* @return a random number between zero and the maximum long value,
* inclusive.
*/
public static long getRandomLong(final MslContext ctx) {
// If the maximum long value is a power of 2, then we can perform a
// bitmask on the randomly generated long value to restrict to our
// target number space.
final boolean isPowerOf2 = MslUtils.isPowerOf2(MslConstants.MAX_LONG_VALUE);
// Generate the random value.
final Random r = ctx.getRandom();
long n = -1;
do {
n = r.nextLong();
// Perform a bitmask if permitted, which will force this loop
// to exit immediately.
if (isPowerOf2)
n &= (MslConstants.MAX_LONG_VALUE - 1);
} while (n < 0 || n > MslConstants.MAX_LONG_VALUE);
// Return the random value.
return n;
}
}
| 9,837 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/util/MslStore.java | /**
* Copyright (c) 2012-2020 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import 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;
/**
* <p>The Message Security Layer store manages the local store of master tokens
* identifying the local entity, user ID tokens identifying local users, and
* all service tokens issued by the local entity or remote entities. It also
* provides methods for identifying the tokens that should be included in a
* message and accessing crypto contexts associated with master tokens.<p>
*
* <p>Applications may wish to ensure the store contains only the newest master
* token and user ID tokens for the known users at application startup and
* shutdown.</p>
*
* <p>Implementations must be thread-safe.</p>
*
* @see MslContext
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public interface MslStore {
/**
* Save a master token and its associated crypto context. This replaces any
* existing association. Passing in a null crypto context is the same as
* calling {@link #removeCryptoContext(MasterToken)}.
*
* @param masterToken the master token.
* @param cryptoContext the crypto context. May be null.
*/
public void setCryptoContext(final MasterToken masterToken, final ICryptoContext cryptoContext);
/**
* Return the newest saved master token in this store.
*
* @return the newest saved master token or null.
*/
public MasterToken getMasterToken();
/**
* Return the next non-replayable ID of the provided master token.
*
* The initial number is one (1). Each call to this function should return
* the next largest number. The next largest number after
* {@link com.netflix.msl.MslConstants#MAX_LONG_VALUE} is zero (0).
*
* @return the next non-replayable ID.
*/
public long getNonReplayableId(final MasterToken masterToken);
/**
* Return the crypto context associated with the provided master token.
*
* @param masterToken the master token.
* @return the crypto context for the master token or null if not found.
*/
public ICryptoContext getCryptoContext(final MasterToken masterToken);
/**
* Remove a master token and its associated crypto context. This also
* removes any stored user ID tokens and service tokens that are no longer
* bound to a known master token.
*
* @param masterToken the master token.
*/
public void removeCryptoContext(final MasterToken masterToken);
/**
* Removes all master tokens and crypto contexts and bound user ID tokens
* and their bound service tokens.
*/
public void clearCryptoContexts();
/**
* Add a user ID token to the store, replacing any existing user ID token
* of the same user. The local user ID has no meeting external to the
* store.
*
* @param userId local user ID.
* @param userIdToken the user ID token.
* @throws MslException if the user ID token is not bound to any stored
* master token.
*/
public void addUserIdToken(final String userId, final UserIdToken userIdToken) throws MslException;
/**
* Returns the user ID token, if any, for the specified local user ID.
*
* @param userId local user ID.
* @return the user ID token for the local user ID or null.
*/
public UserIdToken getUserIdToken(final String userId);
/**
* Remove a user ID token. This also removes any service tokens no longer
* bound to a known user ID token.
*
* @param userIdToken the user ID token.
*/
public void removeUserIdToken(final UserIdToken userIdToken);
/**
* Removes all user ID tokens and user ID token bound service tokens.
*/
public void clearUserIdTokens();
/**
* <p>Add a set of service tokens to the store.</p>
*
* <p>Either all or none of the provided service tokens will be added.</p>
*
* @param tokens the service tokens.
* @throws MslException if a service token is master token bound to a
* master token not found in the store or if a service token is
* user ID token bound to a user ID token not found in the store.
*/
public void addServiceTokens(final Set<ServiceToken> tokens) throws MslException;
/**
* <p>Return the set of service tokens that are applicable to the provided
* pair of master token and user ID token. The base set consists of the
* service tokens that are not bound to any master token or user ID
* token.</p>
*
* <p>If a master token is provided, the service tokens that are bound to
* the master token and not bound to any user ID token are also
* provided.</p>
*
* <p>If a master token and user ID token is provided, the service tokens
* that are bound to both the master token and user ID token are also
* provided.</p>
*
* @param masterToken the master token. May be null.
* @param userIdToken the user ID token. May be null.
* @return the set of service tokens applicable to the message.
* @throws MslException if the user ID token is not bound to the master
* token or a user ID token is provided without also providing a
* master token.
*/
public Set<ServiceToken> getServiceTokens(final MasterToken masterToken, final UserIdToken userIdToken) throws MslException;
/**
* <p>Remove all service tokens matching all the specified parameters. A
* null value for the master token or user ID token restricts removal to
* tokens that are not bound to a master token or not bound to a user ID
* token respectively.</p>
*
* <p>For example, if a name and master token is provided, only tokens with
* that name, bound to that master token, and not bound to a user ID token
* are removed. If only a user ID token is provided, all tokens bound to
* that user ID token are removed.</p>
*
* <p>If no parameters are provided, no tokens are removed.</p>
*
* @param name service token name. May be null.
* @param masterToken master token. May be null.
* @param userIdToken user ID token. May be null.
* @throws MslException if the user ID token is not bound to the master
* token.
*/
public void removeServiceTokens(final String name, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException;
/**
* Removes all service tokens.
*/
public void clearServiceTokens();
} | 9,838 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/util/Base64Secure.java | /**
* Copyright (c) 2016-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.nio.charset.StandardCharsets;
import com.netflix.msl.util.Base64.Base64Impl;
/**
* <p>Base64 encoder/decoder implementation that strictly enforces the validity
* of the encoding and does not exit early if an error is encountered.
* Whitespace (space, tab, newline, carriage return) are skipped.</p>
*
* <p>Based upon {@link javax.xml.bind.DatatypeConverter}.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class Base64Secure implements Base64Impl {
/** The encode map. */
private static final char[] ENCODE_MAP = initEncodeMap();
/** The decode map. */
private static final byte[] DECODE_MAP = initDecodeMap();
/** Tab character value. */
private static final byte TAB = 9;
/** Newline character value. */
private static final byte NEWLINE = 10;
/** Carriage return character value. */
private static final byte CARRIAGE_RETURN = 13;
/** Space character value. */
private static final byte SPACE = 32;
/** Padding character sentinel value. */
private static final byte PADDING = 127;
/**
* @return the 64-character Base64 encode map.
*/
private static char[] initEncodeMap() {
final char[] map = new char[64];
for (int i = 0; i < 26; i++)
map[i] = (char)('A' + i);
for (int i = 26; i < 52; i++)
map[i] = (char)('a' + (i - 26));
for (int i = 52; i < 62; i++)
map[i] = (char)('0' + (i - 52));
map[62] = '+';
map[63] = '/';
return map;
}
/**
* @return the 128-byte Base64 decode map.
*/
private static byte[] initDecodeMap() {
final byte[] map = new byte[128];
for (int i = 0; i < 128; i++)
map[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
map[i] = (byte)(i - 'A');
for (int i = 'a'; i <= 'z'; i++)
map[i] = (byte)(i - 'a' + 26);
for (int i = '0'; i <= '9'; i++)
map[i] = (byte)(i - '0' + 52);
map['+'] = 62;
map['/'] = 63;
map['='] = PADDING;
return map;
}
/**
* @param i the value to encode.
* @return the character the value maps onto.
*/
private static char encode(final int i) {
return ENCODE_MAP[i & 0x3F];
}
/* (non-Javadoc)
* @see com.netflix.msl.util.Base64.Base64Impl#encode(byte[])
*/
@Override
public String encode(final byte[] b) {
// Allocate the character buffer.
final char[] buf = new char[((b.length + 2) / 3) * 4];
int ptr = 0;
// Encode elements until there are only 1 or 2 left.
int remaining = b.length;
int i;
for (i = 0; remaining >= 3; remaining -= 3, i += 3) {
buf[ptr++] = encode(b[i] >> 2);
buf[ptr++] = encode(((b[i] & 0x3) << 4) | ((b[i+1] >> 4) & 0xF));
buf[ptr++] = encode(((b[i + 1] & 0xF) << 2) | ((b[i + 2] >> 6) & 0x3));
buf[ptr++] = encode(b[i + 2] & 0x3F);
}
// If there is one final element...
if (remaining == 1) {
buf[ptr++] = encode(b[i] >> 2);
buf[ptr++] = encode(((b[i]) & 0x3) << 4);
buf[ptr++] = '=';
buf[ptr++] = '=';
}
// If there are two final elements...
else if (remaining == 2) {
buf[ptr++] = encode(b[i] >> 2);
buf[ptr++] = encode(((b[i] & 0x3) << 4) | ((b[i + 1] >> 4) & 0xF));
buf[ptr++] = encode((b[i + 1] & 0xF) << 2);
buf[ptr++] = '=';
}
// Return the encoded string.
return new String(buf);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.Base64.Base64Impl#decode(java.lang.String)
*/
@Override
public byte[] decode(final String s) {
// Flag to remember if we've encountered an invalid character or have
// reached the end of the string prematurely.
boolean invalid = false;
// Convert string to ISO 8859-1 bytes.
final byte[] sb = s.getBytes(StandardCharsets.ISO_8859_1);
// Allocate the destination buffer, which may be too large due to
// whitespace.
final int strlen = sb.length;
final int outlen = strlen * 3 / 4;
final byte[] out = new byte[outlen];
int o = 0;
// Convert each quadruplet to three bytes.
final byte[] quadruplet = new byte[4];
int q = 0;
boolean lastQuad = false;
for (int i = 0; i < strlen; ++i) {
final byte c = sb[i];
// Ensure the character is not "negative".
if (c < 0) {
invalid = true;
continue;
}
// Lookup the character in the decoder map.
final byte b = DECODE_MAP[c];
// Skip invalid characters.
if (b == -1) {
// Flag invalid for non-whitespace.
if (c != SPACE && c != TAB && c != NEWLINE && c != CARRIAGE_RETURN)
invalid = true;
continue;
}
// If we already saw the last quadruplet, we shouldn't see anymore.
if (lastQuad)
invalid = true;
// Append value to quadruplet.
quadruplet[q++] = b;
// If the quadruplet is full, append it to the destination buffer.
if (q == 4) {
// If the quadruplet starts with padding, flag invalid.
if (quadruplet[0] == PADDING || quadruplet[1] == PADDING)
invalid = true;
// If the quadruplet ends with padding, this better be the last
// quadruplet.
if (quadruplet[2] == PADDING || quadruplet[3] == PADDING)
lastQuad = true;
// Decode into the destination buffer.
out[o++] = (byte)((quadruplet[0] << 2) | (quadruplet[1] >> 4));
if (quadruplet[2] != PADDING)
out[o++] = (byte)((quadruplet[1] << 4) | (quadruplet[2] >> 2));
if (quadruplet[3] != PADDING)
out[o++] = (byte)((quadruplet[2] << 6) | (quadruplet[3]));
// Reset the quadruplet index.
q = 0;
}
}
// If the quadruplet is not empty, flag invalid.
if (q != 0)
invalid = true;
// If invalid throw an exception.
if (invalid)
throw new IllegalArgumentException("Invalid Base64 encoded string: " + s);
// Always copy the destination buffer into the return buffer to
// maintain consistent runtime.
final byte[] ret = new byte[o];
System.arraycopy(out, 0, ret, 0, o);
return ret;
}
}
| 9,839 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/util/NullAuthenticationUtils.java | /**
* Copyright (c) 2016 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.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;
/**
* <p>An authentication utilities implementation where all operations are
* permitted.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class NullAuthenticationUtils implements AuthenticationUtils {
/* (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 true;
}
/* (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 true;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.AuthenticationUtils#isSchemePermitted(java.lang.String, com.netflix.msl.tokens.MslUser, com.netflix.msl.userauth.UserAuthenticationScheme)
*/
@Override
public boolean isSchemePermitted(final String identity, final MslUser user, final UserAuthenticationScheme scheme) {
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 true;
}
}
| 9,840 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/util/MslCompression.java | /**
* Copyright (c) 2017-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.io.LZWInputStream;
import com.netflix.msl.io.LZWOutputStream;
/**
* <p>Data compression and uncompression. Can be configured with a backing
* implementation.</p>
*
* <p>This class is thread-safe.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslCompression {
/** Registered compression implementations. */
private static Map<CompressionAlgorithm,CompressionImpl> impls = new ConcurrentHashMap<CompressionAlgorithm,CompressionImpl>();
/** Maximum deflate ratio. Volatile should be good enough. */
private static volatile int maxDeflateRatio = 200;
/**
* <p>A data compression implementation. Implementations must be thread-
* safe.</p>
*/
public static interface CompressionImpl {
/**
* <p>Compress the provided data.</p>
*
* @param data the data to compress.
* @return the compressed data. May also return {@code null} if the
* compressed data would exceed the original data size.
* @throws IOException if there is an error compressing the data.
*/
public byte[] compress(final byte[] data) throws IOException;
/**
* <p>Uncompress the provided data.</p>
*
* <p>If the uncompressed data ever exceeds the maximum deflate ratio
* then uncompression must abort and an exception thrown.</p>
*
* @param data the data to uncompress.
* @param maxDeflateRatio the maximum deflate ratio.
* @return the uncompressed data.
* @throws IOException if there is an error uncompressing the data or
* if the ratio of uncompressed data to the compressed data
* ever exceeds the specified deflate ratio.
*/
public byte[] uncompress(final byte[] data, final int maxDeflateRatio) throws IOException;
}
/**
* Default GZIP compression implementation.
*/
private static class GzipCompressionImpl implements CompressionImpl {
/* (non-Javadoc)
* @see com.netflix.msl.util.MslCompression.CompressionImpl#compress(byte[])
*/
@Override
public byte[] compress(final byte[] data) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
final GZIPOutputStream gzos = new GZIPOutputStream(baos);
try {
gzos.write(data);
} finally {
gzos.close();
}
return baos.toByteArray();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslCompression.CompressionImpl#uncompress(byte[], int)
*/
@Override
public byte[] uncompress(final byte[] data, final int maxDeflateRatio) throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(data);
final GZIPInputStream gzis = new GZIPInputStream(bais);
try {
final byte[] buffer = new byte[data.length];
final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
while (buffer.length > 0) {
// Uncompress.
final int bytesRead = gzis.read(buffer);
if (bytesRead == -1) break;
// Check if the deflate ratio has been exceeded.
if (baos.size() + bytesRead > maxDeflateRatio * data.length)
throw new IOException("Deflate ratio " + maxDeflateRatio + " exceeded. Aborting uncompression.");
// Save the uncompressed data for return.
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
} finally {
gzis.close();
}
}
}
/**
* Default LZW compression implementation.
*/
private static class LzwCompressionImpl implements CompressionImpl {
/* (non-Javadoc)
* @see com.netflix.msl.util.MslCompression.CompressionImpl#compress(byte[])
*/
@Override
public byte[] compress(final byte[] data) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
final LZWOutputStream lzwos = new LZWOutputStream(baos);
try {
lzwos.write(data);
} finally {
lzwos.close();
}
return baos.toByteArray();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslCompression.CompressionImpl#uncompress(byte[], int)
*/
@Override
public byte[] uncompress(final byte[] data, final int maxDeflateRatio) throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(data);
final LZWInputStream lzwis = new LZWInputStream(bais);
try {
final byte[] buffer = new byte[data.length];
final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
while (buffer.length > 0) {
// Uncompress.
final int bytesRead = lzwis.read(buffer);
if (bytesRead == -1) break;
// Check if the deflate ratio has been exceeded.
if (baos.size() + bytesRead > maxDeflateRatio * data.length)
throw new IOException("Deflate ratio " + maxDeflateRatio + " exceeded. Aborting uncompression.");
// Save the uncompressed data for return.
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
} finally {
lzwis.close();
}
}
}
static {
MslCompression.register(CompressionAlgorithm.GZIP, new GzipCompressionImpl());
MslCompression.register(CompressionAlgorithm.LZW, new LzwCompressionImpl());
}
/**
* <p>Register a compression algorithm implementation. Pass {@code null} to
* remove an implementation.</p>
*
* @param algo the compression algorithm.
* @param impl the data compression implementation. May be {@code null}.
*/
public static void register(final CompressionAlgorithm algo, final CompressionImpl impl) {
if (impl == null)
impls.remove(algo);
else
impls.put(algo, impl);
}
/**
* <p>Sets the maximum deflate ratio used during uncompression. If the
* ratio is exceeded uncompression will abort.</p>
*
* @param deflateRatio the maximum deflate ratio.
* @throws IllegalArgumentException if the specified ratio is less than
* one.
*/
public static void setMaxDeflateRatio(final int deflateRatio) {
if (deflateRatio < 1)
throw new IllegalArgumentException("The maximum deflate ratio must be at least one.");
MslCompression.maxDeflateRatio = deflateRatio;
}
/**
* Compress the provided data using the specified compression algorithm.
*
* @param compressionAlgo the compression algorithm.
* @param data the data to compress.
* @return the compressed data or null if the compressed data would be larger than the
* uncompressed data.
* @throws MslException if there is an error compressing the data.
*/
public static byte[] compress(final CompressionAlgorithm compressionAlgo, final byte[] data) throws MslException {
final CompressionImpl impl = impls.get(compressionAlgo);
if (impl == null)
throw new MslException(MslError.UNSUPPORTED_COMPRESSION, compressionAlgo.name());
try {
final byte[] compressed = impl.compress(data);
return (compressed != null && compressed.length < data.length) ? compressed : null;
} catch (final IOException e) {
throw new MslException(MslError.COMPRESSION_ERROR, "algo " + compressionAlgo.name(), e);
}
}
/**
* Uncompress the provided data using the specified compression algorithm.
*
* @param compressionAlgo the compression algorithm.
* @param data the data to uncompress.
* @return the uncompressed data.
* @throws MslException if there is an error uncompressing the data.
*/
public static byte[] uncompress(final CompressionAlgorithm compressionAlgo, final byte[] data) throws MslException {
final CompressionImpl impl = impls.get(compressionAlgo);
if (impl == null)
throw new MslException(MslError.UNSUPPORTED_COMPRESSION, compressionAlgo.name());
try {
return impl.uncompress(data, maxDeflateRatio);
} catch (final IOException e) {
throw new MslException(MslError.UNCOMPRESSION_ERROR, "algo " + compressionAlgo.name(), e);
}
}
} | 9,841 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/util/SimpleMslStore.java | /**
* Copyright (c) 2012-2020 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
/**
* <p>A simple MSL store that maintains state.</p>
*
* <p>This class is thread-safe.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class SimpleMslStore implements MslStore {
/**
* Increments the provided non-replayable ID by 1, wrapping around to zero
* if the provided value is equal to {@link MslConstants#MAX_LONG_VALUE}.
*
* @param id the non-replayable ID to increment.
* @return the non-replayable ID + 1.
* @throws MslInternalException if the provided non-replayable ID is out of
* range.
*/
private static long incrementNonReplayableId(final long id) {
if (id < 0 || id > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Non-replayable ID " + id + " is outside the valid range.");
return (id == MslConstants.MAX_LONG_VALUE) ? 0 : id + 1;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#setCryptoContext(com.netflix.msl.tokens.MasterToken, com.netflix.msl.crypto.ICryptoContext)
*/
@Override
public void setCryptoContext(final MasterToken masterToken, final ICryptoContext cryptoContext) {
if (cryptoContext == null)
removeCryptoContext(masterToken);
else
cryptoContexts.put(masterToken, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getMasterToken()
*/
@Override
public MasterToken getMasterToken() {
MasterToken masterToken = null;
for (final MasterToken storedMasterToken : cryptoContexts.keySet()) {
if (masterToken == null || storedMasterToken.isNewerThan(masterToken))
masterToken = storedMasterToken;
}
return masterToken;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getNonReplayableId(com.netflix.msl.tokens.MasterToken)
*/
@Override
public synchronized long getNonReplayableId(final MasterToken masterToken) {
// Return the next largest non-replayable ID, or 1 if there is none.
final long serialNumber = masterToken.getSerialNumber();
final long currentId = (nonReplayableIds.containsKey(serialNumber))
? nonReplayableIds.get(serialNumber)
: 0;
final long nextId = incrementNonReplayableId(currentId);
nonReplayableIds.put(serialNumber, nextId);
return nextId;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getCryptoContext(com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MasterToken masterToken) {
return cryptoContexts.get(masterToken);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeCryptoContext(com.netflix.msl.tokens.MasterToken)
*/
@Override
public synchronized void removeCryptoContext(final MasterToken masterToken) {
// We must perform the removal operations in reverse-dependency order.
// This ensures the store is in the correct state, allowing all logical
// and safety checks to pass.
//
// First any bound user ID tokens are removed (which first removes any
// service tokens bound to those user ID tokens), then bound service
// tokens, and finally the non-replayable ID and crypto context and
// master token pair.
if (cryptoContexts.containsKey(masterToken)) {
// Look for a second master token with the same serial number. If
// there is one, then just remove this master token and its crypto
// context but do not remove any bound user ID tokens, service
// tokens, or the non-replayable ID as those are still associated
// with the master token that remains.
final long serialNumber = masterToken.getSerialNumber();
for (final MasterToken token : cryptoContexts.keySet()) {
if (!token.equals(masterToken) && token.getSerialNumber() == serialNumber) {
cryptoContexts.remove(masterToken);
return;
}
}
// Remove bound user ID tokens and service tokens.
for (final UserIdToken userIdToken : userIdTokens.values()) {
if (userIdToken.isBoundTo(masterToken))
removeUserIdToken(userIdToken);
}
try {
removeServiceTokens(null, masterToken, null);
} catch (final MslException e) {
// This should not happen since we are only providing a master
// token.
throw new MslInternalException("Unexpected exception while removing master token bound service tokens.", e);
}
// Remove the non-replayable ID.
nonReplayableIds.remove(serialNumber);
// Finally remove the crypto context.
cryptoContexts.remove(masterToken);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearCryptoContexts()
*/
@Override
public synchronized void clearCryptoContexts() {
cryptoContexts.clear();
nonReplayableIds.clear();
userIdTokens.clear();
uitServiceTokens.clear();
mtServiceTokens.clear();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#addUserIdToken(java.lang.String, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public void addUserIdToken(final String userId, final UserIdToken userIdToken) throws MslException {
boolean foundMasterToken = false;
for (final MasterToken masterToken : cryptoContexts.keySet()) {
if (userIdToken.isBoundTo(masterToken)) {
foundMasterToken = true;
break;
}
}
if (!foundMasterToken)
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_NOT_FOUND, "uit mtserialnumber " + userIdToken.getMasterTokenSerialNumber());
userIdTokens.put(userId, userIdToken);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getUserIdToken(java.lang.String)
*/
@Override
public UserIdToken getUserIdToken(final String userId) {
return userIdTokens.get(userId);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public void removeUserIdToken(final UserIdToken userIdToken) {
// Find the master token this user ID token is bound to.
MasterToken masterToken = null;
for (final MasterToken token : cryptoContexts.keySet()) {
if (userIdToken.isBoundTo(token)) {
masterToken = token;
break;
}
}
// If we didn't find a master token we shouldn't be able to find a user
// ID token, but it doesn't hurt to try anyway and clean things up.
for (final Entry<String,UserIdToken> entry : userIdTokens.entrySet()) {
if (entry.getValue().equals(userIdToken)) {
try {
removeServiceTokens(null, masterToken, userIdToken);
} catch (final MslException e) {
// This should not happen since we have already confirmed
// that the user ID token is bound to the master token.
throw new MslInternalException("Unexpected exception while removing user ID token bound service tokens.", e);
}
final String userId = entry.getKey();
userIdTokens.remove(userId);
break;
}
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearUserIdTokens()
*/
@Override
public void clearUserIdTokens() {
final List<UserIdToken> tokens = new ArrayList<UserIdToken>(userIdTokens.values());
for (final UserIdToken token : tokens)
removeUserIdToken(token);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#addServiceTokens(java.util.Set)
*/
@Override
public synchronized void addServiceTokens(final Set<ServiceToken> tokens) throws MslException {
// Verify we recognize the bound service tokens.
for (final ServiceToken token : tokens) {
// Verify master token bound.
if (token.isMasterTokenBound()) {
boolean foundMasterToken = false;
for (final MasterToken masterToken : cryptoContexts.keySet()) {
if (token.isBoundTo(masterToken)) {
foundMasterToken = true;
break;
}
}
if (!foundMasterToken)
throw new MslException(MslError.SERVICETOKEN_MASTERTOKEN_NOT_FOUND, "st mtserialnumber " + token.getMasterTokenSerialNumber());
}
// Verify user token bound.
if (token.isUserIdTokenBound()) {
boolean foundUserIdToken = false;
for (final UserIdToken userIdToken : userIdTokens.values()) {
if (token.isBoundTo(userIdToken)) {
foundUserIdToken = true;
break;
}
}
if (!foundUserIdToken)
throw new MslException(MslError.SERVICETOKEN_USERIDTOKEN_NOT_FOUND, "st uitserialnumber " + token.getUserIdTokenSerialNumber());
}
}
// Add service tokens.
for (final ServiceToken token : tokens) {
// Unbound?
if (token.isUnbound()) {
unboundServiceTokens.add(token);
continue;
}
// Master token bound?
if (token.isMasterTokenBound()) {
Set<ServiceToken> tokenSet = mtServiceTokens.get(token.getMasterTokenSerialNumber());
if (tokenSet == null) {
tokenSet = new HashSet<ServiceToken>();
mtServiceTokens.put(token.getMasterTokenSerialNumber(), tokenSet);
}
tokenSet.add(token);
}
// User ID token bound?
if (token.isUserIdTokenBound()) {
Set<ServiceToken> tokenSet = uitServiceTokens.get(token.getUserIdTokenSerialNumber());
if (tokenSet == null) {
tokenSet = new HashSet<ServiceToken>();
uitServiceTokens.put(token.getUserIdTokenSerialNumber(), tokenSet);
}
tokenSet.add(token);
}
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getServiceTokens(com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public synchronized Set<ServiceToken> getServiceTokens(final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
// Validate arguments.
if (userIdToken != null) {
if (masterToken == null)
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_NULL);
if (!userIdToken.isBoundTo(masterToken))
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit mtserialnumber " + userIdToken.getMasterTokenSerialNumber() + "; mt " + masterToken.getSerialNumber());
}
// Grab service tokens. We start with the set of unbound service
// tokens.
final Set<ServiceToken> serviceTokens = new HashSet<ServiceToken>();
serviceTokens.addAll(unboundServiceTokens);
// If we have a master token add the set of master token bound service
// tokens that are not bound to any user ID tokens.
if (masterToken != null) {
final Set<ServiceToken> mtTokens = mtServiceTokens.get(masterToken.getSerialNumber());
if (mtTokens != null) {
for (final ServiceToken mtToken : mtTokens) {
if (!mtToken.isUserIdTokenBound())
serviceTokens.add(mtToken);
}
}
}
// If we have a user ID token (and because of the check above a master
// token) add the set of user ID token bound service tokens that are
// also bound to the same master token.
if (userIdToken != null) {
final Set<ServiceToken> uitTokens = uitServiceTokens.get(userIdToken.getSerialNumber());
if (uitTokens != null) {
for (final ServiceToken uitToken : uitTokens) {
if (uitToken.isBoundTo(masterToken))
serviceTokens.add(uitToken);
}
}
}
return serviceTokens;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeServiceTokens(java.lang.String, com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public synchronized void removeServiceTokens(final String name, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
// Validate arguments.
if (userIdToken != null && masterToken != null &&
!userIdToken.isBoundTo(masterToken))
{
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit mtserialnumber " + userIdToken.getMasterTokenSerialNumber() + "; mt " + masterToken.getSerialNumber());
}
// If only a name was provided remove all unbound tokens with that
// name.
if (name != null && masterToken == null && userIdToken == null) {
// Remove all unbound tokens with the specified name.
final Iterator<ServiceToken> unboundTokens = unboundServiceTokens.iterator();
while (unboundTokens.hasNext()) {
if (unboundTokens.next().getName().equals(name))
unboundTokens.remove();
}
}
// If a master token was provided but no user ID token was provided,
// remove all tokens bound to the master token. If a name was also
// provided then limit removal to tokens with the specified name.
if (masterToken != null && userIdToken == null) {
final Set<ServiceToken> tokenSet = mtServiceTokens.get(masterToken.getSerialNumber());
if (tokenSet != null) {
final Iterator<ServiceToken> tokens = tokenSet.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
// Skip if the name was provided and it does not match.
if (name != null && !token.getName().equals(name))
continue;
// Remove the token.
tokens.remove();
}
}
}
// If a user ID token was provided remove all tokens bound to the user
// ID token. If a name was also provided then limit removal to tokens
// with the specified name.
if (userIdToken != null) {
final Set<ServiceToken> tokenSet = uitServiceTokens.get(userIdToken.getSerialNumber());
if (tokenSet != null) {
final Iterator<ServiceToken> tokens = tokenSet.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
// Skip if the name was provided and it does not match.
if (name != null && !token.getName().equals(name))
continue;
// Remove the token.
tokens.remove();
}
}
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearServiceTokens()
*/
@Override
public synchronized void clearServiceTokens() {
unboundServiceTokens.clear();
mtServiceTokens.clear();
uitServiceTokens.clear();
}
/** Map of master tokens onto crypto contexts. */
private final Map<MasterToken,ICryptoContext> cryptoContexts = new ConcurrentHashMap<MasterToken,ICryptoContext>();
/** Map of local user IDs onto User ID tokens. */
private final Map<String,UserIdToken> userIdTokens = new ConcurrentHashMap<String,UserIdToken>();
/** Map of master token serial numbers onto non-replayable IDs. */
private final Map<Long,Long> nonReplayableIds = new HashMap<Long,Long>();
/** Set of unbound service tokens. */
private final Set<ServiceToken> unboundServiceTokens = new HashSet<ServiceToken>();
/** Map of master token serial numbers onto service tokens. */
private final Map<Long,Set<ServiceToken>> mtServiceTokens = new HashMap<Long,Set<ServiceToken>>();
/** Map of user ID token serial numbers onto service tokens. */
private final Map<Long,Set<ServiceToken>> uitServiceTokens = new HashMap<Long,Set<ServiceToken>>();
}
| 9,842 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/util/NullMslStore.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.util.Collections;
import java.util.Set;
import com.netflix.msl.MslError;
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;
/**
* <p>A MSL store where all operations are no-ops.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class NullMslStore implements MslStore {
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#setCryptoContext(com.netflix.msl.tokens.MasterToken, com.netflix.msl.crypto.ICryptoContext)
*/
@Override
public void setCryptoContext(final MasterToken masterToken, final ICryptoContext cryptoContext) {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getMasterToken()
*/
@Override
public MasterToken getMasterToken() {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getNonReplayableId(com.netflix.msl.tokens.MasterToken)
*/
@Override
public long getNonReplayableId(final MasterToken masterToken) {
return 1;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getCryptoContext(com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MasterToken masterToken) {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeCryptoContext(com.netflix.msl.tokens.MasterToken)
*/
@Override
public void removeCryptoContext(final MasterToken masterToken) {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearCryptoContexts()
*/
@Override
public void clearCryptoContexts() {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#addUserIdToken(java.lang.String, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public void addUserIdToken(final String userId, final UserIdToken userIdToken) {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getUserIdToken(java.lang.String)
*/
@Override
public UserIdToken getUserIdToken(final String userId) {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeUserIdToken(com.netflix.msl.tokens.UserIdToken)
*/
@Override
public void removeUserIdToken(final UserIdToken userIdToken) {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearUserIdTokens()
*/
@Override
public void clearUserIdTokens() {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#addServiceTokens(java.util.Set)
*/
@Override
public void addServiceTokens(final Set<ServiceToken> tokens) {
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#getServiceTokens(com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public Set<ServiceToken> getServiceTokens(final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
// Validate arguments.
if (userIdToken != null) {
if (masterToken == null)
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_NULL);
if (!userIdToken.isBoundTo(masterToken))
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit mtserialnumber " + userIdToken.getMasterTokenSerialNumber() + "; mt " + masterToken.getSerialNumber());
}
return Collections.emptySet();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#removeServiceTokens(java.lang.String, com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public void removeServiceTokens(final String name, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
// Validate arguments.
if (userIdToken != null && masterToken != null &&
!userIdToken.isBoundTo(masterToken))
{
throw new MslException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit mtserialnumber " + userIdToken.getMasterTokenSerialNumber() + "; mt " + masterToken.getSerialNumber());
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslStore#clearServiceTokens()
*/
@Override
public void clearServiceTokens() {
}
}
| 9,843 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/util/MslContext.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.util.Date;
import java.util.Random;
import java.util.SortedSet;
import com.netflix.msl.MslConstants.ResponseCode;
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.MslEncoderFactory;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.msg.MessageCapabilities;
import com.netflix.msl.msg.MslControl;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
/**
* <p>The context provides access to all factories, builders, and containers
* that are needed by the MSL library. There is expected to be one global
* context per trusted services network or peer-to-peer network. By extension,
* the MSL store instance returned by the context is expected to be specific to
* the owning context.</p>
*
* @see MslStore
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class MslContext {
/** Milliseconds per second. */
private static final long MILLISECONDS_PER_SECOND = 1000;
/** Re-authentication reason codes. */
public static enum ReauthCode {
/** The master token was rejected as bad or invalid. */
ENTITY_REAUTH(ResponseCode.ENTITY_REAUTH),
/** The entity authentication data failed to authenticate the entity. */
ENTITYDATA_REAUTH(ResponseCode.ENTITYDATA_REAUTH),
;
/**
* @return the re-authentication code corresponding to the response
* code.
* @throws IllegalArgumentException if the response code does not map
* onto a re-authentication code.
*/
public static ReauthCode valueOf(final ResponseCode code) {
for (final ReauthCode value : ReauthCode.values()) {
if (value.code == code)
return value;
}
throw new IllegalArgumentException("Unknown reauthentication code value " + code + ".");
}
/**
* Create a new re-authentication code mapped from the specified
* response code.
*
* @param code the response code for the re-authentication code.
*/
private ReauthCode(final ResponseCode code) {
this.code = code;
}
/**
* @return the integer value of the response code.
*/
public int intValue() {
return code.intValue();
}
/** The response code value. */
private final ResponseCode code;
}
/**
* Returns the local entity time. This is assumed to be the real time.
*
* @return {number} the local entity time in milliseconds since the epoch.
*/
public abstract long getTime();
/**
* <p>Returns a random number generator.</p>
*
* <p>It is extremely important to provide a secure (pseudo-)random number
* generator with a good source of entropy. Many random number generators,
* including those found in the Java Runtime Environment, JavaScript, and
* operating systems do not provide sufficient randomness.</p>
*
* <p>If in doubt, performing an {@code XOR} on the output of two or more
* independent random sources can be used to provide better random
* values.</p>
*
* @return a random number generator.
*/
public abstract Random getRandom();
/**
* Returns true if the context is operating in a peer-to-peer network. The
* message processing logic is slightly different in peer-to-peer networks.
*
* @return true if in peer-to-peer mode.
*/
public abstract boolean isPeerToPeer();
/**
* Returns the message capabilities for this entity.
*
* @return this entity's message capabilities.
*/
public abstract MessageCapabilities getMessageCapabilities();
/**
* <p>Returns the entity authentication data for this entity. This is used
* to authenticate messages prior to generation of a master token.</p>
*
* <p>This method should never return {@code null} but may do so in the one
* situation when the {@code reauthCode} parameter is provided and the
* application knows that the request being sent can no longer succeed
* because the existing master token, user ID token, or service tokens are
* no longer valid. This will abort the request.</p>
*
* <p>If the {@code reauthCode} parameter is equal to
* {@link ReauthCode#ENTITY_REAUTH} then the existing master token has been
* rejected, along with its bound user ID tokens and service tokens.</p>
*
* <p>If the {@code reauthCode} parameter is equal to
* {@link ReauthCode#ENTITYDATA_REAUTH} then new entity re-authentication
* data should be returned for this and all subsequent calls.</p>
*
* <p>The entity authentication scheme must never change.</p>
*
* <p>This method will be called multiple times.</p>
*
* @param reauthCode non-{@code null} if the master token or entity
* authentication data was rejected. If the entity authentication
* data was rejected then new entity authentication data is
* required.
* @return this entity's entity authentication data or null.
*/
public abstract EntityAuthenticationData getEntityAuthenticationData(final ReauthCode reauthCode);
/**
* <p>Returns the primary crypto context used for MSL-level crypto
* operations. This is used for the master tokens and user ID tokens.</p>
*
* <p>Trusted network clients should return a crypto context that always
* returns false for verification. The other crypto context methods will
* not be used by trusted network clients.</p>
*
* @return the primary MSL crypto context.
* @throws MslCryptoException if there is an error creating the crypto
* context.
*/
public abstract ICryptoContext getMslCryptoContext() throws MslCryptoException;
/**
* <p>Returns the entity authentication scheme identified by the specified
* name or {@code null} if there is none.</p>
*
* @param name the entity authentication scheme name.
* @return the scheme identified by the specified name or {@code null} if
* there is none.
*/
public abstract EntityAuthenticationScheme getEntityAuthenticationScheme(final String name);
/**
* Returns the entity authentication factory for the specified scheme.
*
* @param scheme the entity authentication scheme.
* @return the entity authentication factory, or null if no factory is
* available.
*/
public abstract EntityAuthenticationFactory getEntityAuthenticationFactory(final EntityAuthenticationScheme scheme);
/**
* <p>Returns the user authentication scheme identified by the specified
* name or {@code null} if there is none.</p>
*
* @param name the user authentication scheme name.
* @return the scheme identified by the specified name or {@code null} if
* there is none.
*/
public abstract UserAuthenticationScheme getUserAuthenticationScheme(final String name);
/**
* Returns the user authentication factory for the specified scheme.
*
* Trusted network clients should always return null.
*
* @param scheme the user authentication scheme.
* @return the user authentication factory, or null if no factory is
* available.
*/
public abstract UserAuthenticationFactory getUserAuthenticationFactory(final UserAuthenticationScheme scheme);
/**
* Returns the token factory.
*
* This method will not be called by trusted network clients.
*
* @return the token factory.
*/
public abstract TokenFactory getTokenFactory();
/**
* <p>Returns the key exchange scheme identified by the specified name or
* {@code null} if there is none.</p>
*
* @param name the key exchange scheme name.
* @return the scheme identified by the specified name or {@code null} if
* there is none.
*/
public abstract KeyExchangeScheme getKeyExchangeScheme(final String name);
/**
* Returns the key exchange factory for the specified scheme.
*
* @param scheme the key exchange scheme.
* @return the key exchange factory, or null if no factory is available.
*/
public abstract KeyExchangeFactory getKeyExchangeFactory(final KeyExchangeScheme scheme);
/**
* Returns the supported key exchange factories in order of preferred use.
* This should return an immutable collection.
*
* @return the key exchange factories, or the empty set.
*/
public abstract SortedSet<KeyExchangeFactory> getKeyExchangeFactories();
/**
* Returns the MSL store specific to this MSL context.
*
* @return the MSL store.
*/
public abstract MslStore getMslStore();
/**
* Returns the MSL encoder factory specific to this MSL context.
*
* @return the MSL encoder factory.
*/
public abstract MslEncoderFactory getMslEncoderFactory();
/**
* <p>Update the remote entity time.</p>
*
* <p>This function is only used by {@link MslControl} and should not be
* used by the application.</p>
*
* @param time remote entity time.
*/
public final void updateRemoteTime(final Date time) {
final long localSeconds = getTime() / MILLISECONDS_PER_SECOND;
final long remoteSeconds = time.getTime() / MILLISECONDS_PER_SECOND;
offset = remoteSeconds - localSeconds;
synced = true;
}
/**
* <p>Return the expected remote entity time or {@code null} if the clock
* is not yet synchronized.</p>
*
* <p>This function is only used by {@link MslControl} and should not be
* used by the application.</p>
*
* @return the expected remote entity time or {@code null} if not known.
*/
public final Date getRemoteTime() {
if (!synced) return null;
final long localSeconds = getTime() / MILLISECONDS_PER_SECOND;
final long remoteSeconds = localSeconds + offset;
return new Date(remoteSeconds * MILLISECONDS_PER_SECOND);
}
/** Remote clock is synchronized. */
private volatile boolean synced = false;
/** Remote entity time offset from local time in seconds. */
private volatile long offset = 0;
}
| 9,844 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/util/AuthenticationUtils.java | /**
* Copyright (c) 2013-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.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;
/**
* Authentication utility functions.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public interface AuthenticationUtils {
/**
* Returns true if the entity identity has been revoked.
*
* @param identity the entity identity.
* @return true if the entity identity has been revoked.
*/
public boolean isEntityRevoked(final String identity);
/**
* Returns true if the identified entity is permitted to use the specified
* entity authentication scheme.
*
* @param identity the entity identity.
* @param scheme the entity authentication scheme.
* @return true if the entity is permitted to use the scheme.
*/
public boolean isSchemePermitted(final String identity, final EntityAuthenticationScheme scheme);
/**
* Returns true if the identified entity is permitted to use the specified
* user authentication scheme.
*
* @param identity the entity identity.
* @param scheme the user authentication scheme.
* @return true if the entity is permitted to use the scheme.
*/
public boolean isSchemePermitted(final String identity, final UserAuthenticationScheme scheme);
/**
* Returns true if the identified entity and user combination is permitted
* to use the specified user authentication scheme.
*
* @param identity the entity identity.
* @param user the user.
* @param scheme the user authentication scheme.
* @return true if the entity and user are permitted to use the scheme.
*/
public boolean isSchemePermitted(final String identity, final MslUser user, final UserAuthenticationScheme scheme);
/**
* Returns true if the identified entity is permitted to use the specified
* key exchange scheme.
*
* @param identity the entity identity.
* @param scheme the key exchange scheme.
* @return true if the entity is permitted to use the scheme.
*/
public boolean isSchemePermitted(final String identity, final KeyExchangeScheme scheme);
}
| 9,845 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageFactory.java | /**
* Copyright (c) 2015-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslConstants.ResponseCode;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.MslUserIdTokenException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslUtils;
/**
* <p>A message factory is used to create message streams and builders.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MessageFactory {
/**
* <p>Construct a new message input stream. The header is parsed.</p>
*
* <p>If key request data is provided and a matching key response data is
* found in the message header the key exchange will be performed to
* process the message payloads.</p>
*
* <p>Service tokens will be decrypted and verified with the provided crypto
* contexts identified by token name. A default crypto context may be
* provided by using the empty string as the token name; if a token name is
* not explcitly mapped onto a crypto context, the default crypto context
* will be used.</p>
*
* @param ctx MSL context.
* @param source MSL input stream.
* @param keyRequestData key request data to use when processing key
* response data.
* @param cryptoContexts the map of service token names onto crypto
* contexts used to decrypt and verify service tokens.
* @throws IOException if there is a problem reading from the input stream.
* @throws MslEncodingException if there is an error parsing the message.
* @throws MslCryptoException if there is an error decrypting or verifying
* the header or creating the message payload crypto context.
* @throws MslEntityAuthException if unable to create the entity
* authentication data.
* @throws MslUserAuthException if unable to create the user authentication
* data.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be or if it has been revoked.
* @throws MslUserIdTokenException if the user ID token has been revoked.
* @throws MslKeyExchangeException if there is an error with the key
* request data or key response data or the key exchange scheme is
* not supported.
* @throws MslMessageException if the message does not contain an entity
* authentication data or a master token, the header data is
* missing or invalid, or the message ID is negative, or the
* message is not encrypted and contains user authentication data,
* or if the message master token is expired and the message is not
* renewable.
* @throws MslException if the message does not contain an entity
* authentication data or a master token, or a token is improperly
* bound to another token.
*/
public MessageInputStream createInputStream(final MslContext ctx, final InputStream source, final Set<KeyRequestData> keyRequestData, final Map<String,ICryptoContext> cryptoContexts) throws IOException, MslEncodingException, MslEntityAuthException, MslCryptoException, MslUserAuthException, MslMessageException, MslKeyExchangeException, MslMasterTokenException, MslUserIdTokenException, MslMessageException, MslException {
return new MessageInputStream(ctx, source, keyRequestData, cryptoContexts);
}
/**
* Construct a new error message output stream. The header is output
* immediately by calling {@code #flush()} on the destination output
* stream.
*
* @param ctx the MSL context.
* @param destination MSL output stream.
* @param header error header.
* @param format the MSL encoder format.
* @throws IOException if there is an error writing the header.
*/
public MessageOutputStream createOutputStream(final MslContext ctx, final OutputStream destination, final ErrorHeader header, final MslEncoderFormat format) throws IOException {
return new MessageOutputStream(ctx, destination, header, format);
}
/**
* Construct a new message output stream. The header is output
* immediately by calling {@code #flush()} on the destination output
* stream. The most preferred compression algorithm and encoder format
* supported by the local entity and message header will be used.
*
* @param ctx the MSL context.
* @param destination MSL output stream.
* @param header message header.
* @param cryptoContext payload data crypto context.
* @throws IOException if there is an error writing the header.
*/
public MessageOutputStream createOutputStream(final MslContext ctx, final OutputStream destination, final MessageHeader header, final ICryptoContext cryptoContext) throws IOException {
return new MessageOutputStream(ctx, destination, header, cryptoContext);
}
/**
* <p>Create a new message builder that will craft a new error message in
* response to another message. If the message ID of the request is not
* specified (i.e. unknown) then a random message ID will be generated.</p>
*
* @param ctx MSL context.
* @param requestMessageId message ID of request. May be null.
* @param error the MSL error.
* @param userMessage localized user-consumable error message. May be null.
* @return the error header.
* @throws MslCryptoException if there is an error encrypting or signing
* the message.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
* @throws MslMessageException if no entity authentication data was
* returned by the MSL context.
*/
public ErrorHeader createErrorResponse(final MslContext ctx, final Long requestMessageId, final MslError error, final String userMessage) throws MslMessageException {
final EntityAuthenticationData entityAuthData = ctx.getEntityAuthenticationData(null);
// If we have the request message ID then the error response message ID
// must be equal to the request message ID + 1.
long messageId;
if (requestMessageId != null) {
messageId = MessageBuilder.incrementMessageId(requestMessageId);
}
// Otherwise use a random message ID.
else {
messageId = MslUtils.getRandomLong(ctx);
}
final ResponseCode errorCode = error.getResponseCode();
final int internalCode = error.getInternalCode();
final String errorMsg = error.getMessage();
return new ErrorHeader(ctx, entityAuthData, messageId, errorCode, internalCode, errorMsg, userMessage);
}
/**
* <p>Create a new message builder that will craft a new message with the
* specified message ID.</p>
*
* @param ctx MSL context.
* @param masterToken master token. May be null unless a user ID token is
* provided.
* @param userIdToken user ID token. May be null.
* @param messageId the message ID to use. Must be within range.
* @throws MslException if a user ID token is not bound to its
* corresponding master token.
*/
public MessageBuilder createRequest(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken, final long messageId) throws MslException {
return new MessageBuilder(ctx, masterToken, userIdToken, messageId);
}
/**
* <p>Create a new message builder that will craft a new message.</p>
*
* @param ctx MSL context.
* @param masterToken master token. May be null unless a user ID token is
* provided.
* @param userIdToken user ID token. May be null.
* @throws MslException if a user ID token is not bound to its
* corresponding master token.
*/
public MessageBuilder createRequest(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
return new MessageBuilder(ctx, masterToken, userIdToken);
}
/**
* Create a new message builder that will craft a new message in response
* to another message. The constructed message may be used as a request.
*
* @param ctx MSL context.
* @param requestHeader message header to respond to.
* @throws MslMasterTokenException if the provided message's master token
* is not trusted.
* @throws MslCryptoException if the crypto context from a key exchange
* cannot be created.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created.
* @throws MslUserAuthException if there is an error with the user
* authentication data or the user ID token cannot be created.
* @throws MslException if a user ID token in the message header is not
* bound to its corresponding master token or there is an error
* creating or renewing the master token.
*/
public MessageBuilder createResponse(final MslContext ctx, final MessageHeader requestHeader) throws MslKeyExchangeException, MslCryptoException, MslMasterTokenException, MslUserAuthException, MslException {
return new ResponseMessageBuilder(ctx, requestHeader);
}
/**
* Create a new message builder that will craft a new message in response
* to another message without issuing or renewing any master tokens or user
* ID tokens. The constructed message may be used as a request.
*
* @param ctx MSL context.
* @param requestHeader message header to respond to.
* @throws MslCryptoException if there is an error accessing the remote
* entity identity.
* @throws MslException if any of the request's user ID tokens is not bound
* to its master token.
*/
public MessageBuilder createIdempotentResponse(final MslContext ctx, final MessageHeader requestHeader) throws MslCryptoException, MslException {
return new IdempotentResponseMessageBuilder(ctx, requestHeader);
}
}
| 9,846 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageOutputStream.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* <p>A MSL message consists of a single MSL header followed by one or more
* payload chunks carrying application data. Each payload chunk is individually
* packaged but sequentially ordered. The end of the message is indicated by a
* payload with no data.</p>
*
* <p>No payload chunks may be included in an error message.</p>
*
* <p>Data is buffered until {@link #flush()} or {@link #close()} is called.
* At that point a new payload chunk is created and written out. Closing a
* {@code MessageOutputStream} does not close the destination output stream in
* case additional MSL messages will be written.</p>
*
* <p>A copy of the payload chunks is kept in-memory and can be retrieved by a
* a call to {@code getPayloads()} until {@code stopCaching()} is called. This
* is used to facilitate automatic re-sending of messages.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MessageOutputStream extends OutputStream {
/**
* Construct a new error message output stream. The header is output
* immediately by calling {@code #flush()} on the destination output
* stream.
*
* @param ctx the MSL context.
* @param destination MSL output stream.
* @param header error header.
* @param format the MSL encoder format.
* @throws IOException if there is an error writing the header.
*/
public MessageOutputStream(final MslContext ctx, final OutputStream destination, final ErrorHeader header, final MslEncoderFormat format) throws IOException {
// Encode the header.
final byte[] encoding;
try {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
encoding = header.toMslEncoding(encoder, format);
} catch (final MslEncoderException e) {
throw new IOException("Error encoding the error header.", e);
}
this.ctx = ctx;
this.destination = destination;
this.encoderFormat = format;
this.capabilities = ctx.getMessageCapabilities();
this.header = header;
this.compressionAlgo = null;
this.cryptoContext = null;
this.destination.write(encoding);
this.destination.flush();
}
/**
* <p>Construct a new message output stream. The header is output
* immediately by calling {@code #flush()} on the destination output
* stream.</p>
*
* <p>The most preferred compression algorithm and encoder format supported
* by the message header will be used. If this is a response, the message
* header capabilities will already consist of the intersection of the
* local and remote entity capabilities.</p>
*
* @param ctx the MSL context.
* @param destination MSL output stream.
* @param header message header.
* @param cryptoContext payload data crypto context.
* @throws IOException if there is an error writing the header.
*/
public MessageOutputStream(final MslContext ctx, final OutputStream destination, final MessageHeader header, final ICryptoContext cryptoContext) throws IOException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
// Identify the compression algorithm and encoder format.
final MessageCapabilities capabilities = header.getMessageCapabilities();
final CompressionAlgorithm compressionAlgo;
final MslEncoderFormat encoderFormat;
if (capabilities != null) {
final Set<CompressionAlgorithm> compressionAlgos = capabilities.getCompressionAlgorithms();
compressionAlgo = CompressionAlgorithm.getPreferredAlgorithm(compressionAlgos);
final Set<MslEncoderFormat> encoderFormats = capabilities.getEncoderFormats();
encoderFormat = encoder.getPreferredFormat(encoderFormats);
} else {
compressionAlgo = null;
encoderFormat = encoder.getPreferredFormat(null);
}
// Encode the header.
final byte[] encoding;
try {
encoding = header.toMslEncoding(encoder, encoderFormat);
} catch (final MslEncoderException e) {
throw new IOException("Error encoding the message header.", e);
}
this.ctx = ctx;
this.destination = destination;
this.encoderFormat = encoderFormat;
this.capabilities = capabilities;
this.header = header;
this.compressionAlgo = compressionAlgo;
this.cryptoContext = cryptoContext;
this.destination.write(encoding);
this.destination.flush();
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
/**
* Set the payload chunk compression algorithm that will be used for all
* future payload chunks. This function will flush any buffered data iff
* the compression algorithm is being changed.
*
* @param compressionAlgo payload chunk compression algorithm. Null for no
* compression.
* @return true if the compression algorithm is supported by the message,
* false if it is not.
* @throws IOException if buffered data could not be flushed. The
* compression algorithm will be unchanged.
* @throws MslInternalException if writing an error message.
* @see #flush()
*/
public boolean setCompressionAlgorithm(final CompressionAlgorithm compressionAlgo) throws IOException {
// Make sure this is not an error message,
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
throw new MslInternalException("Cannot write payload data for an error message.");
// Make sure the message is capable of using the compression algorithm.
if (compressionAlgo != null) {
if (capabilities == null)
return false;
final Set<CompressionAlgorithm> compressionAlgos = capabilities.getCompressionAlgorithms();
if (!compressionAlgos.contains(compressionAlgo))
return false;
}
if (this.compressionAlgo != compressionAlgo)
flush();
this.compressionAlgo = compressionAlgo;
return true;
}
/**
* @return the message header. Will be null for error messages.
*/
public MessageHeader getMessageHeader() {
if (header instanceof MessageHeader)
return (MessageHeader)header;
return null;
}
/**
* @return the error header. Will be null except for error messages.
*/
public ErrorHeader getErrorHeader() {
if (header instanceof ErrorHeader)
return (ErrorHeader)header;
return null;
}
/**
* Returns true if the payload application data is encrypted. This will be
* true if the entity authentication scheme provides encryption or if
* session keys were used. Returns false for error messages which do not
* have any payload chunks.
*
* @return true if the payload application data is encrypted. Will be false
* for error messages.
*/
public boolean encryptsPayloads() {
// Return false for error messages.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
return false;
// If the message uses entity authentication data for an entity
// authentication scheme that provides encryption, return true.
final EntityAuthenticationData entityAuthData = messageHeader.getEntityAuthenticationData();
if (entityAuthData != null && entityAuthData.getScheme().encrypts())
return true;
// If the message uses a master token, return true.
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
return true;
// If the message includes key response data, return true.
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null)
return true;
// Otherwise return false.
return false;
}
/**
* Returns true if the payload application data is integrity protected.
* This will be true if the entity authentication scheme provides integrity
* protection or if session keys were used. Returns false for error
* messages which do not have any payload chunks.
*
* @return true if the payload application data is integrity protected.
* Will be false for error messages.
*/
public boolean protectsPayloadIntegrity() {
// Return false for error messages.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
return false;
// If the message uses entity authentication data for an entity
// authentication scheme that provides integrity protection, return
// true.
final EntityAuthenticationData entityAuthData = messageHeader.getEntityAuthenticationData();
if (entityAuthData != null && entityAuthData.getScheme().protectsIntegrity())
return true;
// If the message uses a master token, return true.
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
return true;
// If the message includes key response data, return true.
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null)
return true;
// Otherwise return false.
return false;
}
/**
* Returns the payloads sent so far. Once payload caching is turned off
* this list will always be empty.
*
* @return an immutable ordered list of the payloads sent so far.
*/
List<PayloadChunk> getPayloads() {
return Collections.unmodifiableList(payloads);
}
/**
* Turns off caching of any message data (e.g. payloads).
*/
void stopCaching() {
caching = false;
payloads.clear();
}
/**
* By default the destination output stream is not closed when this message
* output stream is closed. If it should be closed then this method can be
* used to dictate the desired behavior.
*
* @param close true if the destination output stream should be closed,
* false if it should not.
*/
public void closeDestination(final boolean close) {
this.closeDestination = close;
}
/* (non-Javadoc)
* @see java.io.OutputStream#close()
*/
@Override
public void close() throws IOException {
if (closed) return;
// Send a final payload that can be used to identify the end of data.
// This is done by setting closed equal to true while the current
// payload not null.
closed = true;
flush();
currentPayload = null;
// Only close the destination if instructed to do so because we might
// want to reuse the connection.
if (closeDestination)
destination.close();
}
/**
* Flush any buffered data out to the destination. This creates a payload
* chunk. If there is no buffered data or this is an error message this
* function does nothing.
*
* @throws IOException if buffered data could not be flushed.
* @throws MslInternalException if writing an error message.
* @see java.io.OutputStream#flush()
*/
@Override
public void flush() throws IOException {
// If the current payload is null, we are already closed.
if (currentPayload == null) return;
// If we are not closed, and there is no data then we have nothing to
// send.
if (!closed && currentPayload.size() == 0) return;
// This is a no-op for error messages and handshake messages.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null || messageHeader.isHandshake()) return;
// Otherwise we are closed and need to send any buffered data as the
// last payload. If there is no buffered data, we still need to send a
// payload with the end of message flag set.
try {
final byte[] data = currentPayload.toByteArray();
final PayloadChunk chunk = createPayloadChunk(ctx, payloadSequenceNumber, messageHeader.getMessageId(), closed, compressionAlgo, data, this.cryptoContext);
if (caching) payloads.add(chunk);
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] encoding = chunk.toMslEncoding(encoder, encoderFormat);
destination.write(encoding);
destination.flush();
++payloadSequenceNumber;
// If we are closed, get rid of the current payload. This prevents
// us from sending any more payloads. Otherwise reset it for reuse.
if (closed)
currentPayload = null;
else
currentPayload.reset();
} catch (final MslEncoderException e) {
throw new IOException("Error encoding payload chunk [sequence number " + payloadSequenceNumber + "].", e);
} catch (final MslCryptoException e) {
throw new IOException("Error encrypting payload chunk [sequence number " + payloadSequenceNumber + "].", e);
} catch (final MslException e) {
throw new IOException("Error compressing payload chunk [sequence number " + payloadSequenceNumber + "].", e);
}
}
/**
* Create new payload chunk
*
* @param ctx the MSL context.
* @param sequenceNumber sequence number.
* @param messageId the message ID.
* @param endofmsg true if this is the last payload chunk of the message.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @param data the payload chunk application data.
* @param cryptoContext the crypto context.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the payload chunk.
* @throws MslException if there is an error compressing the data.
*/
protected PayloadChunk createPayloadChunk(final MslContext ctx, final long sequenceNumber, final long messageId, final boolean endofmsg, final CompressionAlgorithm compressionAlgo, final byte[] data, final ICryptoContext cryptoContext) throws MslEncodingException, MslCryptoException, MslException {
return new PayloadChunk(ctx, sequenceNumber, messageId, endofmsg, compressionAlgo, data, cryptoContext);
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(byte[], int, int)
*/
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
// Fail if closed.
if (closed)
throw new IOException("Message output stream already closed.");
// Make sure this is not an error message or handshake message.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
throw new MslInternalException("Cannot write payload data for an error message.");
if (messageHeader.isHandshake())
throw new MslInternalException("Cannot write payload data for a handshake message.");
// Append data.
currentPayload.write(b, off, len);
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(byte[])
*/
@Override
public void write(final byte[] b) throws IOException {
write(b, 0, b.length);
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(int)
*/
@Override
public void write(final int b) throws IOException {
final byte[] ba = new byte[1];
ba[0] = (byte)(b & 0xFF);
write(ba);
}
/** MSL context. */
private final MslContext ctx;
/** Destination output stream. */
private final OutputStream destination;
/** MSL encoder format. */
private final MslEncoderFormat encoderFormat;
/** Message output stream capabilities. */
private final MessageCapabilities capabilities;
/** Header. */
private final Header header;
/** Payload crypto context. */
private final ICryptoContext cryptoContext;
/** Paload chunk compression algorithm. */
private CompressionAlgorithm compressionAlgo;
/** Current payload sequence number. */
private long payloadSequenceNumber = 1;
/** Current payload chunk data. */
private ByteArrayOutputStream currentPayload = new ByteArrayOutputStream();
/** Stream is closed. */
private boolean closed = false;
/** True if the destination output stream should be closed. */
private boolean closeDestination = false;
/** True if caching data. */
private boolean caching = true;
/** Ordered list of sent payloads. */
private final List<PayloadChunk> payloads = new ArrayList<PayloadChunk>();
}
| 9,847 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageDebugContext.java | /**
* Copyright (c) 2013-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
/**
* <p>A message debug context is used to provide debugging callbacks to
* {@link com.netflix.msl.msg.MslControl}.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public interface MessageDebugContext {
/**
* Called just prior to sending a message with the message header or error
* header that will be sent. An error may occur preventing successful
* transmission of the header after this method is called.
*
* @param header message header or error header.
*/
public void sentHeader(final Header header);
/**
* Called just after receiving a message, before performing additional
* validation, with the message header or error header.
*
* @param header message header or error header.
*/
public void receivedHeader(final Header header);
}
| 9,848 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/ErrorHeader.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslConstants.ResponseCode;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>The error data is represented as
* {@code
* errordata = {
* "#mandatory" : [ "messageid", "errorcode" ],
* "timestamp" : "int64(0,2^53^)",
* "messageid" : "int64(0,2^53^)",
* "errorcode" : "int32(0,-)",
* "internalcode" : "int32(0,-)",
* "errormsg" : "string",
* "usermsg" : "string",
* }} where:
* <ul>
* <li>{@code timestamp} is the sender time when the header is created in seconds since the UNIX epoch</li>
* <li>{@code messageid} is the message ID</li>
* <li>{@code errorcode} is the error code</li>
* <li>{@code internalcode} is an service-specific error code</li>
* <li>{@code errormsg} is a developer-consumable error message</li>
* <li>{@code usermsg} is a user-consumable localized error message</li>
* </ul></p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class ErrorHeader extends Header {
/** Milliseconds per second. */
private static final long MILLISECONDS_PER_SECOND = 1000;
// Message error data.
/** Key timestamp. */
private static final String KEY_TIMESTAMP = "timestamp";
/** Key message ID. */
private static final String KEY_MESSAGE_ID = "messageid";
/** Key error code. */
private static final String KEY_ERROR_CODE = "errorcode";
/** Key internal code. */
private static final String KEY_INTERNAL_CODE = "internalcode";
/** Key error message. */
private static final String KEY_ERROR_MESSAGE = "errormsg";
/** Key user message. */
private static final String KEY_USER_MESSAGE = "usermsg";
/**
* <p>Construct a new error header with the provided error data.</p>
*
* @param ctx MSL context.
* @param entityAuthData the entity authentication data.
* @param messageId the message ID.
* @param errorCode the error code.
* @param internalCode the internal code. Negative to indicate no code.
* @param errorMsg the error message. May be null.
* @param userMsg the user message. May be null.
* @throws MslMessageException if no entity authentication data is
* provided.
*/
public ErrorHeader(final MslContext ctx, final EntityAuthenticationData entityAuthData, final long messageId, final ResponseCode errorCode, final int internalCode, final String errorMsg, final String userMsg) throws MslMessageException {
// Message ID must be within range.
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is out of range.");
// Message entity must be provided.
if (entityAuthData == null)
throw new MslMessageException(MslError.MESSAGE_ENTITY_NOT_FOUND);
this.ctx = ctx;
this.entityAuthData = entityAuthData;
this.timestamp = ctx.getTime() / MILLISECONDS_PER_SECOND;
this.messageId = messageId;
this.errorCode = errorCode;
this.internalCode = (internalCode >= 0) ? internalCode : -1;
this.errorMsg = errorMsg;
this.userMsg = userMsg;
// Construct the error data.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
errordata = encoder.createObject();
errordata.put(KEY_TIMESTAMP, this.timestamp);
errordata.put(KEY_MESSAGE_ID, this.messageId);
errordata.put(KEY_ERROR_CODE, this.errorCode.intValue());
if (this.internalCode > 0) errordata.put(KEY_INTERNAL_CODE, this.internalCode);
if (this.errorMsg != null) errordata.put(KEY_ERROR_MESSAGE, this.errorMsg);
if (this.userMsg != null) errordata.put(KEY_USER_MESSAGE, this.userMsg);
}
/**
* <p>Construct a new error header from the provided MSL object.</p>
*
* @param ctx MSL context.
* @param errordataBytes error data MSL encoding.
* @param entityAuthData the entity authentication data.
* @param signature the header signature.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException if there is an error decrypting or verifying
* the header.
* @throws MslEntityAuthException if the entity authentication data is not
* supported or erroneous.
* @throws MslMessageException if there is no entity authentication data
* (null), the error data is missing or invalid, the message ID is
* negative, or the internal code is negative.
*/
protected ErrorHeader(final MslContext ctx, final byte[] errordataBytes, final EntityAuthenticationData entityAuthData, final byte[] signature) throws MslEncodingException, MslCryptoException, MslEntityAuthException, MslMessageException {
this.ctx = ctx;
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] plaintext;
try {
// Validate the entity authentication data.
this.entityAuthData = entityAuthData;
if (entityAuthData == null)
throw new MslMessageException(MslError.MESSAGE_ENTITY_NOT_FOUND);
// Grab the entity crypto context.
final EntityAuthenticationScheme scheme = entityAuthData.getScheme();
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(scheme);
if (factory == null)
throw new MslEntityAuthException(MslError.ENTITYAUTH_FACTORY_NOT_FOUND, scheme.name());
final ICryptoContext cryptoContext = factory.getCryptoContext(ctx, entityAuthData);
// Verify and decrypt the error data.
if (!cryptoContext.verify(errordataBytes, signature, encoder))
throw new MslCryptoException(MslError.MESSAGE_VERIFICATION_FAILED).setEntityAuthenticationData(entityAuthData);
plaintext = cryptoContext.decrypt(errordataBytes, encoder);
} catch (final MslCryptoException e) {
e.setEntityAuthenticationData(entityAuthData);
throw e;
} catch (final MslEntityAuthException e) {
e.setEntityAuthenticationData(entityAuthData);
throw e;
}
try {
errordata = encoder.parseObject(plaintext);
messageId = errordata.getLong(KEY_MESSAGE_ID);
if (this.messageId < 0 || this.messageId > MslConstants.MAX_LONG_VALUE)
throw new MslMessageException(MslError.MESSAGE_ID_OUT_OF_RANGE, "errordata " + errordata).setEntityAuthenticationData(entityAuthData);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "errordata " + Base64.encode(plaintext), e).setEntityAuthenticationData(entityAuthData);
}
try {
timestamp = (errordata.has(KEY_TIMESTAMP)) ? errordata.getLong(KEY_TIMESTAMP) : null;
// If we do not recognize the error code then default to fail.
ResponseCode code = ResponseCode.FAIL;
try {
code = ResponseCode.valueOf(errordata.getInt(KEY_ERROR_CODE));
} catch (final IllegalArgumentException e) {
code = ResponseCode.FAIL;
}
errorCode = code;
if (errordata.has(KEY_INTERNAL_CODE)) {
internalCode = errordata.getInt(KEY_INTERNAL_CODE);
if (this.internalCode < 0)
throw new MslMessageException(MslError.INTERNAL_CODE_NEGATIVE, "errordata " + errordata).setEntityAuthenticationData(entityAuthData).setMessageId(messageId);
} else {
internalCode = -1;
}
errorMsg = errordata.optString(KEY_ERROR_MESSAGE, null);
userMsg = errordata.optString(KEY_USER_MESSAGE, null);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "errordata " + errordata, e).setEntityAuthenticationData(entityAuthData).setMessageId(messageId);
}
}
/**
* Returns the entity authentication data.
*
* @return the entity authentication data.
*/
public EntityAuthenticationData getEntityAuthenticationData() {
return entityAuthData;
}
/**
* @return the timestamp. May be null.
*/
public Date getTimestamp() {
return (timestamp != null) ? new Date(timestamp * MILLISECONDS_PER_SECOND) : null;
}
/**
* @return the message ID.
*/
public long getMessageId() {
return messageId;
}
/**
* Returns the error code. If the parsed error code is not recognized then
* this returns {@code ResponseCode#FAIL}.
*
* @return the error code.
*/
public ResponseCode getErrorCode() {
return errorCode;
}
/**
* @return the internal code or -1 if none provided.
*/
public int getInternalCode() {
return internalCode;
}
/**
* @return the error message. May be null.
*/
public String getErrorMessage() {
return errorMsg;
}
/**
* @return the user message. May be null.
*/
public String getUserMessage() {
return userMsg;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
// Return any cached encoding.
if (encodings.containsKey(format))
return encodings.get(format);
// Create the crypto context.
final EntityAuthenticationScheme scheme = entityAuthData.getScheme();
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(scheme);
if (factory == null)
throw new MslEncoderException("No entity authentication factory found for entity.");
final ICryptoContext cryptoContext;
try {
cryptoContext = factory.getCryptoContext(ctx, entityAuthData);
} catch (final MslEntityAuthException e) {
throw new MslEncoderException("Error creating the entity crypto context.", e);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error creating the entity crypto context.", e);
}
// Encrypt and sign the error data.
final byte[] plaintext = encoder.encodeObject(errordata, format);
final byte[] ciphertext;
try {
ciphertext = cryptoContext.encrypt(plaintext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error encrypting the error data.", e);
}
final byte[] signature;
try {
signature = cryptoContext.sign(ciphertext, encoder, format, this);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error signing the error data.", e);
}
// Create the encoding.
final MslObject header = encoder.createObject();
header.put(Header.KEY_ENTITY_AUTHENTICATION_DATA, entityAuthData);
header.put(Header.KEY_ERRORDATA, ciphertext);
header.put(Header.KEY_SIGNATURE, signature);
final byte[] encoding = encoder.encodeObject(header, format);
// Cache and return the encoding.
encodings.put(format, encoding);
return encoding;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (!(obj instanceof ErrorHeader)) return false;
final ErrorHeader that = (ErrorHeader)obj;
return entityAuthData.equals(that.entityAuthData) &&
(timestamp != null && timestamp.equals(that.timestamp) ||
timestamp == null && that.timestamp == null) &&
messageId == that.messageId &&
errorCode == that.errorCode &&
internalCode == that.internalCode &&
(errorMsg == that.errorMsg || (errorMsg != null && errorMsg.equals(that.errorMsg))) &&
(userMsg == that.userMsg || (userMsg != null && userMsg.equals(that.userMsg)));
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return entityAuthData.hashCode() ^
((timestamp != null) ? timestamp.hashCode() : 0) ^
Long.valueOf(messageId).hashCode() ^
errorCode.hashCode() ^
Integer.valueOf(internalCode).hashCode() ^
((errorMsg != null) ? errorMsg.hashCode() : 0) ^
((userMsg != null) ? userMsg.hashCode() : 0);
}
/** MSL context. */
protected final MslContext ctx;
/** Entity authentication data. */
protected final EntityAuthenticationData entityAuthData;
/** Error data. */
protected final MslObject errordata;
/** Timestamp in seconds since the epoch. */
private final Long timestamp;
/** Message ID. */
private final long messageId;
/** Error code. */
private final ResponseCode errorCode;
/** Internal code. */
private final int internalCode;
/** Error message. */
private final String errorMsg;
/** User message. */
private final String userMsg;
/** Cached encodings. */
protected final Map<MslEncoderFormat,byte[]> encodings = new HashMap<MslEncoderFormat,byte[]>();
}
| 9,849 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/ErrorMessageRegistry.java | /**
* Copyright (c) 2013-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.util.List;
import com.netflix.msl.MslError;
/**
* <p>The error message registry is used to provide localized user-consumable
* messages for specific MSL errors.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public interface ErrorMessageRegistry {
/**
* Returns the user-consumable message associated with the given MSL error,
* localized according to the list of preferred languages.
*
* @param err MSL error.
* @param languages preferred languages as BCP-47 codes in descending
* order. May be {@code null}.
* @return the localized user message or {@code null} if there is none.
*/
public String getUserMessage(final MslError err, final List<String> languages);
/**
* Returns the user-consumable message associated with a given non-MSL
* error, localized according to the list of preferred languages.
*
* @param err non-MSL error.
* @param languages preferred languages as BCP-47 codes in descending
* order. May be {@code null}.
* @return the localized user message or {@code null} if there is none.
*/
public String getUserMessage(final Throwable err, final List<String> languages);
}
| 9,850 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/PayloadChunk.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.io.MslEncodable;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslCompression;
import com.netflix.msl.util.MslContext;
/**
* <p>A payload chunk is a self-contained block of application data that is
* encrypted, verified, and optionally compressed independent of other chunks.
* A message payload may contain one or more chunks.</p>
*
* <p>Payload chunks are bound to a specific message by the message ID.</p>
*
* <p>Each payload chunk in a message is sequentially ordered by the chunk
* sequence number. The sequence number starts at 1 and is incremented by 1 on
* each sequential chunk.</p>
*
* <p>Payload chunks are represented as
* {@code
* payloadchunk = {
* "#mandatory" : [ "payload", "signature" ],
* "payload" : "binary",
* "signature" : "binary"
* }} where:
* <ul>
* <li>{@code payload} is the Base64-encoded encrypted payload (payload)</li>
* <li>{@code signature} is the Base64-encoded verification data of the payload</li>
* </ul></p>
*
* <p>The payload is represented as
* {@code
* payload = {
* "#mandatory" : [ "sequencenumber", "messageid", "data" ],
* "sequencenumber" : "int64(1,2^53^)",
* "messageid" : "int64(0,2^53^)",
* "endofmsg" : "boolean",
* "compressionalgo" : "enum(GZIP|LZW)",
* "data" : "binary"
* }} where:
* <ul>
* <li>{@code sequencenumber} is the chunk sequence number</li>
* <li>{@code messageid} is the message ID</li>
* <li>{@code endofmsg} indicates this is the last payload of the message</li>
* <li>{@code compressionalgo} indicates the algorithm used to compress the data</li>
* <li>{@code data} is the optionally compressed application data</li>
* </ul></p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class PayloadChunk implements MslEncodable {
/** Key payload. */
private static final String KEY_PAYLOAD = "payload";
/** Key signature. */
private static final String KEY_SIGNATURE = "signature";
// payload
/** Key sequence number. */
private static final String KEY_SEQUENCE_NUMBER = "sequencenumber";
/** Key message ID. */
private static final String KEY_MESSAGE_ID = "messageid";
/** Key end of message. */
private static final String KEY_END_OF_MESSAGE = "endofmsg";
/** Key compression algorithm. */
private static final String KEY_COMPRESSION_ALGORITHM = "compressionalgo";
/** Key encrypted data. */
private static final String KEY_DATA = "data";
/**
* Construct a new payload chunk with the given message ID, data and
* provided crypto context. If requested, the data will be compressed
* before encrypting.
*
* @param ctx the MSL context.
* @param sequenceNumber sequence number.
* @param messageId the message ID.
* @param endofmsg true if this is the last payload chunk of the message.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @param data the payload chunk application data.
* @param cryptoContext the crypto context.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the payload chunk.
* @throws MslException if there is an error compressing the data.
*/
public PayloadChunk(final MslContext ctx, final long sequenceNumber, final long messageId, final boolean endofmsg, final CompressionAlgorithm compressionAlgo, final byte[] data, final ICryptoContext cryptoContext) throws MslEncodingException, MslCryptoException, MslException {
// Verify sequence number and message ID.
if (sequenceNumber < 0 || sequenceNumber > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Sequence number " + sequenceNumber + " is outside the valid range.");
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is outside the valid range.");
// Optionally compress the application data.
final byte[] payloadData;
if (compressionAlgo != null) {
final byte[] compressed = MslCompression.compress(compressionAlgo, data);
// Only use compression if the compressed data is smaller than the
// uncompressed data.
if (compressed != null && compressed.length < data.length) {
this.compressionAlgo = compressionAlgo;
payloadData = compressed;
} else {
this.compressionAlgo = null;
payloadData = data;
}
} else {
this.compressionAlgo = null;
payloadData = data;
}
// Set the payload properties.
this.sequenceNumber = sequenceNumber;
this.messageId = messageId;
this.endofmsg = endofmsg;
this.data = data;
// Construct the payload.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
this.payload = encoder.createObject();
this.payload.put(KEY_SEQUENCE_NUMBER, this.sequenceNumber);
this.payload.put(KEY_MESSAGE_ID, this.messageId);
if (this.endofmsg) this.payload.put(KEY_END_OF_MESSAGE, this.endofmsg);
if (this.compressionAlgo != null) this.payload.put(KEY_COMPRESSION_ALGORITHM, this.compressionAlgo.name());
this.payload.put(KEY_DATA, payloadData);
// Save the crypto context.
this.cryptoContext = cryptoContext;
}
/**
* <p>Construct a new payload chunk from the provided MSL object.</p>
*
* <p>The provided crypto context will be used to decrypt and verify the
* data signature.</p>
*
* @param ctx the MSL context.
* @param payloadChunkMo the MSL object.
* @param cryptoContext the crypto context.
* @throws MslCryptoException if there is a problem decrypting or verifying
* the payload chunk.
* @throws MslEncodingException if there is a problem parsing the data.
* @throws MslMessageException if the compression algorithm is not known,
* or the payload data is corrupt or missing.
* @throws MslException if there is an error uncompressing the data.
*/
public PayloadChunk(final MslContext ctx, final MslObject payloadChunkMo, final ICryptoContext cryptoContext) throws MslEncodingException, MslCryptoException, MslMessageException, MslException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
// Save the crypto context.
this.cryptoContext = cryptoContext;
// Verify the data.
final byte[] ciphertext;
try {
ciphertext = payloadChunkMo.getBytes(KEY_PAYLOAD);
final byte[] signature = payloadChunkMo.getBytes(KEY_SIGNATURE);
if (!cryptoContext.verify(ciphertext, signature, encoder))
throw new MslCryptoException(MslError.PAYLOAD_VERIFICATION_FAILED);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "payload chunk " + payloadChunkMo, e);
}
// Pull the payload data.
final byte[] plaintext = cryptoContext.decrypt(ciphertext, encoder);
try {
payload = encoder.parseObject(plaintext);
sequenceNumber = payload.getLong(KEY_SEQUENCE_NUMBER);
if (sequenceNumber < 0 || sequenceNumber > MslConstants.MAX_LONG_VALUE)
throw new MslException(MslError.PAYLOAD_SEQUENCE_NUMBER_OUT_OF_RANGE, "payload chunk payload " + payload);
messageId = payload.getLong(KEY_MESSAGE_ID);
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslException(MslError.PAYLOAD_MESSAGE_ID_OUT_OF_RANGE, "payload chunk payload " + payload);
endofmsg = (payload.has(KEY_END_OF_MESSAGE)) ? payload.getBoolean(KEY_END_OF_MESSAGE) : false;
if (payload.has(KEY_COMPRESSION_ALGORITHM)) {
final String algoName = payload.getString(KEY_COMPRESSION_ALGORITHM);
try {
compressionAlgo = CompressionAlgorithm.valueOf(algoName);
} catch (final IllegalArgumentException e) {
throw new MslMessageException(MslError.UNIDENTIFIED_COMPRESSION, algoName, e);
}
} else {
compressionAlgo = null;
}
final byte[] compressedData = payload.getBytes(KEY_DATA);
if (compressedData.length == 0) {
if (!endofmsg)
throw new MslMessageException(MslError.PAYLOAD_DATA_MISSING);
data = new byte[0];
} else if (compressionAlgo == null) {
data = compressedData;
} else {
data = MslCompression.uncompress(compressionAlgo, compressedData);
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "payload chunk payload " + Base64.encode(plaintext), e);
}
}
/**
* @return the sequence number.
*/
public long getSequenceNumber() {
return sequenceNumber;
}
/**
* @return the message ID.
*/
public long getMessageId() {
return messageId;
}
/**
* @return true if this is the last payload chunk of the message.
*/
public boolean isEndOfMessage() {
return endofmsg;
}
/**
* @return the compression algorithm. May be {@code null} if not
* not compressed.
*/
public CompressionAlgorithm getCompressionAlgo() {
return compressionAlgo;
}
/**
* Returns the application data if we were able to decrypt it.
*
* @return the chunk application data. May be empty (zero-length).
*/
public byte[] getData() {
return data;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
// Return any cached encoding.
if (encodings.containsKey(format))
return encodings.get(format);
// Encrypt the payload.
final byte[] plaintext = encoder.encodeObject(payload, format);
final byte[] ciphertext;
try{
ciphertext = cryptoContext.encrypt(plaintext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error encrypting the payload.", e);
}
// Sign the payload.
final byte[] signature;
try {
signature = cryptoContext.sign(ciphertext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error signing the payload.", e);
}
// Encode the payload chunk.
final MslObject mo = encoder.createObject();
mo.put(KEY_PAYLOAD, ciphertext);
mo.put(KEY_SIGNATURE, signature);
final byte[] encoding = encoder.encodeObject(mo, format);
// Cache and return the encoding.
encodings.put(format, encoding);
return encoding;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof PayloadChunk)) return false;
final PayloadChunk that = (PayloadChunk)obj;
return sequenceNumber == that.sequenceNumber &&
messageId == that.messageId &&
endofmsg == that.endofmsg &&
compressionAlgo == that.compressionAlgo &&
Arrays.equals(data, that.data);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Long.valueOf(sequenceNumber).hashCode() ^
Long.valueOf(messageId).hashCode() ^
Boolean.valueOf(endofmsg).hashCode() ^
((compressionAlgo != null) ? compressionAlgo.hashCode() : 0) ^
Arrays.hashCode(data);
}
/** Payload. */
private final MslObject payload;
/** Sequence number. */
private final long sequenceNumber;
/** Message ID. */
private final long messageId;
/** End of message flag. */
private final boolean endofmsg;
/** Compression algorithm. */
private final CompressionAlgorithm compressionAlgo;
/** The application data. */
private final byte[] data;
/** Payload crypto context. */
protected final ICryptoContext cryptoContext;
/** Cached encodings. */
protected final Map<MslEncoderFormat,byte[]> encodings = new HashMap<MslEncoderFormat,byte[]>();
}
| 9,851 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageInputStream.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.MslUserIdTokenException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.SessionCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.io.MslTokenizer;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.util.MslContext;
/**
* <p>A MSL message consists of a single MSL header followed by one or more
* payload chunks carrying application data. Each payload chunk is individually
* packaged but sequentially ordered. No payload chunks may be included in an
* error message.</p>
*
* <p>Data is read until an end-of-message payload chunk is encountered or an
* error occurs. Closing a {@code MessageInputStream} does not close the source
* input stream in case additional MSL messages will be read.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MessageInputStream extends InputStream {
/**
* <p>Return the crypto context resulting from key response data contained
* in the provided header.</p>
*
* <p>The {@link MslException}s thrown by this method will not have the
* entity or user set.</p>
*
* @param ctx MSL context.
* @param header header.
* @param keyRequestData key request data for key exchange.
* @return the crypto context or null if the header does not contain key
* response data or is for an error message.
* @throws MslKeyExchangeException if there is an error with the key
* request data or key response data or the key exchange scheme is
* not supported.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be.
* @throws MslEntityAuthException if there is a problem with the master
* token identity.
*/
private static ICryptoContext getKeyxCryptoContext(final MslContext ctx, final MessageHeader header, final Set<KeyRequestData> keyRequestData) throws MslCryptoException, MslKeyExchangeException, MslEncodingException, MslMasterTokenException, MslEntityAuthException {
// Pull the header data.
final MessageHeader messageHeader = header;
final MasterToken masterToken = messageHeader.getMasterToken();
final KeyResponseData keyResponse = messageHeader.getKeyResponseData();
// If there is no key response data then return null.
if (keyResponse == null)
return null;
// If the key response data master token is decrypted then use the
// master token keys to create the crypto context.
final MasterToken keyxMasterToken = keyResponse.getMasterToken();
if (keyxMasterToken.isDecrypted())
return new SessionCryptoContext(ctx, keyxMasterToken);
// Perform the key exchange.
final KeyExchangeScheme responseScheme = keyResponse.getKeyExchangeScheme();
final KeyExchangeFactory factory = ctx.getKeyExchangeFactory(responseScheme);
if (factory == null)
throw new MslKeyExchangeException(MslError.KEYX_FACTORY_NOT_FOUND, responseScheme.name());
// Attempt the key exchange but if it fails then try with the next
// key request data before giving up.
MslException keyxException = null;
final Iterator<KeyRequestData> keyRequests = keyRequestData.iterator();
while (keyRequests.hasNext()) {
final KeyRequestData keyRequest = keyRequests.next();
final KeyExchangeScheme requestScheme = keyRequest.getKeyExchangeScheme();
// Skip incompatible key request data.
if (!responseScheme.equals(requestScheme))
continue;
try {
return factory.getCryptoContext(ctx, keyRequest, keyResponse, masterToken);
} catch (final MslKeyExchangeException e) {
if (!keyRequests.hasNext()) throw e;
keyxException = e;
} catch (final MslEncodingException e) {
if (!keyRequests.hasNext()) throw e;
keyxException = e;
} catch (final MslMasterTokenException e) {
if (!keyRequests.hasNext()) throw e;
keyxException = e;
} catch (final MslEntityAuthException e) {
if (!keyRequests.hasNext()) throw e;
keyxException = e;
}
}
// We did not perform a successful key exchange. If we caught an
// exception then throw that exception now.
if (keyxException != null) {
if (keyxException instanceof MslKeyExchangeException)
throw (MslKeyExchangeException)keyxException;
if (keyxException instanceof MslEncodingException)
throw (MslEncodingException)keyxException;
if (keyxException instanceof MslMasterTokenException)
throw (MslMasterTokenException)keyxException;
if (keyxException instanceof MslEntityAuthException)
throw (MslEntityAuthException)keyxException;
throw new MslInternalException("Unexpected exception caught during key exchange.", keyxException);
}
// If we did not perform a successful key exchange then the
// payloads will not decrypt properly. Throw an exception.
throw new MslKeyExchangeException(MslError.KEYX_RESPONSE_REQUEST_MISMATCH, Arrays.toString(keyRequestData.toArray()));
}
/**
* <p>Construct a new message input stream. The header is parsed.</p>
*
* <p>If key request data is provided and a matching key response data is
* found in the message header the key exchange will be performed to
* process the message payloads.</p>
*
* <p>Service tokens will be decrypted and verified with the provided crypto
* contexts identified by token name. A default crypto context may be
* provided by using the empty string as the token name; if a token name is
* not explcitly mapped onto a crypto context, the default crypto context
* will be used.</p>
*
* @param ctx MSL context.
* @param source MSL input stream.
* @param keyRequestData key request data to use when processing key
* response data.
* @param cryptoContexts the map of service token names onto crypto
* contexts used to decrypt and verify service tokens.
* @throws IOException if there is a problem reading from the input stream.
* @throws MslEncodingException if there is an error parsing the message.
* @throws MslCryptoException if there is an error decrypting or verifying
* the header or creating the message payload crypto context.
* @throws MslEntityAuthException if unable to create the entity
* authentication data.
* @throws MslUserAuthException if unable to create the user authentication
* data.
* @throws MslMessageException if the message master token is expired and
* the message is not renewable.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be or if it has been revoked.
* @throws MslUserIdTokenException if the user ID token has been revoked.
* @throws MslKeyExchangeException if there is an error with the key
* request data or key response data or the key exchange scheme is
* not supported.
* @throws MslMessageException if the message does not contain an entity
* authentication data or a master token, the header data is
* missing or invalid, or the message ID is negative, or the
* message is not encrypted and contains user authentication data,
* or if the message master token is expired and the message is not
* renewable.
* @throws MslException if the message does not contain an entity
* authentication data or a master token, or a token is improperly
* bound to another token.
*/
public MessageInputStream(final MslContext ctx, final InputStream source, final Set<KeyRequestData> keyRequestData, final Map<String,ICryptoContext> cryptoContexts) throws IOException, MslEncodingException, MslEntityAuthException, MslCryptoException, MslUserAuthException, MslMessageException, MslKeyExchangeException, MslMasterTokenException, MslUserIdTokenException, MslMessageException, MslException {
// Parse the header.
this.ctx = ctx;
this.source = source;
final MslObject mo;
try {
this.tokenizer = this.ctx.getMslEncoderFactory().createTokenizer(source);
if (!this.tokenizer.more(-1))
throw new MslEncodingException(MslError.MESSAGE_DATA_MISSING);
mo = this.tokenizer.nextObject(-1);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "header", e);
}
this.header = Header.parseHeader(ctx, mo, cryptoContexts);
try {
// For error messages there are no key exchange or payload crypto
// contexts.
if (this.header instanceof ErrorHeader) {
this.keyxCryptoContext = null;
this.cryptoContext = null;
return;
}
// Grab the key exchange crypto context, if any.
final MessageHeader messageHeader = (MessageHeader)this.header;
this.keyxCryptoContext = getKeyxCryptoContext(ctx, messageHeader, keyRequestData);
// In peer-to-peer mode or in trusted network mode with no key
// exchange the payload crypto context equals the header crypto
// context.
if (ctx.isPeerToPeer() || this.keyxCryptoContext == null)
this.cryptoContext = messageHeader.getCryptoContext();
// Otherwise the payload crypto context equals the key exchange
// crypto context.
else
this.cryptoContext = this.keyxCryptoContext;
// If this is a handshake message but it is not renewable or does
// not contain key request data then reject the message.
if (messageHeader.isHandshake() &&
(!messageHeader.isRenewable() || messageHeader.getKeyRequestData().isEmpty()))
{
throw new MslMessageException(MslError.HANDSHAKE_DATA_MISSING, messageHeader.toString());
}
// If I am in peer-to-peer mode or the master token is verified
// (i.e. issued by the local entity which is therefore a trusted
// network server) then perform the master token checks.
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null && (ctx.isPeerToPeer() || masterToken.isVerified())) {
// If the master token has been revoked then reject the
// message.
final TokenFactory factory = ctx.getTokenFactory();
final MslError revoked = factory.isMasterTokenRevoked(ctx, masterToken);
if (revoked != null)
throw new MslMasterTokenException(revoked, masterToken);
// If the user ID token has been revoked then reject the
// message. We know the master token is not null and that it is
// verified so we assume the user ID token is as well.
final UserIdToken userIdToken = messageHeader.getUserIdToken();
if (userIdToken != null) {
final MslError uitRevoked = factory.isUserIdTokenRevoked(ctx, masterToken, userIdToken);
if (uitRevoked != null)
throw new MslUserIdTokenException(uitRevoked, userIdToken);
}
// If the master token is expired...
if (masterToken.isExpired(null)) {
// If the message is not renewable or does not contain key
// request data then reject the message.
if (!messageHeader.isRenewable())
throw new MslMessageException(MslError.MESSAGE_EXPIRED_NOT_RENEWABLE, messageHeader.toString());
else if (messageHeader.getKeyRequestData().isEmpty())
throw new MslMessageException(MslError.MESSAGE_EXPIRED_NO_KEYREQUEST_DATA, messageHeader.toString());
// If the master token will not be renewed by the token
// factory then reject the message.
//
// This throws an exception if the master token is not
// renewable.
final MslError notRenewable = factory.isMasterTokenRenewable(ctx, masterToken);
if (notRenewable != null)
throw new MslMessageException(notRenewable, "Master token is expired and not renewable.");
}
}
// If the message is non-replayable (it is not from a trusted
// network server).
final Long nonReplayableId = messageHeader.getNonReplayableId();
if (nonReplayableId != null) {
// ...and does not include a master token then reject the
// message.
if (masterToken == null)
throw new MslMessageException(MslError.INCOMPLETE_NONREPLAYABLE_MESSAGE, messageHeader.toString());
// If the non-replayable ID is not accepted then notify the
// sender.
final TokenFactory factory = ctx.getTokenFactory();
final MslError replayed = factory.acceptNonReplayableId(ctx, masterToken, nonReplayableId);
if (replayed != null)
throw new MslMessageException(replayed, messageHeader.toString());
}
} catch (final MslException e) {
if (this.header instanceof MessageHeader) {
final MessageHeader messageHeader = (MessageHeader)this.header;
e.setMasterToken(messageHeader.getMasterToken());
e.setEntityAuthenticationData(messageHeader.getEntityAuthenticationData());
e.setUserIdToken(messageHeader.getUserIdToken());
e.setUserAuthenticationData(messageHeader.getUserAuthenticationData());
e.setMessageId(messageHeader.getMessageId());
} else {
final ErrorHeader errorHeader = (ErrorHeader)this.header;
e.setEntityAuthenticationData(errorHeader.getEntityAuthenticationData());
e.setMessageId(errorHeader.getMessageId());
}
throw e;
}
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
// Do not close the source because we might want to reuse it.
super.finalize();
}
/**
* Retrieve the next MSL object.
*
* @return the next MSL object or null if none remaining.
* @throws MslEncodingException if there is a problem parsing the data.
*/
protected MslObject nextMslObject() throws MslEncodingException {
// Make sure this message is allowed to have payload chunks.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
throw new MslInternalException("Read attempted with error message.");
// If we previously reached the end of the message, don't try to read
// more.
if (eom)
return null;
// Otherwise read the next MSL object.
try {
if (!tokenizer.more(-1)) {
eom = true;
return null;
}
return tokenizer.nextObject(-1);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "payloadchunk", e);
}
}
/**
* Create a new payload chunk
*
* @param ctx the MSL context.
* @param mo the MSL object.
* @param cryptoContext the crypto context.
* @throws MslCryptoException if there is a problem decrypting or verifying
* the payload chunk.
* @throws MslEncodingException if there is a problem parsing the data.
* @throws MslMessageException if the compression algorithm is not known,
* or the payload data is corrupt or missing.
* @throws MslException if there is an error uncompressing the data.
*/
protected PayloadChunk createPayloadChunk(final MslContext ctx, final MslObject mo, final ICryptoContext cryptoContext) throws MslEncodingException, MslCryptoException, MslMessageException, MslException {
return new PayloadChunk(ctx, mo, cryptoContext);
}
/**
* Retrieve the next payload chunk data.
*
* @return the next payload chunk data or null if none remaining.
* @throws MslCryptoException if there is a problem decrypting or verifying
* the payload chunk.
* @throws MslEncodingException if there is a problem parsing the data.
* @throws MslMessageException if the payload verification failed.
* @throws MslInternalException if attempting to access payloads of an
* error message.
* @throws MslException if there is an error uncompressing the data.
*/
protected ByteArrayInputStream nextData() throws MslCryptoException, MslEncodingException, MslMessageException, MslInternalException, MslException {
// Make sure this message is allowed to have payload chunks.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
throw new MslInternalException("Read attempted with error message.");
// If reading buffered data return the next buffered payload data.
if (payloadIterator != null && payloadIterator.hasNext())
return payloadIterator.next();
// Otherwise read the next payload.
final MslObject mo = nextMslObject();
if (mo == null) return null;
final PayloadChunk payload = createPayloadChunk(ctx, mo, cryptoContext);
// Make sure the payload belongs to this message and is the one we are
// expecting.
final MasterToken masterToken = messageHeader.getMasterToken();
final EntityAuthenticationData entityAuthData = messageHeader.getEntityAuthenticationData();
final UserIdToken userIdToken = messageHeader.getUserIdToken();
final UserAuthenticationData userAuthData = messageHeader.getUserAuthenticationData();
if (payload.getMessageId() != messageHeader.getMessageId()) {
throw new MslMessageException(MslError.PAYLOAD_MESSAGE_ID_MISMATCH, "payload mid " + payload.getMessageId() + " header mid " + messageHeader.getMessageId())
.setMasterToken(masterToken)
.setEntityAuthenticationData(entityAuthData)
.setUserIdToken(userIdToken)
.setUserAuthenticationData(userAuthData);
}
if (payload.getSequenceNumber() != payloadSequenceNumber) {
throw new MslMessageException(MslError.PAYLOAD_SEQUENCE_NUMBER_MISMATCH, "payload seqno " + payload.getSequenceNumber() + " expected seqno " + payloadSequenceNumber)
.setMasterToken(masterToken)
.setEntityAuthenticationData(entityAuthData)
.setUserIdToken(userIdToken)
.setUserAuthenticationData(userAuthData);
}
++payloadSequenceNumber;
// FIXME remove this logic once the old handshake inference logic
// is no longer supported.
// Check for a handshake if this is the first payload chunk.
if (handshake == null) {
handshake = (messageHeader.isRenewable() && !messageHeader.getKeyRequestData().isEmpty() &&
payload.isEndOfMessage() && payload.getData().length == 0);
}
// Check for end of message.
if (payload.isEndOfMessage())
eom = true;
// If mark was called save the payload in the buffer. We have to unset
// the payload iterator since we're adding to the payloads list.
final ByteArrayInputStream data = new ByteArrayInputStream(payload.getData());
if (payloads != null) {
payloads.add(data);
payloadIterator = null;
}
return data;
}
/**
* Returns true if the message is a handshake message.
*
* FIXME
* This method should be removed by a direct query of the message header
* once the old behavior of inferred handshake messages based on a single
* empty payload chunk is no longer supported.
*
* @return true if the message is a handshake message.
* @throws MslCryptoException if there is a problem decrypting or verifying
* the payload chunk.
* @throws MslEncodingException if there is a problem parsing the data.
* @throws MslMessageException if the payload verification failed.
* @throws MslInternalException if attempting to access payloads of an
* error message.
* @throws MslException if there is an error uncompressing the data.
*/
public boolean isHandshake() throws MslCryptoException, MslEncodingException, MslMessageException, MslInternalException, MslException {
final MessageHeader messageHeader = getMessageHeader();
// Error messages are not handshake messages.
if (messageHeader == null) return false;
// If the message header has its handshake flag set return true.
if (messageHeader.isHandshake()) return true;
// If we haven't read a payload we don't know if this is a handshake
// message or not. This also implies the current payload is null.
if (handshake == null) {
try {
// nextData() will set the value of handshake if a payload is
// found.
currentPayload = nextData();
if (currentPayload == null)
handshake = Boolean.FALSE;
} catch (final MslException e) {
// Save the exception to be thrown next time read() is called.
readException = new IOException("Error reading the payload chunk.", e);
throw e;
}
}
// Return the current handshake status.
return handshake.booleanValue();
}
/**
* @return the message header. Will be null for error messages.
*/
public MessageHeader getMessageHeader() {
if (header instanceof MessageHeader)
return (MessageHeader)header;
return null;
}
/**
* @return the error header. Will be null except for error messages.
*/
public ErrorHeader getErrorHeader() {
if (header instanceof ErrorHeader)
return (ErrorHeader)header;
return null;
}
/**
* Returns the sender's entity identity. The identity will be unknown if
* the local entity is a trusted network client and the message was sent by
* a trusted network server using the local entity's master token.
*
* @return the sender's entity identity or null if unknown.
* @throws MslCryptoException if there is a crypto error accessing the
* entity identity;
*/
public String getIdentity() throws MslCryptoException {
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader != null) {
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
return masterToken.getIdentity();
return messageHeader.getEntityAuthenticationData().getIdentity();
}
final ErrorHeader errorHeader = getErrorHeader();
return errorHeader.getEntityAuthenticationData().getIdentity();
}
/**
* Returns the user associated with the message. The user will be unknown
* if the local entity is a trusted network client and the message was sent
* by a trusted network server.
*
* @return the user associated with the message or null if unknown.
*/
public MslUser getUser() {
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
return null;
return messageHeader.getUser();
}
/**
* @return the payload crypto context. Will be null for error messages.
*/
public ICryptoContext getPayloadCryptoContext() {
return cryptoContext;
}
/**
* @return the key exchange crypto context. Will be null if no key response
* data was returned in this message and for error messages.
*/
public ICryptoContext getKeyExchangeCryptoContext() {
return keyxCryptoContext;
}
/**
* Returns true if the payload application data is encrypted. This will be
* true if the entity authentication scheme provides encryption or if
* session keys were used. Returns false for error messages which do not
* have any payload chunks.
*
* @return true if the payload application data is encrypted. Will be false
* for error messages.
*/
public boolean encryptsPayloads() {
// Return false for error messages.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
return false;
// If the message uses entity authentication data for an entity
// authentication scheme that provides encryption, return true.
final EntityAuthenticationData entityAuthData = messageHeader.getEntityAuthenticationData();
if (entityAuthData != null && entityAuthData.getScheme().encrypts())
return true;
// If the message uses a master token, return true.
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
return true;
// If the message includes key response data, return true.
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null)
return true;
// Otherwise return false.
return false;
}
/**
* Returns true if the payload application data is integrity protected.
* This will be true if the entity authentication scheme provides integrity
* protection or if session keys were used. Returns false for error
* messages which do not have any payload chunks.
*
* @return true if the payload application data is integrity protected.
* Will be false for error messages.
*/
public boolean protectsPayloadIntegrity() {
// Return false for error messages.
final MessageHeader messageHeader = getMessageHeader();
if (messageHeader == null)
return false;
// If the message uses entity authentication data for an entity
// authentication scheme that provides integrity protection, return
// true.
final EntityAuthenticationData entityAuthData = messageHeader.getEntityAuthenticationData();
if (entityAuthData != null && entityAuthData.getScheme().protectsIntegrity())
return true;
// If the message uses a master token, return true.
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
return true;
// If the message includes key response data, return true.
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null)
return true;
// Otherwise return false.
return false;
}
/* (non-Javadoc)
* @see java.io.InputStream#available()
*/
@Override
public int available() throws IOException {
// Start with the amount available in the current payload.
if (currentPayload == null) return 0;
int available = currentPayload.available();
// If there is buffered data, iterate over all subsequent buffered
// payloads.
if (payloads != null) {
final int startIndex = payloads.indexOf(currentPayload);
if (startIndex != -1 && startIndex < payloads.size() - 1) {
final Iterator<ByteArrayInputStream> nextPayloads = payloads.listIterator(startIndex + 1);
while (nextPayloads.hasNext()) {
final ByteArrayInputStream payload = nextPayloads.next();
available += payload.available();
}
}
}
// Return available bytes.
return available;
}
/**
* By default the source input stream is not closed when this message input
* stream is closed. If it should be closed then this method can be used to
* dictate the desired behavior.
*
* @param close true if the source input stream should be closed, false if
* it should not.
*/
public void closeSource(final boolean close) {
this.closeSource = close;
}
/* (non-Javadoc)
* @see java.io.InputStream#close()
*/
@Override
public void close() throws IOException {
// Close the tokenizer.
try {
tokenizer.close();
} catch (final MslEncoderException e) {
// Ignore exceptions.
}
// Only close the source if instructed to do so because we might want
// to reuse the connection.
if (closeSource) {
source.close();
}
// Otherwise if this is not a handshake message or error message then
// consume all payloads that may still be on the source input stream.
else {
try {
if (!isHandshake() && getMessageHeader() != null) {
while (true) {
final ByteArrayInputStream data = nextData();
if (data == null) break;
}
}
} catch (final MslException e) {
// Ignore exceptions.
}
}
}
/* (non-Javadoc)
* @see java.io.InputStream#mark(int)
*/
@Override
public void mark(final int readlimit) {
// Remember the read limit, reset the read count.
this.readlimit = readlimit;
this.readcount = 0;
// Start buffering.
buffering = true;
// If there is a current payload...
if (currentPayload != null) {
// Remove all buffered data earlier than the current payload.
while (payloads.size() > 0 && !payloads.get(0).equals(currentPayload))
payloads.remove(0);
// Add the current payload if it was not already buffered.
if (payloads.size() == 0)
payloads.add(currentPayload);
// Reset the iterator to continue reading buffered data from the
// current payload.
payloadIterator = payloads.listIterator();
currentPayload = payloadIterator.next();
// Set the new mark point on the current payload.
currentPayload.mark(readlimit);
return;
}
// Otherwise we've either read to the end or haven't read anything at
// all yet. Discard all buffered data.
payloadIterator = null;
payloads.clear();
}
/* (non-Javadoc)
* @see java.io.InputStream#markSupported()
*/
@Override
public boolean markSupported() {
return true;
}
/* (non-Javadoc)
* @see java.io.InputStream#read()
*/
@Override
public int read() throws IOException {
final byte[] b = new byte[1];
if (read(b) == -1) return -1;
return b[0];
}
/* (non-Javadoc)
* @see java.io.InputStream#read(byte[], int, int)
*/
@Override
public int read(final byte[] cbuf, final int off, final int len) throws IOException {
// Throw any cached read exception.
if (readException != null) {
final IOException e = readException;
readException = null;
throw e;
}
// Return end of stream immediately for handshake messages.
try {
if (this.isHandshake())
return -1;
} catch (final MslException e) {
// FIXME
// Unset the read exception since we are going to throw it right
// now. This logic can go away once the old handshake logic is
// removed.
readException = null;
throw new IOException("Error reading the payload chunk.", e);
}
// Read from payloads until we are done or cannot read anymore.
int bytesRead = 0;
while (bytesRead < len) {
final int read = (currentPayload != null) ? currentPayload.read(cbuf, off + bytesRead, len - bytesRead) : -1;
// If we read some data continue.
if (read != -1) {
bytesRead += read;
continue;
}
// Otherwise grab the next payload data.
try {
currentPayload = nextData();
if (currentPayload == null)
break;
} catch (final MslException e) {
// If we already read some data return it and save the
// exception to be thrown next time read() is called.
final IOException ioe = new IOException("Error reading the payload chunk.", e);
if (bytesRead > 0) {
readException = ioe;
return bytesRead;
}
// Otherwise throw the exception now.
throw ioe;
}
}
// If nothing was read (but something was requested) return end of
// stream.
if (bytesRead == 0 && len > 0)
return -1;
// If buffering data increment the read count.
if (buffering) {
readcount += bytesRead;
// If the read count exceeds the read limit stop buffering payloads
// and reset the read count and limit, but retain the payload
// iterator as we need to continue reading from any buffered data.
if (readcount > readlimit) {
buffering = false;
readcount = readlimit = 0;
}
}
// Return the number of bytes read.
return bytesRead;
}
/* (non-Javadoc)
* @see java.io.InputStream#read(byte[])
*/
@Override
public int read(final byte[] cbuf) throws IOException {
return read(cbuf, 0, cbuf.length);
}
/* (non-Javadoc)
* @see java.io.InputStream#reset()
*/
@Override
public void reset() throws IOException {
// Do nothing if we are not buffering.
if (!buffering)
return;
// Reset all payloads and initialize the payload iterator.
//
// We need to reset the payloads since we are going to re-read them and
// want the correct value returned when queried for available bytes.
for (final ByteArrayInputStream payload : payloads)
payload.reset();
payloadIterator = payloads.listIterator();
if (payloadIterator.hasNext()) {
currentPayload = payloadIterator.next();
} else {
currentPayload = null;
}
// Reset the read count.
readcount = 0;
}
/* (non-Javadoc)
* @see java.io.InputStream#skip(long)
*/
@Override
public long skip(final long n) throws IOException {
// Skip from payloads until we are done or cannot skip anymore.
int bytesSkipped = 0;
while (bytesSkipped < n) {
final long skipped = (currentPayload != null) ? currentPayload.skip(n - bytesSkipped) : 0;
// If we skipped some data continue.
if (skipped != 0) {
bytesSkipped += skipped;
continue;
}
// Otherwise grab the next payload data.
try {
currentPayload = nextData();
if (currentPayload == null)
break;
} catch (final MslInternalException e) {
throw new IOException("Cannot skip data off an error message.", e);
} catch (final MslException e) {
throw new IOException("Error skipping in the payload chunk.", e);
}
}
return bytesSkipped;
}
/** MSL context. */
private final MslContext ctx;
/** MSL input stream. */
private final InputStream source;
/** MSL tokenizer. */
private final MslTokenizer tokenizer;
/** Header. */
private final Header header;
/** Payload crypto context. */
private final ICryptoContext cryptoContext;
/** Key exchange crypto context. */
private final ICryptoContext keyxCryptoContext;
/** Current payload sequence number. */
private long payloadSequenceNumber = 1;
/** End of message reached. */
private boolean eom = false;
/** Handshake message. */
private Boolean handshake = null;
/** True if the source input stream should be closed. */
private boolean closeSource = false;
/** True if buffering. */
private boolean buffering = false;
/**
* Buffered payload data.
*
* This list contains all payload data that has been referenced since the
* last call to {@link #mark(int)}.
*/
private final List<ByteArrayInputStream> payloads = new LinkedList<ByteArrayInputStream>();;
/** Buffered payload data iterator. Not null if reading buffered data. */
private ListIterator<ByteArrayInputStream> payloadIterator = null;
/** Mark read limit. */
private int readlimit = 0;
/** Mark read count. */
private int readcount = 0;
/** Current payload chunk data. */
private ByteArrayInputStream currentPayload = null;
/** Cached read exception. */
private IOException readException = null;
}
| 9,852 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageContext.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslConstants.ResponseCode;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* <p>The message context provides the information that should be used to
* construct a single message. Each message should have its own context.</p>
*
* <p>All context methods may be called multiple times except for
* {@code #write(OutputStream)} which is guaranteed to be called only once.
* (The written data will be cached in memory in case the message needs to be
* resent.)</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public interface MessageContext {
/** Re-authentication reason codes. */
public static enum ReauthCode {
/** The user authentication data did not identify a user. */
USERDATA_REAUTH(ResponseCode.USERDATA_REAUTH),
/** The single-sign-on token was rejected as bad, invalid, or expired. */
SSOTOKEN_REJECTED(ResponseCode.SSOTOKEN_REJECTED),
;
/**
* @return the re-authentication code corresponding to the response
* code.
* @throws IllegalArgumentException if the response code does not map
* onto a re-authentication code.
*/
public static ReauthCode valueOf(final ResponseCode code) {
for (final ReauthCode value : ReauthCode.values()) {
if (value.code == code)
return value;
}
throw new IllegalArgumentException("Unknown reauthentication code value " + code + ".");
}
/**
* Create a new re-authentication code mapped from the specified
* response code.
*
* @param code the response code for the re-authentication code.
*/
private ReauthCode(final ResponseCode code) {
this.code = code;
}
/**
* @return the integer value of the response code.
*/
public int intValue() {
return code.intValue();
}
/** The response code value. */
private final ResponseCode code;
}
/**
* <p>Called when receiving a message to process service tokens.</p>
*
* <p>This method should return a map of crypto contexts by service token
* name for all known service tokens. If the service token name is not
* found then the crypto context mapped onto the empty string will be
* used if found.</p>
*
* @return the service token crypto contexts.
*/
public Map<String,ICryptoContext> getCryptoContexts();
/**
* <p>Called to identify the expected remote entity identity. If the remote
* entity identity is not known this method must return {@code null}.</p>
*
* <p>Trusted network servers may always return {@code null}.</p>
*
* @return the remote entity identity or {@code null} if the identity is
* not known.
*/
public String getRemoteEntityIdentity();
/**
* <p>Called to determine if the message application data must be
* encrypted.</p>
*
* @return true if the application data must be encrypted.
*/
public boolean isEncrypted();
/**
* <p>Called to determine if the message application data must be integrity
* protected.</p>
*
* @return true if the application data must be integrity protected.
*/
public boolean isIntegrityProtected();
/**
* <p>Called to determine if a message should be marked as non-replayable.</p>
*
* <p>Trusted network servers must always return {@code false}.</p>
*
* @return true if the application data should not be carried in a
* replayable message.
*/
public boolean isNonReplayable();
/**
* <p>Called to determine if a message is requesting a master token, user
* ID token, or service tokens.</p>
*
* <p>Trusted network servers must always return {@code false}.</p>
*
* @return true if the message must have a master token and user ID token
* (if associated with a user) or must be carried in a renewable
* message to acquire said tokens.
*/
public boolean isRequestingTokens();
/**
* <p>Called to identify the local user the message should be sent with. If
* a user ID token exists for this user it will be used.</p>
*
* <p>Trusted network servers must always return {@code null}.</p>
*
* <p>Any non-null value returned by this method must match the local user
* associated with the user authentication data returned by
* {@link #getUserAuthData(ReauthCode, boolean, boolean)}.</p>
*
* <p>This method may return a non-null value when
* {@link #getUserAuthData(ReauthCode, boolean, boolean)} will return null
* if the message should be associated with a user but there is no user
* authentication data. For example during new user creation.</p>
*
* <p>This method must return {@code null} if the message should not be
* associated with a user and
* {@link #getUserAuthData(ReauthCode, boolean, boolean)} will also return
* {@code null}.</p>
*
* @return the local user identity or null.
*/
public String getUserId();
/**
* <p>Called if the user ID is not {@code null} to attach user
* authentication data to messages.</p>
*
* <p>Trusted network servers must always return {@code null}.</p>
*
* <p>This method should return user authentication data if the message
* should be associated with a user that has not already received a user ID
* token. This may involve prompting the user for credentials. If the
* message should not be associated with a user, a user ID token already
* exists for the user, or if user credentials are unavailable then this
* method should return {@code null}.</p>
*
* <p>The one exception is if the application wishes to re-authenticate the
* user against the current user ID token in which case this method should
* return user authentication data. The {@code renewable} parameter may be
* used to limit this operation to renewable messages.</p>
*
* <p>This method may be called if user re-authentication is required for
* the transaction to complete. If the application knows that user
* authentication is required for the request being sent and is unable to
* provide user authentication data then it should attempt to cancel the
* request and return {@code null}.</p>
*
* <p>If the {@code reauthCode} parameter is non-{@code null} then new user
* authentication data should be returned for this and all subsequent calls.
* The application may wish to return {@code null} if it knows that the
* request being sent can no longer succeed because the existing user ID
* token or service tokens are no longer valid. This will abort the
* request. Note that a {@code reauthCode} argument may be provided even if
* no user authentication data was included in the message.</p>
*
* <p>If the {@code required} parameter is true then user authentication
* should be returned for this call, even if a user ID token already exists
* for the user. {@code null} should still be returned when {@code required}
* is true if the message should be associated with a user but there is no
* user authentication data. For example during new user creation.</p>
*
* <p>This method will be called multiple times.</p>
*
* @param reauthCode non-{@code null} if new user authentication data is
* required. The reason the old user authentication data was
* rejected is identified by the code.
* @param renewable true if the message being sent is renewable.
* @param required true if user authentication data must be returned.
* @return the user authentication data or null.
*/
public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required);
/**
* <p>Called if a message does not contain a user ID token for the remote
* user.</p>
*
* <p>Trusted network clients must always return {@code null}.</p>
*
* <p>If a non-null value is returned by this method and a master token
* exists for the remote entity then a new user ID token will be created
* for the remote user and sent in the message. This is not the user
* identified by {@link #getUserId()} or authenticated by
* {@link #getUserAuthData(ReauthCode, boolean, boolean)} as those methods
* are used for the local user.</p>
*
* @return the user to attach to the message or null.
*/
public MslUser getUser();
/**
* <p>Called if a request is eligible for key exchange (i.e. the request
* is renewable and contains entity authentication data or a renewable
* master token).</p>
*
* <p>Trusted network servers must always return the empty set.</p>
*
* <p>This method must return key request data for all supported key
* exchange schemes. Failure to provide any key request data may result in
* message delivery failures.</p>
*
* <p>This method may also be called if entity re-authentication is required
* for the transaction to complete.</p>
*
* @return the key request data. May be the empty set.
* @throws MslKeyExchangeException if there is an error generating the key
* request data.
*/
public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException;
/**
* <p>Called prior to message sending to allow the processor to modify the
* message being built.</p>
*
* <p>The boolean {@code handshake} will be true if the function is being
* called for a handshake message that must be sent before the application
* data can be sent. The builder for handshake messages may lack a master
* token, user ID token, and other bound service tokens.</p>
*
* <p>The processor must not attempt to access or retain a reference to the
* builder after this function completes.</p>
*
* <p>This method will be called multiple times. The set of service tokens
* managed by the provided message service token builder may be different
* for each call. The processor should treat each call to this method
* independently from each other.</p>
*
* @param builder message service token builder.
* @param handshake true if the provided builder is for a handshake message.
* @throws MslMessageException if the builder throws an exception or the
* desired service tokens cannot be attached.
* @throws MslCryptoException if there is an error encrypting or signing
* the service token data.
* @throws MslEncodingException if there is an error encoding the service
* token JSON data.
* @throws MslException if there is an error compressing the data.
* @see com.netflix.msl.MslError#RESPONSE_REQUIRES_MASTERTOKEN
* @see com.netflix.msl.MslError#RESPONSE_REQUIRES_USERIDTOKEN
*/
public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) throws MslMessageException, MslCryptoException, MslEncodingException, MslException;
/**
* <p>Called when the message is ready to be sent. The processor should
* use the provided {@code MessageOutputStream} to write its application
* data. This method will only be called once.</p>
*
* <p>The processor must not attempt to access or retain a reference to the
* message output stream after this function completes. It is okay for this
* method to be long-running as the data will be streamed.</p>
*
* <p>If application data must be sent before the remote entity can reply
* then this method must call {@link MessageOutputStream#flush()} before
* returning. If all of the application data must be sent before the remote
* entity can reply then this method must call
* {@link MessageOutputStream#close()} before returning. Closing the
* message output stream will prevent further use of the output stream
* returned by {@link MslControl}.</p>
*
* @param output message output stream.
* @throws IOException if the output stream throws an I/O exception.
*/
public void write(final MessageOutputStream output) throws IOException;
/**
* Returns a message debug context applicable to the message being sent or
* received.
*
* @return the message debug context or {@code null} if there is none.
*/
public MessageDebugContext getDebugContext();
}
| 9,853 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/ResponseMessageBuilder.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeFactory.KeyExchangeData;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.MslContext;
/**
* <p>Response message builder.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class ResponseMessageBuilder extends MessageBuilder {
/**
* Issue a new master token for the specified identity or renew an existing
* master token.
*
* @param ctx MSL context.
* @param format MSL encoder format.
* @param keyRequestData available key request data.
* @param masterToken master token to renew. Null if the identity is
* provided.
* @param entityAuthData entity authentication data. Null if a master token
* is provided.
* @return the new master token and crypto context or {@code} null if the
* factory chooses not to perform key exchange.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created or none
* of the key exchange schemes are supported.
* @throws MslMasterTokenException if the master token is not trusted.
* @throws MslEntityAuthException if there is a problem with the master
* token identity or entity identity.
* @throws MslException if there is an error creating or renewing the
* master token.
*/
private static KeyExchangeData issueMasterToken(final MslContext ctx, final MslEncoderFormat format, final Set<KeyRequestData> keyRequestData, final MasterToken masterToken, final EntityAuthenticationData entityAuthData) throws MslKeyExchangeException, MslCryptoException, MslMasterTokenException, MslEntityAuthException, MslException {
// Attempt key exchange in the preferred order.
MslException keyxException = null;
final Iterator<KeyExchangeFactory> factories = ctx.getKeyExchangeFactories().iterator();
while (factories.hasNext()) {
final KeyExchangeFactory factory = factories.next();
for (final KeyRequestData request : keyRequestData) {
if (!factory.getScheme().equals(request.getKeyExchangeScheme()))
continue;
// Attempt the key exchange, but if it fails try with the next
// combination before giving up.
try {
if (masterToken != null)
return factory.generateResponse(ctx, format, request, masterToken);
else
return factory.generateResponse(ctx, format, request, entityAuthData);
} catch (final MslCryptoException e) {
if (!factories.hasNext()) throw e;
keyxException = e;
} catch (final MslKeyExchangeException e) {
if (!factories.hasNext()) throw e;
keyxException = e;
} catch (final MslEncodingException e) {
if (!factories.hasNext()) throw e;
keyxException = e;
} catch (final MslMasterTokenException e) {
if (!factories.hasNext()) throw e;
keyxException = e;
} catch (final MslEntityAuthException e) {
if (!factories.hasNext()) throw e;
keyxException = e;
}
}
}
// We did not perform a successful key exchange. If we caught an
// exception then throw that exception now.
if (keyxException != null) {
if (keyxException instanceof MslCryptoException)
throw (MslCryptoException)keyxException;
if (keyxException instanceof MslKeyExchangeException)
throw (MslKeyExchangeException)keyxException;
if (keyxException instanceof MslEncodingException)
throw (MslEncodingException)keyxException;
if (keyxException instanceof MslMasterTokenException)
throw (MslMasterTokenException)keyxException;
if (keyxException instanceof MslEntityAuthException)
throw (MslEntityAuthException)keyxException;
throw new MslInternalException("Unexpected exception caught during key exchange.", keyxException);
}
// If we didn't find any then we're unable to perform key exchange.
throw new MslKeyExchangeException(MslError.KEYX_FACTORY_NOT_FOUND, Arrays.toString(keyRequestData.toArray()));
}
/**
* Create a new message builder that will craft a new message in response
* to another message. The constructed message may be used as a request.
*
* @param ctx MSL context.
* @param requestHeader message header to respond to.
* @throws MslMasterTokenException if the provided message's master token
* is not trusted.
* @throws MslCryptoException if the crypto context from a key exchange
* cannot be created.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created.
* @throws MslUserAuthException if there is an error with the user
* authentication data or the user ID token cannot be created.
* @throws MslException if a user ID token in the message header is not
* bound to its corresponding master token or there is an error
* creating or renewing the master token.
*/
public ResponseMessageBuilder(final MslContext ctx, final MessageHeader requestHeader) throws MslKeyExchangeException, MslCryptoException, MslMasterTokenException, MslUserAuthException, MslException {
super(ctx);
final MasterToken masterToken = requestHeader.getMasterToken();
final EntityAuthenticationData entityAuthData = requestHeader.getEntityAuthenticationData();
UserIdToken userIdToken = requestHeader.getUserIdToken();
final UserAuthenticationData userAuthData = requestHeader.getUserAuthenticationData();
// The response message ID must be equal to the request message ID + 1.
final long requestMessageId = requestHeader.getMessageId();
final long messageId = incrementMessageId(requestMessageId);
// Compute the intersection of the request and response message
// capabilities.
final MessageCapabilities capabilities = MessageCapabilities.intersection(requestHeader.getMessageCapabilities(), ctx.getMessageCapabilities());
// Identify the response format.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final Set<MslEncoderFormat> formats = (capabilities != null) ? capabilities.getEncoderFormats() : null;
final MslEncoderFormat format = encoder.getPreferredFormat(formats);
try {
// If the message contains key request data and is renewable...
final KeyExchangeData keyExchangeData;
final Set<KeyRequestData> keyRequestData = requestHeader.getKeyRequestData();
if (requestHeader.isRenewable() && !keyRequestData.isEmpty()) {
// If the message contains a master token...
if (masterToken != null) {
// If the master token is renewable or expired then renew
// the master token.
if (masterToken.isRenewable(null) || masterToken.isExpired(null))
keyExchangeData = issueMasterToken(ctx, format, keyRequestData, masterToken, null);
// Otherwise we don't need to do anything special.
else
keyExchangeData = null;
}
// Otherwise use the entity authentication data to issue a
// master token.
else {
// The message header is already authenticated via the
// entity authentication data's crypto context so we can
// simply proceed with the master token issuance.
keyExchangeData = issueMasterToken(ctx, format, keyRequestData, null, entityAuthData);
}
}
// If the message does not contain key request data there is no key
// exchange for us to do.
else {
keyExchangeData = null;
}
// If we successfully performed key exchange, use the new master
// token for user authentication.
final MasterToken userAuthMasterToken;
if (keyExchangeData != null) {
userAuthMasterToken = keyExchangeData.keyResponseData.getMasterToken();
} else {
userAuthMasterToken = masterToken;
}
// If the message contains a user ID token issued by the local
// entity...
if (userIdToken != null && userIdToken.isVerified()) {
// If the user ID token is renewable and the message is
// renewable, or it is expired, or it needs to be rebound
// to the new master token then renew the user ID token.
if ((userIdToken.isRenewable(null) && requestHeader.isRenewable()) ||
userIdToken.isExpired(null) ||
!userIdToken.isBoundTo(userAuthMasterToken))
{
final TokenFactory tokenFactory = ctx.getTokenFactory();
userIdToken = tokenFactory.renewUserIdToken(ctx, userIdToken, userAuthMasterToken);
}
}
// If the message is renewable and contains user authentication
// data and a master token then we need to attempt user
// authentication and issue a user ID token.
else if (requestHeader.isRenewable() && userAuthMasterToken != null && userAuthData != null) {
// If this request was parsed then its user authentication data
// should have been authenticated and the user will exist. If
// it was not parsed, then we need to perform user
// authentication now.
MslUser user = requestHeader.getUser();
if (user == null) {
final UserAuthenticationScheme scheme = userAuthData.getScheme();
final UserAuthenticationFactory factory = ctx.getUserAuthenticationFactory(scheme);
if (factory == null) {
throw new MslUserAuthException(MslError.USERAUTH_FACTORY_NOT_FOUND, scheme.name())
.setMasterToken(masterToken)
.setUserAuthenticationData(userAuthData)
.setMessageId(requestMessageId);
}
user = factory.authenticate(ctx, userAuthMasterToken.getIdentity(), userAuthData, null);
}
final TokenFactory tokenFactory = ctx.getTokenFactory();
userIdToken = tokenFactory.createUserIdToken(ctx, user, userAuthMasterToken);
}
// Create the message builder.
//
// Peer-to-peer responses swap the tokens.
final KeyResponseData keyResponseData = requestHeader.getKeyResponseData();
final Set<ServiceToken> serviceTokens = requestHeader.getServiceTokens();
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
final Set<ServiceToken> peerServiceTokens = requestHeader.getPeerServiceTokens();
initializeMessageBuilder(ctx, messageId, capabilities, peerMasterToken, peerUserIdToken, peerServiceTokens, masterToken, userIdToken, serviceTokens, keyExchangeData);
} else {
final MasterToken localMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : masterToken;
initializeMessageBuilder(ctx, messageId, capabilities, localMasterToken, userIdToken, serviceTokens, null, null, null, keyExchangeData);
}
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setUserIdToken(userIdToken);
e.setUserAuthenticationData(userAuthData);
e.setMessageId(requestMessageId);
throw e;
}
}
/**
* Create a new message builder that will craft a new message in response
* to another message without issuing or renewing any master tokens or user
* ID tokens. The constructed message may be used as a request.
*
* @param ctx MSL context.
* @param requestHeader message header to respond to.
* @throws MslCryptoException if there is an error accessing the remote
* entity identity.
* @throws MslException if any of the request's user ID tokens is not bound
* to its master token.
*/
public void createIdempotentResponse(final MslContext ctx, final MessageHeader requestHeader) throws MslCryptoException, MslException {
final MasterToken masterToken = requestHeader.getMasterToken();
final EntityAuthenticationData entityAuthData = requestHeader.getEntityAuthenticationData();
final UserIdToken userIdToken = requestHeader.getUserIdToken();
final UserAuthenticationData userAuthData = requestHeader.getUserAuthenticationData();
// The response message ID must be equal to the request message ID + 1.
final long requestMessageId = requestHeader.getMessageId();
final long messageId = incrementMessageId(requestMessageId);
// Compute the intersection of the request and response message
// capabilities.
final MessageCapabilities capabilities = MessageCapabilities.intersection(requestHeader.getMessageCapabilities(), ctx.getMessageCapabilities());
// Create the message builder.
//
// Peer-to-peer responses swap the tokens.
try {
final KeyResponseData keyResponseData = requestHeader.getKeyResponseData();
final Set<ServiceToken> serviceTokens = requestHeader.getServiceTokens();
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
final Set<ServiceToken> peerServiceTokens = requestHeader.getPeerServiceTokens();
initializeMessageBuilder(ctx, messageId, capabilities, peerMasterToken, peerUserIdToken, peerServiceTokens, masterToken, userIdToken, serviceTokens, null);
} else {
final MasterToken localMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : masterToken;
initializeMessageBuilder(ctx, messageId, capabilities, localMasterToken, userIdToken, serviceTokens, null, null, null, null);
}
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setUserIdToken(userIdToken);
e.setUserAuthenticationData(userAuthData);
e.setMessageId(requestMessageId);
throw e;
}
}
}
| 9,854 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageBuilder.java | /**
* Copyright (c) 2012-2020 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.crypto.NullCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.keyx.KeyExchangeFactory.KeyExchangeData;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.msg.MessageHeader.HeaderData;
import com.netflix.msl.msg.MessageHeader.HeaderPeerData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslUtils;
/**
* <p>A message builder provides methods for building messages.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MessageBuilder {
/** Empty service token data. */
private static final byte[] EMPTY_DATA = new byte[0];
/**
* Increments the provided message ID by 1, wrapping around to zero if
* the provided value is equal to {@link MslConstants#MAX_LONG_VALUE}.
*
* @param messageId the message ID to increment.
* @return the message ID + 1.
* @throws MslInternalException if the provided message ID is out of range.
*/
public static long incrementMessageId(final long messageId) {
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is outside the valid range.");
return (messageId == MslConstants.MAX_LONG_VALUE) ? 0 : messageId + 1;
}
/**
* Decrements the provided message ID by 1, wrapping around to
* {@link MslConstants#MAX_LONG_VALUE} if the provided value is equal to 0.
*
* @param messageId the message ID to decrement.
* @return the message ID - 1.
* @throws MslInternalException if the provided message ID is out of range.
*/
public static long decrementMessageId(final long messageId) {
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is outside the valid range.");
return (messageId == 0) ? MslConstants.MAX_LONG_VALUE : messageId - 1;
}
/**
* <p>Create a new message builder.</p>
*
* @param ctx MSL context.
*/
protected MessageBuilder(final MslContext ctx) {
this.ctx = ctx;
}
/**
* <p>Create a new message builder that will craft a new message with the
* specified message ID.</p>
*
* @param ctx MSL context.
* @param masterToken master token. May be null unless a user ID token is
* provided.
* @param userIdToken user ID token. May be null.
* @param messageId the message ID to use. Must be within range.
* @throws MslException if a user ID token is not bound to its
* corresponding master token.
*/
public MessageBuilder(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken, final long messageId) throws MslException {
this.ctx = ctx;
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is outside the valid range.");
final MessageCapabilities capabilities = ctx.getMessageCapabilities();
initializeMessageBuilder(ctx, messageId, capabilities, masterToken, userIdToken, null, null, null, null, null);
}
/**
* <p>Create a new message builder that will craft a new message.</p>
*
* @param ctx MSL context.
* @param masterToken master token. May be null unless a user ID token is
* provided.
* @param userIdToken user ID token. May be null.
* @throws MslException if a user ID token is not bound to its
* corresponding master token.
*/
public MessageBuilder(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
this(ctx, masterToken, userIdToken, MslUtils.getRandomLong(ctx));
}
/**
* Initialize a message builder with the provided tokens and key exchange
* data if a master token was issued or renewed.
*
* @param ctx MSL context.
* @param messageId message ID.
* @param capabilities message capabilities.
* @param masterToken master token. May be null unless a user ID token is
* provided.
* @param userIdToken user ID token. May be null.
* @param serviceTokens initial set of service tokens. May be null.
* @param peerMasterToken peer master token. May be null unless a peer user
* ID token is provided.
* @param peerUserIdToken peer user ID token. May be null.
* @param peerServiceTokens initial set of peer service tokens.
* May be null.
* @param keyExchangeData key exchange data. May be null.
* @throws MslException if a user ID token is not bound to its master
* token.
*/
protected void initializeMessageBuilder(final MslContext ctx, final long messageId, final MessageCapabilities capabilities, final MasterToken masterToken, final UserIdToken userIdToken, final Set<ServiceToken> serviceTokens, final MasterToken peerMasterToken, final UserIdToken peerUserIdToken, final Set<ServiceToken> peerServiceTokens, final KeyExchangeData keyExchangeData) throws MslException {
// Primary and peer token combinations will be verified when the
// message header is constructed. So delay those checks in favor of
// avoiding duplicate code.
if (!ctx.isPeerToPeer() && (peerMasterToken != null || peerUserIdToken != null))
throw new MslInternalException("Cannot set peer master token or peer user ID token when not in peer-to-peer mode.");
// Set the primary fields.
this.messageId = messageId;
this.capabilities = capabilities;
this.masterToken = masterToken;
this.userIdToken = userIdToken;
this.keyExchangeData = keyExchangeData;
// If key exchange data is provided and we are not in peer-to-peer mode
// then its master token should be used for querying service tokens.
final MasterToken serviceMasterToken;
if (keyExchangeData != null && !ctx.isPeerToPeer()) {
serviceMasterToken = keyExchangeData.keyResponseData.getMasterToken();
} else {
serviceMasterToken = masterToken;
}
// Set the initial service tokens based on the MSL store and provided
// service tokens.
final Set<ServiceToken> tokens = ctx.getMslStore().getServiceTokens(serviceMasterToken, userIdToken);
this.serviceTokens.addAll(tokens);
if (serviceTokens != null) {
for (final ServiceToken token : serviceTokens) {
// Make sure the service token is properly bound.
if (token.isMasterTokenBound() && !token.isBoundTo(serviceMasterToken))
throw new MslMessageException(MslError.SERVICETOKEN_MASTERTOKEN_MISMATCH, "st " + token + "; mt " + serviceMasterToken).setMasterToken(serviceMasterToken);
if (token.isUserIdTokenBound() && !token.isBoundTo(userIdToken))
throw new MslMessageException(MslError.SERVICETOKEN_USERIDTOKEN_MISMATCH, "st " + token + "; uit " + userIdToken).setMasterToken(serviceMasterToken).setUserIdToken(userIdToken);
// Add the service token.
this.serviceTokens.add(token);
}
}
// Set the peer-to-peer data.
if (ctx.isPeerToPeer()) {
this.peerMasterToken = peerMasterToken;
this.peerUserIdToken = peerUserIdToken;
// If key exchange data is provided then its master token should
// be used to query peer service tokens.
final MasterToken peerServiceMasterToken;
if (keyExchangeData != null)
peerServiceMasterToken = keyExchangeData.keyResponseData.getMasterToken();
else
peerServiceMasterToken = this.peerMasterToken;
// Set the initial peer service tokens based on the MSL store and
// provided peer service tokens.
final Set<ServiceToken> peerTokens = ctx.getMslStore().getServiceTokens(peerServiceMasterToken, peerUserIdToken);
this.peerServiceTokens.addAll(peerTokens);
if (peerServiceTokens != null) {
for (final ServiceToken peerToken : peerServiceTokens) {
// Make sure the service token is properly bound.
if (peerToken.isMasterTokenBound() && !peerToken.isBoundTo(peerMasterToken))
throw new MslMessageException(MslError.SERVICETOKEN_MASTERTOKEN_MISMATCH, "st " + peerToken + "; mt " + peerMasterToken).setMasterToken(peerMasterToken);
if (peerToken.isUserIdTokenBound() && !peerToken.isBoundTo(peerUserIdToken))
throw new MslMessageException(MslError.SERVICETOKEN_USERIDTOKEN_MISMATCH, "st " + peerToken + "; uit " + peerUserIdToken).setMasterToken(peerMasterToken).setUserIdToken(peerUserIdToken);
// Add the peer service token.
this.peerServiceTokens.add(peerToken);
}
}
}
}
/**
* @return the message ID the builder will use.
*/
public long getMessageId() {
return messageId;
}
/**
* @return the primary master token or null if the message will use entity
* authentication data.
*/
public MasterToken getMasterToken() {
return masterToken;
}
/**
* @return the primary user ID token or null if the message will use user
* authentication data.
*/
public UserIdToken getUserIdToken() {
return userIdToken;
}
/**
* @return the key exchange data or null if there is none.
*/
public KeyExchangeData getKeyExchangeData() {
return keyExchangeData;
}
/**
* @return true if the message builder will create a message capable of
* encrypting the header data.
*/
public boolean willEncryptHeader() {
final EntityAuthenticationScheme scheme = ctx.getEntityAuthenticationData(null).getScheme();
return masterToken != null || scheme.encrypts();
}
/**
* @return true if the message builder will create a message capable of
* encrypting the payload data.
*/
public boolean willEncryptPayloads() {
final EntityAuthenticationScheme scheme = ctx.getEntityAuthenticationData(null).getScheme();
return masterToken != null ||
(!ctx.isPeerToPeer() && keyExchangeData != null) ||
scheme.encrypts();
}
/**
* @return true if the message builder will create a message capable of
* integrity protecting the header data.
*/
public boolean willIntegrityProtectHeader() {
final EntityAuthenticationScheme scheme = ctx.getEntityAuthenticationData(null).getScheme();
return masterToken != null || scheme.protectsIntegrity();
}
/**
* @return true if the message builder will create a message capable of
* integrity protecting the payload data.
*/
public boolean willIntegrityProtectPayloads() {
final EntityAuthenticationScheme scheme = ctx.getEntityAuthenticationData(null).getScheme();
return masterToken != null ||
(!ctx.isPeerToPeer() && keyExchangeData != null) ||
scheme.protectsIntegrity();
}
/**
* Construct the message header from the current message builder state.
*
* @return the message header.
* @throws MslCryptoException if there is an error encrypting or signing
* the message.
* @throws MslMasterTokenException if the header master token is not
* trusted and needs to be to accept this message header.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
* @throws MslMessageException if the message is non-replayable but does
* not include a master token.
* @throws MslException should not happen.
*/
public MessageHeader getHeader() throws MslCryptoException, MslMasterTokenException, MslEntityAuthException, MslMessageException, MslException {
final KeyResponseData response = (keyExchangeData != null) ? keyExchangeData.keyResponseData : null;
final Long nonReplayableId;
if (nonReplayable) {
if (masterToken == null)
throw new MslMessageException(MslError.NONREPLAYABLE_MESSAGE_REQUIRES_MASTERTOKEN);
nonReplayableId = ctx.getMslStore().getNonReplayableId(masterToken);
} else {
nonReplayableId = null;
}
final HeaderData headerData = new HeaderData(messageId, nonReplayableId, renewable, handshake, capabilities, keyRequestData, response, userAuthData, userIdToken, serviceTokens);
final HeaderPeerData peerData = new HeaderPeerData(peerMasterToken, peerUserIdToken, peerServiceTokens);
return createMessageHeader(ctx, ctx.getEntityAuthenticationData(null), masterToken, headerData, peerData);
}
/**
* Construct a new message header
*
* @param ctx MSL context.
* @param entityAuthData entity authentication data. Null if a master token is provided.
* @param masterToken master token to renew. Null if the identity is provided.
* @param headerData message header data container.
* @param peerData message header peer data container.
* @return the message header.
*/
protected MessageHeader createMessageHeader(final MslContext ctx, final EntityAuthenticationData entityAuthData, final MasterToken masterToken, final HeaderData headerData, final HeaderPeerData peerData) throws MslException, MslCryptoException {
return new MessageHeader(ctx, entityAuthData, masterToken, headerData, peerData);
}
/**
* <p>Set the message ID.</p>
*
* <p>This method will override the message ID that was computed when the
* message builder was created, and should not need to be called in most
* cases.</p>
*
* @param messageId the message ID.
* @return this.
* @throws MslInternalException if the message ID is out of range.
*/
public MessageBuilder setMessageId(final long messageId) {
if (messageId < 0 || messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + messageId + " is out of range.");
this.messageId = messageId;
return this;
}
/**
* @return true if the message will be marked non-replayable.
*/
public boolean isNonReplayable() {
return nonReplayable;
}
/**
* Make the message non-replayable. If true this will also set the
* handshake flag to false.
*
* @param nonReplayable true if the message should be non-replayable.
* @return this.
* @see #setHandshake(boolean)
*/
public MessageBuilder setNonReplayable(final boolean nonReplayable) {
this.nonReplayable = nonReplayable;
if (this.nonReplayable)
this.handshake = false;
return this;
}
/**
* @return true if the message will be marked renewable.
*/
public boolean isRenewable() {
return renewable;
}
/**
* Set the message renewable flag. If false this will also set the
* handshake flag to false.
*
* @param renewable true if the message is renewable.
* @return this.
* @see #setHandshake(boolean)
*/
public MessageBuilder setRenewable(final boolean renewable) {
this.renewable = renewable;
if (!this.renewable)
this.handshake = false;
return this;
}
/**
* @return true if the message will be marked as a handshake message.
*/
public boolean isHandshake() {
return handshake;
}
/**
* Set the message handshake flag. If true this will also set the non-
* replayable flag to false and the renewable flag to true.
*
* @param handshake true if the message is a handshake message.
* @return this.
* @see #setNonReplayable(boolean)
* @see #setRenewable(boolean)
*/
public MessageBuilder setHandshake(final boolean handshake) {
this.handshake = handshake;
if (this.handshake) {
this.nonReplayable = false;
this.renewable = true;
}
return this;
}
/**
* <p>Set or change the master token and user ID token. This will overwrite
* any existing tokens. If the user ID token is not null then any existing
* user authentication data will be removed.</p>
*
* <p>Changing these tokens may result in invalidation of existing service
* tokens. Those service tokens will be removed from the message being
* built.</p>
*
* <p>This is a special method for the {@link MslControl} class that assumes
* the builder does not have key response data in trusted network mode.</p>
*
* @param masterToken the master token.
* @param userIdToken the user ID token. May be null.
*/
public void setAuthTokens(final MasterToken masterToken, final UserIdToken userIdToken) {
// Make sure the assumptions hold. Otherwise a bad message could be
// built.
if (userIdToken != null && !userIdToken.isBoundTo(masterToken))
throw new MslInternalException("User ID token must be bound to master token.");
// In trusted network mode key exchange data should only exist if this
// is a server response. In which case this method should not be
// getting called.
if (keyExchangeData != null && !ctx.isPeerToPeer())
throw new MslInternalException("Attempt to set message builder master token when key exchange data exists as a trusted network server.");
// Load the stored service tokens.
final Set<ServiceToken> storedTokens;
try {
storedTokens = ctx.getMslStore().getServiceTokens(masterToken, userIdToken);
} catch (final MslException e) {
// This should never happen because we already checked that the
// user ID token is bound to the master token.
throw new MslInternalException("Invalid master token and user ID token combination despite checking above.", e);
}
// Remove any service tokens that will no longer be bound.
final Iterator<ServiceToken> tokens = serviceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if ((token.isUserIdTokenBound() && !token.isBoundTo(userIdToken)) ||
(token.isMasterTokenBound() && !token.isBoundTo(masterToken)))
{
tokens.remove();
}
}
// Add any service tokens based on the MSL store replacing ones already
// set as they may be newer. The application will have a chance to
// manage the service tokens before the message is constructed and
// sent.
for (final ServiceToken token : storedTokens) {
excludeServiceToken(token.getName(), token.isMasterTokenBound(), token.isUserIdTokenBound());
serviceTokens.add(token);
}
// Set the new authentication tokens.
this.masterToken = masterToken;
this.userIdToken = userIdToken;
if (this.userIdToken != null)
this.userAuthData = null;
}
/**
* <p>Set the user authentication data of the message.</p>
*
* <p>This will overwrite any existing user authentication data.</p>
*
* @param userAuthData user authentication data to set. May be null.
* @return this.
*/
public MessageBuilder setUserAuthenticationData(final UserAuthenticationData userAuthData) {
this.userAuthData = userAuthData;
return this;
}
/**
* <p>Set the remote user of the message. This will create a user ID token
* in trusted network mode or peer user ID token in peer-to-peer mode.</p>
*
* <p>Adding a new user ID token will not impact the service tokens; it is
* assumed that no service tokens exist that are bound to the newly created
* user ID token.</p>
*
* <p>This is a special method for the {@link MslControl} class that assumes
* the builder does not already have a user ID token for the remote user
* and does have a master token that the new user ID token can be bound
* against.</p>
*
* @param user remote user.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslException if there is an error creating the user ID token.
*/
public void setUser(final MslUser user) throws MslCryptoException, MslException {
// Make sure the assumptions hold. Otherwise a bad message could be
// built.
if (!ctx.isPeerToPeer() && userIdToken != null ||
ctx.isPeerToPeer() && peerUserIdToken != null)
{
throw new MslInternalException("User ID token or peer user ID token already exists for the remote user.");
}
// If key exchange data is provided then its master token should be
// used for the new user ID token and for querying service tokens.
final MasterToken uitMasterToken;
if (keyExchangeData != null) {
uitMasterToken = keyExchangeData.keyResponseData.getMasterToken();
} else {
uitMasterToken = (!ctx.isPeerToPeer()) ? masterToken : peerMasterToken;
}
// Make sure we have a master token to create the user for.
if (uitMasterToken == null)
throw new MslInternalException("User ID token or peer user ID token cannot be created because no corresponding master token exists.");
// Create the new user ID token.
final TokenFactory factory = ctx.getTokenFactory();
final UserIdToken userIdToken = factory.createUserIdToken(ctx, user, uitMasterToken);
// Set the new user ID token.
if (!ctx.isPeerToPeer()) {
this.userIdToken = userIdToken;
this.userAuthData = null;
} else {
this.peerUserIdToken = userIdToken;
}
}
/**
* Add key request data to the message.
*
* @param keyRequestData key request data to add.
* @return this.
*/
public MessageBuilder addKeyRequestData(final KeyRequestData keyRequestData) {
this.keyRequestData.add(keyRequestData);
return this;
}
/**
* Remove key request data from the message.
*
* @param keyRequestData key request data to remove.
* @return this.
*/
public MessageBuilder removeKeyRequestData(final KeyRequestData keyRequestData) {
this.keyRequestData.remove(keyRequestData);
return this;
}
/**
* <p>Add a service token to the message. This will overwrite any service
* token with the same name that is also bound to the master token or user
* ID token in the same way as the new service token.</p>
*
* <p>Adding a service token with empty data indicates the recipient should
* delete the service token.</p>
*
* @param serviceToken service token to add.
* @return this.
* @throws MslMessageException if the service token serial numbers do not
* match the primary master token or primary user ID token of the
* message being built.
*/
public MessageBuilder addServiceToken(final ServiceToken serviceToken) throws MslMessageException {
// If key exchange data is provided and we are not in peer-to-peer mode
// then its master token should be used for querying service tokens.
final MasterToken serviceMasterToken;
if (keyExchangeData != null && !ctx.isPeerToPeer()) {
serviceMasterToken = keyExchangeData.keyResponseData.getMasterToken();
} else {
serviceMasterToken = masterToken;
}
// Make sure the service token is properly bound.
if (serviceToken.isMasterTokenBound() && !serviceToken.isBoundTo(serviceMasterToken))
throw new MslMessageException(MslError.SERVICETOKEN_MASTERTOKEN_MISMATCH, "st " + serviceToken + "; mt " + serviceMasterToken).setMasterToken(serviceMasterToken);
if (serviceToken.isUserIdTokenBound() && !serviceToken.isBoundTo(userIdToken))
throw new MslMessageException(MslError.SERVICETOKEN_USERIDTOKEN_MISMATCH, "st " + serviceToken + "; uit " + userIdToken).setMasterToken(serviceMasterToken).setUserIdToken(userIdToken);
// Remove any existing service token with the same name and bound state.
excludeServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
// Add the service token.
serviceTokens.add(serviceToken);
return this;
}
/**
* <p>Add a service token to the message if a service token with the same
* name that is also bound to the master token or user ID token in the same
* way as the new service token does not already exist.</p>
*
* <p>Adding a service token with empty data indicates the recipient should
* delete the service token.</p>
*
* @param serviceToken service token to add.
* @return this.
* @throws MslMessageException if the service token serial numbers do not
* match the master token or user ID token of the message being
* built.
*/
public MessageBuilder addServiceTokenIfAbsent(final ServiceToken serviceToken) throws MslMessageException {
final Iterator<ServiceToken> tokens = serviceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if (token.getName().equals(serviceToken.getName()) &&
token.isMasterTokenBound() == serviceToken.isMasterTokenBound() &&
token.isUserIdTokenBound() == serviceToken.isUserIdTokenBound())
{
return this;
}
}
addServiceToken(serviceToken);
return this;
}
/**
* <p>Exclude a service token from the message. This matches the token name
* and whether or not it is bound to the master token or to a user ID
* token. It does not require the token to be bound to the exact same
* master token or user ID token that will be used in the message.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* <p>This function is equivalent to calling
* {@link #excludeServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return this.
* @see #excludeServiceToken(String, boolean, boolean)
*/
public MessageBuilder excludeServiceToken(final ServiceToken serviceToken) {
return excludeServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Exclude a service token from the message matching all the specified
* parameters. A false value for the master token bound or user ID token
* bound parameters restricts exclusion to tokens that are not bound to a
* master token or not bound to a user ID token respectively.</p>
*
* <p>For example, if a name is provided and the master token bound
* parameter is true while the user ID token bound parameter is false, then
* the master token bound service token with the same name will be excluded
* from the message. If a name is provided but both other parameters are
* false, then only an unbound service token with the same name will be
* excluded.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return this.
*/
public MessageBuilder excludeServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
final Iterator<ServiceToken> tokens = serviceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if (token.getName().equals(name) &&
token.isMasterTokenBound() == masterTokenBound &&
token.isUserIdTokenBound() == userIdTokenBound)
{
tokens.remove();
}
}
return this;
}
/**
* <p>Mark a service token for deletion.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* <p>This function is equivalent to calling
* {@link #deleteServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return this.
*/
public MessageBuilder deleteServiceToken(final ServiceToken serviceToken) {
return deleteServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Mark a service token for deletion. A false value for the master token
* bound or user ID token bound parameters restricts deletion to tokens
* that are not bound to a master token or not bound to a user ID token
* respectively.</p>
*
* <p>For example, if a name is provided and the master token bound
* parameter is true while the user ID token bound parameter is false, then
* the master token bound service token with the same name will be marked
* for deletion. If a name is provided but both other parameters are false,
* then only an unbound service token with the same name will be marked for
* deletion.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* @param name service token name.
* @param masterTokenBound true to delete a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to delete a user ID token bound service
* token.
* @return this.
*/
public MessageBuilder deleteServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Rebuild the original token with empty service data.
final MasterToken masterToken = masterTokenBound ? this.masterToken : null;
final UserIdToken userIdToken = userIdTokenBound ? this.userIdToken : null;
try {
final ServiceToken token = new ServiceToken(ctx, name, EMPTY_DATA, masterToken, userIdToken, false, null, new NullCryptoContext());
return addServiceToken(token);
} catch (final MslException e) {
throw new MslInternalException("Failed to create and add empty service token to message.", e);
}
}
/**
* @return the unmodifiable set of service tokens that will be included in
* the built message.
*/
public Set<ServiceToken> getServiceTokens() {
return Collections.unmodifiableSet(serviceTokens);
}
/**
* @return the peer master token or null if there is none.
*/
public MasterToken getPeerMasterToken() {
return peerMasterToken;
}
/**
* @return the peer user ID token or null if there is none.
*/
public UserIdToken getPeerUserIdToken() {
return peerUserIdToken;
}
/**
* <p>Set the peer master token and peer user ID token of the message. This
* will overwrite any existing peer master token or peer user ID token.</p>
*
* <p>Changing these tokens may result in invalidation of existing peer
* service tokens. Those peer service tokens will be removed from the
* message being built.</p>
*
* @param masterToken peer master token to set. May be null.
* @param userIdToken peer user ID token to set. May be null.
* @throws MslMessageException if the peer user ID token is not bound to
* the peer master token.
*/
public void setPeerAuthTokens(final MasterToken masterToken, final UserIdToken userIdToken) throws MslMessageException {
if (!ctx.isPeerToPeer())
throw new MslInternalException("Cannot set peer master token or peer user ID token when not in peer-to-peer mode.");
if (userIdToken != null && masterToken == null)
throw new MslInternalException("Peer master token cannot be null when setting peer user ID token.");
if (userIdToken != null && !userIdToken.isBoundTo(masterToken))
throw new MslMessageException(MslError.USERIDTOKEN_MASTERTOKEN_MISMATCH, "uit " + userIdToken + "; mt " + masterToken).setMasterToken(masterToken).setUserIdToken(userIdToken);
// Load the stored peer service tokens.
final Set<ServiceToken> storedTokens;
try {
storedTokens = ctx.getMslStore().getServiceTokens(masterToken, userIdToken);
} catch (final MslException e) {
// The checks above should have prevented any invalid master token,
// user ID token combinations.
throw new MslInternalException("Invalid peer master token and user ID token combination despite proper check.", e);
}
// Remove any peer service tokens that will no longer be bound.
final Iterator<ServiceToken> tokens = peerServiceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if ((token.isUserIdTokenBound() && !token.isBoundTo(userIdToken)) ||
(token.isMasterTokenBound() && !token.isBoundTo(masterToken)))
{
tokens.remove();
}
}
// Add any peer service tokens based on the MSL store if they are not
// already set (as a set one may be newer than the stored one).
for (final ServiceToken token : storedTokens) {
excludePeerServiceToken(token.getName(), token.isMasterTokenBound(), token.isUserIdTokenBound());
peerServiceTokens.add(token);
}
// Set the new peer authentication tokens.
peerUserIdToken = userIdToken;
peerMasterToken = masterToken;
}
/**
* <p>Add a peer service token to the message. This will overwrite any peer
* service token with the same name that is also bound to a peer master
* token or peer user ID token in the same way as the new service token.</p>
*
* <p>Adding a service token with empty data indicates the recipient should
* delete the service token.</p>
*
* @param serviceToken service token to add.
* @return this.
* @throws MslMessageException if the service token serial numbers do not
* match the peer master token or peer user ID token of the message
* being built.
*/
public MessageBuilder addPeerServiceToken(final ServiceToken serviceToken) throws MslMessageException {
// If we are not in peer-to-peer mode then peer service tokens cannot
// be set.
if (!ctx.isPeerToPeer())
throw new MslInternalException("Cannot set peer service tokens when not in peer-to-peer mode.");
// Make sure the service token is properly bound.
if (serviceToken.isMasterTokenBound() && !serviceToken.isBoundTo(peerMasterToken))
throw new MslMessageException(MslError.SERVICETOKEN_MASTERTOKEN_MISMATCH, "st " + serviceToken + "; mt " + peerMasterToken).setMasterToken(peerMasterToken);
if (serviceToken.isUserIdTokenBound() && !serviceToken.isBoundTo(peerUserIdToken))
throw new MslMessageException(MslError.SERVICETOKEN_USERIDTOKEN_MISMATCH, "st " + serviceToken + "; uit " + peerUserIdToken).setMasterToken(peerMasterToken).setUserIdToken(peerUserIdToken);
// Remove any existing service token with the same name and bound state.
excludePeerServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
// Add the peer service token.
peerServiceTokens.add(serviceToken);
return this;
}
/**
* <p>Add a peer service token to the message if a peer service token with
* the same name that is also bound to the peer master token or peer user
* ID token in the same way as the new service token does not already
* exist.</p>
*
* <p>Adding a service token with empty data indicates the recipient should
* delete the service token.</p>
*
* @param serviceToken service token to add.
* @return this.
* @throws MslMessageException if the service token serial numbers do not
* match the peer master token or peer user ID token of the message
* being built.
*/
public MessageBuilder addPeerServiceTokenIfAbsent(final ServiceToken serviceToken) throws MslMessageException {
final Iterator<ServiceToken> tokens = peerServiceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if (token.getName().equals(serviceToken.getName()) &&
token.isMasterTokenBound() == serviceToken.isMasterTokenBound() &&
token.isUserIdTokenBound() == serviceToken.isUserIdTokenBound())
{
return this;
}
}
addPeerServiceToken(serviceToken);
return this;
}
/**
* <p>Exclude a peer service token from the message. This matches the token
* name and whether or not it is bound to the master token or to a user ID
* token. It does not require the token to be bound to the exact same
* master token or user ID token that will be used in the message.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* <p>This function is equivalent to calling
* {@link #excludePeerServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return this.
*/
public MessageBuilder excludePeerServiceToken(final ServiceToken serviceToken) {
return excludePeerServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Exclude a peer service token from the message matching all the
* specified parameters. A false value for the master token bound or user
* ID token bound parameters restricts exclusion to tokens that are not
* bound to a master token or not bound to a user ID token
* respectively.</p>
*
* <p>For example, if a name is provided and the master token bound
* parameter is true while the user ID token bound parameter is false, then
* the master token bound service token with the same name will be excluded
* from the message. If a name is provided but both other parameters are
* false, then only an unbound service token with the same name will be
* excluded.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return this.
*/
public MessageBuilder excludePeerServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
final Iterator<ServiceToken> tokens = peerServiceTokens.iterator();
while (tokens.hasNext()) {
final ServiceToken token = tokens.next();
if (token.getName().equals(name) &&
token.isMasterTokenBound() == masterTokenBound &&
token.isUserIdTokenBound() == userIdTokenBound)
{
tokens.remove();
}
}
return this;
}
/**
* <p>Mark a peer service token for deletion.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* <p>This function is equivalent to calling
* {@link #deletePeerServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return this.
*/
public MessageBuilder deletePeerServiceToken(final ServiceToken serviceToken) {
return deletePeerServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Mark a peer service token for deletion. A false value for the master
* token bound or user ID token bound parameters restricts deletion to
* tokens that are not bound to a master token or not bound to a user ID
* token respectively.</p>
*
* <p>For example, if a name is provided and the master token bound
* parameter is true while the user ID token bound parameter is false, then
* the master token bound service token with the same name will be marked
* for deletion. If a name is provided but both other parameters are false,
* then only an unbound service token with the same name will be marked for
* deletion.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* @param name service token name.
* @param masterTokenBound true to delete a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to delete a user ID token bound service
* token.
* @return this.
*/
public MessageBuilder deletePeerServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Rebuild the original token with empty service data.
final MasterToken peerMasterToken = masterTokenBound ? this.peerMasterToken : null;
final UserIdToken peerUserIdToken = userIdTokenBound ? this.peerUserIdToken : null;
try {
final ServiceToken token = new ServiceToken(ctx, name, EMPTY_DATA, peerMasterToken, peerUserIdToken, false, null, new NullCryptoContext());
return addPeerServiceToken(token);
} catch (final MslException e) {
throw new MslInternalException("Failed to create and add empty peer service token to message.", e);
}
}
/**
* @return the unmodifiable set of peer service tokens that will be
* included in the built message.
*/
public Set<ServiceToken> getPeerServiceTokens() {
return Collections.unmodifiableSet(peerServiceTokens);
}
/** MSL context. */
private final MslContext ctx;
/** Message header master token. */
protected MasterToken masterToken;
/** Header data message ID. */
protected long messageId;
/** Key exchange data. */
protected KeyExchangeData keyExchangeData;
/** Message non-replayable. */
protected boolean nonReplayable = false;
/** Header data renewable. */
protected boolean renewable = false;
/** Handshake message. */
protected boolean handshake = false;
/** Message capabilities. */
protected MessageCapabilities capabilities;
/** Header data key request data. */
protected final Set<KeyRequestData> keyRequestData = new HashSet<KeyRequestData>();
/** Header data user authentication data. */
protected UserAuthenticationData userAuthData = null;
/** Header data user ID token. */
protected UserIdToken userIdToken = null;
/** Header data service tokens. */
protected final Set<ServiceToken> serviceTokens = new HashSet<ServiceToken>();
/** Header peer data master token. */
protected MasterToken peerMasterToken = null;
/** Header peer data user ID token. */
protected UserIdToken peerUserIdToken = null;
/** Header peer data service tokens. */
protected final Set<ServiceToken> peerServiceTokens = new HashSet<ServiceToken>();
}
| 9,855 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageServiceTokenBuilder.java | /**
* Copyright (c) 2012-2020 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.KeyExchangeFactory.KeyExchangeData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.util.MslContext;
/**
* <p>A message service token builder provides methods for intelligently
* manipulating the primary and peer service tokens that will be included in a
* message.</p>
*
* <p>There are two categories of service tokens: primary and peer.
* <ul>
* <li>Primary service tokens are associated with the primary master token and
* peer user ID token, and are the only category of service token to appear in
* trusted network mode. Primary service tokens are also used in peer-to-peer
* mode.</li>
* <li>Peer service tokens are associated with the peer master token and peer
* user ID token and only used in peer-to-peer mode.</li>
* </ul></p>
*
* <p>There are three levels of service token binding.
* <ul>
* <li>Unbound service tokens may be freely moved between entities and
* users.</li>
* <li>Master token bound service tokens must be accompanied by a master token
* that they are bound to and will be rejected if sent with a different master
* token or without a master token. This binds a service token to a specific
* entity.</li>
* <li>User ID token bound service tokens must be accompanied by a user ID
* token that they are bound to and will be rejected if sent with a different
* user or used without a user ID token. This binds a service token to a
* specific user and by extension a specific entity.</li>
* </ul></p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MessageServiceTokenBuilder {
/**
* <p>Select the appropriate crypto context for the named service token.</p>
*
* <p>If the service token name exists as a key in the map of crypto
* contexts, the mapped crypto context will be returned. Otherwise the
* default crypto context mapped from the empty string key will be returned.
* If no explicit or default crypto context exists null will be
* returned.</p>
*
* @param name service token name.
* @param cryptoContexts the map of service token names onto crypto
* contexts used to decrypt and verify service tokens.
* @return the correct crypto context for the service token or null.
*/
private static ICryptoContext selectCryptoContext(final String name, final Map<String,ICryptoContext> cryptoContexts) {
if (cryptoContexts.containsKey(name))
return cryptoContexts.get(name);
return cryptoContexts.get("");
}
/**
* Create a new message service token builder with the provided MSL and
* message contexts and message builder.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param builder message builder for message being built.
*/
public MessageServiceTokenBuilder(final MslContext ctx, final MessageContext msgCtx, final MessageBuilder builder) {
this.ctx = ctx;
this.cryptoContexts = msgCtx.getCryptoContexts();
this.builder = builder;
}
/**
* Returns the master token that primary service tokens should be bound
* against.
*
* @return the primary service token master token or {@code null} if there
* is none.
*/
private MasterToken getPrimaryMasterToken() {
// If key exchange data is provided and we are not in peer-to-peer mode
// then its master token will be used for creating service tokens.
final KeyExchangeData keyExchangeData = builder.getKeyExchangeData();
if (keyExchangeData != null && !ctx.isPeerToPeer()) {
return keyExchangeData.keyResponseData.getMasterToken();
} else {
return builder.getMasterToken();
}
}
/**
* Returns true if the message has a primary master token available for
* adding master-bound primary service tokens.
*
* @return true if the message has a primary master token.
*/
public boolean isPrimaryMasterTokenAvailable() {
return getPrimaryMasterToken() != null;
}
/**
* @return true if the message has a primary user ID token.
*/
public boolean isPrimaryUserIdTokenAvailable() {
return builder.getUserIdToken() != null;
}
/**
* @return true if the message has a peer master token.
*/
public boolean isPeerMasterTokenAvailable() {
return builder.getPeerMasterToken() != null;
}
/**
* @return true if the message has a peer user ID token.
*/
public boolean isPeerUserIdTokenAvailable() {
return builder.getPeerUserIdToken() != null;
}
/**
* @return the unmodifiable set of primary service tokens that will be
* included in the built message.
*/
public Set<ServiceToken> getPrimaryServiceTokens() {
return builder.getServiceTokens();
}
/**
* @return the unmodifiable set of peer service tokens that will be
* included in the built message.
*/
public Set<ServiceToken> getPeerServiceTokens() {
return builder.getPeerServiceTokens();
}
/**
* Adds a primary service token to the message, replacing any existing
* primary service token with the same name.
*
* @param serviceToken primary service token.
* @return true if the service token was added, false if the service token
* is bound to a master token or user ID token and the message does
* not have the same token.
* @throws MslMessageException if the service token serial numbers do not
* match the primary master token or primary user ID token of the
* message being built.
*/
public boolean addPrimaryServiceToken(final ServiceToken serviceToken) throws MslMessageException {
try {
builder.addServiceToken(serviceToken);
return true;
} catch (final MslMessageException e) {
return false;
}
}
/**
* Adds a peer service token to the message, replacing any existing peer
* service token with the same name.
*
* @param serviceToken peer service token.
* @return true if the service token was added, false if the service token
* is bound to a master token or user ID token and the message does
* not have the same token.
* @throws MslMessageException if the service token serial numbers do not
* match the peer master token or peer user ID token of the message
* being built.
*/
public boolean addPeerServiceToken(final ServiceToken serviceToken) throws MslMessageException {
try {
builder.addPeerServiceToken(serviceToken);
return true;
} catch (final MslMessageException e) {
return false;
}
}
/**
* Adds a new unbound primary service token to the message, replacing any
* existing primary service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addUnboundPrimaryServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, null, null, encrypt, compressionAlgo, cryptoContext);
try {
builder.addServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite being unbound.", e);
}
return true;
}
/**
* Adds a new unbound peer service token to the message, replacing any
* existing peer service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addUnboundPeerServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, null, null, encrypt, compressionAlgo, cryptoContext);
try {
builder.addPeerServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite being unbound.", e);
}
return true;
}
/**
* Adds a new master token bound primary service token to the message,
* replacing any existing primary service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token or the message does not
* have a primary master token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addMasterBoundPrimaryServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no master token.
final MasterToken masterToken = getPrimaryMasterToken();
if (masterToken == null)
return false;
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, masterToken, null, encrypt, compressionAlgo, cryptoContext);
try {
builder.addServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite setting correct master token.", e);
}
return true;
}
/**
* Adds a new master token bound peer service token to the message,
* replacing any existing peer service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token or the message does not
* have a peer master token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addMasterBoundPeerServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no master token.
final MasterToken masterToken = builder.getPeerMasterToken();
if (masterToken == null)
return false;
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, masterToken, null, encrypt, compressionAlgo, cryptoContext);
try {
builder.addPeerServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite setting correct master token.", e);
}
return true;
}
/**
* Adds a new user ID token bound primary service token to the message,
* replacing any existing primary service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token or the message does not
* have a primary user ID token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addUserBoundPrimaryServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no master token.
final MasterToken masterToken = getPrimaryMasterToken();
if (masterToken == null)
return false;
// Fail if there is no user ID token.
final UserIdToken userIdToken = builder.getUserIdToken();
if (userIdToken == null)
return false;
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, masterToken, userIdToken, encrypt, compressionAlgo, cryptoContext);
try {
builder.addServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite setting correct master token and user ID token.", e);
}
return true;
}
/**
* Adds a new user ID token bound peer service token to the message,
* replacing any peer existing service token with the same name.
*
* @param name service token name.
* @param data service token data.
* @param encrypt true if the service token data should be encrypted.
* @param compressionAlgo the compression algorithm. May be {@code null}
* for no compression.
* @return true if the service token was added, false if there is no crypto
* context found for this service token or the message does not
* have a peer user ID token.
* @throws MslCryptoException if there is an error encrypting or signing
* the token data.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslException if there is an error compressing the data.
*/
public boolean addUserBoundPeerServiceToken(final String name, final byte[] data, final boolean encrypt, final CompressionAlgorithm compressionAlgo) throws MslEncodingException, MslCryptoException, MslException {
// Fail if there is no master token.
final MasterToken masterToken = builder.getPeerMasterToken();
if (masterToken == null)
return false;
// Fail if there is no user ID token.
final UserIdToken userIdToken = builder.getPeerUserIdToken();
if (userIdToken == null)
return false;
// Fail if there is no crypto context.
final ICryptoContext cryptoContext = selectCryptoContext(name, cryptoContexts);
if (cryptoContext == null)
return false;
// Add the service token.
final ServiceToken serviceToken = new ServiceToken(ctx, name, data, masterToken, userIdToken, encrypt, compressionAlgo, cryptoContext);
try {
builder.addPeerServiceToken(serviceToken);
} catch (final MslMessageException e) {
throw new MslInternalException("Service token bound to incorrect authentication tokens despite setting correct master token and user ID token.", e);
}
return true;
}
/**
* <p>Exclude a primary service token from the message. This matches the
* token name and whether or not it is bound to a master token or to a user
* ID token. It does not require the token to be bound to the exact same
* master token or user ID token that will be used in the message.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* <p>This function is equivalent to calling
* {@link #excludePrimaryServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return true if the service token was found and therefore removed.
*/
public boolean excludePrimaryServiceToken(final ServiceToken serviceToken) {
return excludePrimaryServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Exclude a primary service token from the message matching all
* specified parameters. A false value for the master token bound or user
* ID token bound parameters restricts exclusion to tokens that are not
* bound to a master token or not bound to a user ID token
* respectively.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return true if the service token was found and therefore removed.
*/
public boolean excludePrimaryServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Exclude the service token if found.
for (final ServiceToken serviceToken : builder.getServiceTokens()) {
if (serviceToken.getName().equals(name) &&
serviceToken.isMasterTokenBound() == masterTokenBound &&
serviceToken.isUserIdTokenBound() == userIdTokenBound)
{
builder.excludeServiceToken(name, masterTokenBound, userIdTokenBound);
return true;
}
}
// Not found.
return false;
}
/**
* <p>Exclude a peer service token from the message. This matches the
* token name and whether or not it is bound to a master token or to a user
* ID token. It does not require the token to be bound to the exact same
* master token or user ID token that will be used in the message.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* <p>This function is equivalent to calling
* {@link #excludePeerServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return true if the service token was found and therefore removed.
*/
public boolean excludePeerServiceToken(final ServiceToken serviceToken) {
return excludePeerServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Exclude a peer service token from the message matching all specified
* parameters. A false value for the master token bound or user ID token
* bound parameters restricts exclusion to tokens that are not bound to a
* master token or not bound to a user ID token respectively.</p>
*
* <p>The service token will not be sent in the built message. This is not
* the same as requesting the remote entity delete a service token.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return true if the peer service token was found and therefore removed.
*/
public boolean excludePeerServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Exclude the service token if found.
for (final ServiceToken serviceToken : builder.getPeerServiceTokens()) {
if (serviceToken.getName().equals(name) &&
serviceToken.isMasterTokenBound() == masterTokenBound &&
serviceToken.isUserIdTokenBound() == userIdTokenBound)
{
builder.excludePeerServiceToken(name, masterTokenBound, userIdTokenBound);
return true;
}
}
// Not found.
return false;
}
/**
* <p>Mark a primary service token for deletion, if it exists. This matches
* the token name and whether or not it is bound to a master token or to a
* user ID token. It does not require the token to be bound to the exact
* same master token or user ID token that will be used in the message.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* <p>This function is equivalent to calling
* {@link #deletePrimaryServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return true if the service token exists and was marked for deletion.
*/
public boolean deletePrimaryServiceToken(final ServiceToken serviceToken) {
return deletePrimaryServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Mark a primary service token for deletion, if it exists, matching all
* specified parameters. A false value for the master token bound or user
* ID token bound parameters restricts deletion to tokens that are not
* bound to a master token or not bound to a user ID token
* respectively.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return true if the service token exists and was marked for deletion.
*/
public boolean deletePrimaryServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Mark the service token for deletion if found.
for (final ServiceToken serviceToken : builder.getServiceTokens()) {
if (serviceToken.getName().equals(name) &&
serviceToken.isMasterTokenBound() == masterTokenBound &&
serviceToken.isUserIdTokenBound() == userIdTokenBound)
{
builder.deleteServiceToken(name, masterTokenBound, userIdTokenBound);
return true;
}
}
// Not found.
return false;
}
/**
* <p>Mark a peer service token for deletion, if it exists. This matches
* the token name and whether or not it is bound to a master token or to a
* user ID token. It does not require the token to be bound to the exact
* same master token or user ID token that will be used in the message.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* <p>This function is equivalent to calling
* {@link #deletePeerServiceToken(String, boolean, boolean)}.</p>
*
* @param serviceToken the service token.
* @return true if the service token exists and was marked for deletion.
*/
public boolean deletePeerServiceToken(final ServiceToken serviceToken) {
return deletePeerServiceToken(serviceToken.getName(), serviceToken.isMasterTokenBound(), serviceToken.isUserIdTokenBound());
}
/**
* <p>Mark a peer service token for deletion, if it exists, matching all
* specified parameters. A false value for the master token bound or user
* ID token bound parameters restricts deletion to tokens that are not
* bound to a master token or not bound to a user ID token
* respectively.</p>
*
* <p>The service token will be sent in the built message with an empty
* value. This is not the same as requesting that a service token be
* excluded from the message.</p>
*
* @param name service token name.
* @param masterTokenBound true to exclude a master token bound service
* token. Must be true if {@code userIdTokenBound} is true.
* @param userIdTokenBound true to exclude a user ID token bound service
* token.
* @return true if the peer service token exists and was marked for
* deletion.
*/
public boolean deletePeerServiceToken(final String name, final boolean masterTokenBound, final boolean userIdTokenBound) {
// Mark the service token for deletion if found.
for (final ServiceToken serviceToken : builder.getPeerServiceTokens()) {
if (serviceToken.getName().equals(name) &&
serviceToken.isMasterTokenBound() == masterTokenBound &&
serviceToken.isUserIdTokenBound() == userIdTokenBound)
{
builder.deletePeerServiceToken(name, masterTokenBound, userIdTokenBound);
return true;
}
}
// Not found.
return false;
}
/** MSL context. */
private final MslContext ctx;
/** Service token crypto contexts. */
private final Map<String,ICryptoContext> cryptoContexts;
/** Message builder for message being built. */
private final MessageBuilder builder;
}
| 9,856 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/NonReplayableMessageContext.java | /**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
/**
* <p>A message context implementation that can be extended for use with
* messages that cannot be replayed. This also carries the security properties
* of encryption and integrity protection.</p>
*
* <p>Example uses of the non-replayable message context would be for the
* transmission of financial transactions or to grant access to restricted
* resources where a repeat transmission may result in incorrect data or
* abuse.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class NonReplayableMessageContext implements MessageContext {
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return true;
}
}
| 9,857 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/IdempotentResponseMessageBuilder.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.util.Set;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslException;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.util.MslContext;
/**
* <p>Idempotent message builder.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class IdempotentResponseMessageBuilder extends MessageBuilder {
/**
* Create a new message builder that will craft a new message in response
* to another message without issuing or renewing any master tokens or user
* ID tokens. The constructed message may be used as a request.
*
* @param ctx MSL context.
* @param requestHeader message header to respond to.
* @throws MslCryptoException if there is an error accessing the remote
* entity identity.
* @throws MslException if any of the request's user ID tokens is not bound
* to its master token.
*/
public IdempotentResponseMessageBuilder(final MslContext ctx, final MessageHeader requestHeader) throws MslCryptoException, MslException {
super(ctx);
final MasterToken masterToken = requestHeader.getMasterToken();
final EntityAuthenticationData entityAuthData = requestHeader.getEntityAuthenticationData();
final UserIdToken userIdToken = requestHeader.getUserIdToken();
final UserAuthenticationData userAuthData = requestHeader.getUserAuthenticationData();
// The response message ID must be equal to the request message ID + 1.
final long requestMessageId = requestHeader.getMessageId();
final long messageId = incrementMessageId(requestMessageId);
// Compute the intersection of the request and response message
// capabilities.
final MessageCapabilities capabilities = MessageCapabilities.intersection(requestHeader.getMessageCapabilities(), ctx.getMessageCapabilities());
// Create the message builder.
//
// Peer-to-peer responses swap the tokens.
try {
final KeyResponseData keyResponseData = requestHeader.getKeyResponseData();
final Set<ServiceToken> serviceTokens = requestHeader.getServiceTokens();
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
final Set<ServiceToken> peerServiceTokens = requestHeader.getPeerServiceTokens();
initializeMessageBuilder(ctx, messageId, capabilities, peerMasterToken, peerUserIdToken, peerServiceTokens, masterToken, userIdToken, serviceTokens, null);
} else {
final MasterToken localMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : masterToken;
initializeMessageBuilder(ctx, messageId, capabilities, localMasterToken, userIdToken, serviceTokens, null, null, null, null);
}
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setUserIdToken(userIdToken);
e.setUserAuthenticationData(userAuthData);
e.setMessageId(requestMessageId);
throw e;
}
}
}
| 9,858 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/FilterStreamFactory.java | /**
* Copyright (c) 2013-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.io.InputStream;
import java.io.OutputStream;
/**
* A filter stream factory provides filter input stream and filter output
* stream instances.
*
* Implementations must be thread-safe.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public interface FilterStreamFactory {
/**
* Return a new input stream that has the provided input stream as its
* backing source. If no filtering is desired then the original input
* stream must be returned.
*
* @param in the input stream to wrap.
* @return a new filter input stream backed by the provided input stream or
* the original input stream..
*/
public InputStream getInputStream(final InputStream in);
/**
* Return a new output stream that has the provided output stream as its
* backing destination. If no filtering is desired then the original output
* stream must be returned.
*
* @param out the output stream to wrap.
* @return a new filter output stream backed by the provided output stream
* or the original output stream.
*/
public OutputStream getOutputStream(final OutputStream out);
}
| 9,859 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/ServerReceiveMessageContext.java | /**
* Copyright (c) 2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* <p>A trusted services network message context used to receive client
* messages suitable for use with
* {@link MslControl#receive(com.netflix.msl.util.MslContext, MessageContext, java.io.InputStream, java.io.OutputStream, int)}.
* Since this message context is only used for receiving messages, it cannot be
* used to send application data back to the client and does not require
* encryption or integrity protection.</p>
*
* <p>The application may wish to override
* {@link #updateServiceTokens(MessageServiceTokenBuilder, boolean)} to
* modify any service tokens sent in handshake responses.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class ServerReceiveMessageContext extends PublicMessageContext {
/**
* <p>Create a new receive message context.</p>
*
* @param cryptoContexts service token crypto contexts. May be
* {@code null}.
* @param dbgCtx optional message debug context. May be {@code null}.
*/
public ServerReceiveMessageContext(final Map<String,ICryptoContext> cryptoContexts, final MessageDebugContext dbgCtx) {
this.cryptoContexts = (cryptoContexts != null) ? new HashMap<String,ICryptoContext>(cryptoContexts) : new HashMap<String,ICryptoContext>();
this.dbgCtx = dbgCtx;
}
@Override
public Map<String, ICryptoContext> getCryptoContexts() {
return Collections.unmodifiableMap(cryptoContexts);
}
@Override
public String getRemoteEntityIdentity() {
return null;
}
@Override
public boolean isRequestingTokens() {
return false;
}
@Override
public String getUserId() {
return null;
}
@Override
public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required) {
return null;
}
@Override
public MslUser getUser() {
return null;
}
@Override
public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException {
return Collections.emptySet();
}
@Override
public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) {
}
@Override
public void write(final MessageOutputStream output) throws IOException {
}
@Override
public MessageDebugContext getDebugContext() {
return dbgCtx;
}
/** Service token crypto contexts. */
protected final Map<String,ICryptoContext> cryptoContexts;
/** Message debug context. */
protected final MessageDebugContext dbgCtx;
}
| 9,860 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MslControl.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.FileLockInterruptionException;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslConstants.ResponseCode;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslErrorResponseException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.NullCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.entityauth.UnauthenticatedAuthenticationData;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.io.MslTokenizer;
import com.netflix.msl.io.Url;
import com.netflix.msl.io.Url.Connection;
import com.netflix.msl.keyx.KeyExchangeFactory;
import com.netflix.msl.keyx.KeyExchangeFactory.KeyExchangeData;
import com.netflix.msl.keyx.KeyExchangeScheme;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.MslContext;
import com.netflix.msl.util.MslStore;
import com.netflix.msl.util.MslUtils;
import com.netflix.msl.util.NullMslStore;
/**
* <p>Message Security Layer control provides the base operational MSL logic of
* sending and receiving messages with an optional thread pool. An application
* should only use one instance of {@code MslControl} for all MSL
* communication. This class is thread-safe.</p>
*
* <p>This class provides methods for sending and receiving messages for all
* types of entities in both trusted network and peer-to-peer network types.
* Refer to the documentation for each method to determine which methods should
* be used based on the entity's role and network type.</p>
*
* <h3>Error Handling</h3>
*
* <dl>
* <dt>{@link ResponseCode#FAIL}</dt>
* <dd>The caller is notified of the failure.</dd>
*
* <dt>{@link ResponseCode#TRANSIENT_FAILURE}</dt>
* <dd>The caller is notified of the failure. MSL will not automatically
* retry.</dd>
*
* <dt>{@link ResponseCode#ENTITY_REAUTH}</dt>
* <dd>MSL will attempt to resend the message using the entity authentication
* data. The previous master token and master token-bound service tokens
* will be discarded if successful.</dd>
*
* <dt>{@link ResponseCode#USER_REAUTH}</dt>
* <dd>MSL will attempt to resend the message using the user authentication
* data if made available by the message context. Otherwise request fails.
* The previous user ID token-bound service tokens will be discarded if
* successful.</dd>
*
* <dt>{@link ResponseCode#KEYX_REQUIRED}</dt>
* <dd>MSL will attempt to perform key exchange to establish session keys and
* then resend the message.</dd>
*
* <dt>{@link ResponseCode#ENTITYDATA_REAUTH}</dt>
* <dd>MSL will attempt to resend the message using new entity authentication
* data. The previous master token and master token-bound service tokens
* will be discarded if successful.</dd>
*
* <dt>{@link ResponseCode#USERDATA_REAUTH}</dt>
* <dd>MSL will attempt to resend the message using new user authentication
* data if made available by the message context. Otherwise request fails.
* The previous user ID token-bound service tokens will be discarded if
* successful.</dd>
*
* <dt>{@link ResponseCode#EXPIRED}</dt>
* <dd>MSL will attempt to resend the message with the renewable flag set or
* after receiving a new master token.</dd>
*
* <dt>{@link ResponseCode#REPLAYED}</dt>
* <dd>MSL will attempt to resend the message after renewing the master token
* or receiving a new master token.</dd>
*
* <dt>{@link ResponseCode#SSOTOKEN_REJECTED}</dt>
* <dd>Identical to {@link ResponseCode#USERDATA_REAUTH}.</dd>
* </dl>
*
* <h3>Anti-Replay</h3>
*
* <p>Requests marked as non-replayable will include a non-replayable ID.</p>
*
* <p>Responses must always reply with the message ID of the request
* incremented by 1. When the request message ID equals 2<sup>63</sup>-1 the
* response message ID must be 0. If the response message ID does not equal the
* expected value it is rejected and the caller is notified.</p>
*
* <h3>Renewal Synchronization</h3>
*
* <p>For a given MSL context there will be at most one renewable request with
* a master token and key request data in process. This prevents excessive
* master token renewal and potential renewal race conditions.</p>
*
* <p>Requests will be marked renewable if any of the following is true:
* <ul>
* <li>The master token renewal window has been entered.</li>
* <li>The user ID token renewal window has been entered.</li>
* <li>The application requests or requires establishment of session keys.</li>
* </ul>
* </p>
*
* <h3>MSL Handshake</h3>
*
* <p>Whenever requested or possible application data is encrypted and
* integrity-protected while in transit. If the MSL context entity
* authentication scheme does not support encryption or integrity protection
* when requested an initial handshake will be performed to establish session
* keys. This handshake occurs silently without the application's
* knowledge.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslControl {
/**
* Application level errors that may translate into MSL level errors.
*/
public static enum ApplicationError {
/** The entity identity is no longer accepted by the application. */
ENTITY_REJECTED,
/** The user identity is no longer accepted by the application. */
USER_REJECTED,
}
/**
* A {@link MessageInputStream} and {@link MessageOutputStream} pair
* representing a single MSL communication channel established between
* the local and remote entities.
*/
public static class MslChannel {
/**
* Create a new MSL channel with the provided input and output streams.
*
* @param input message input stream to read from the remote entity.
* @param output message output stream to write to the remote entity.
*/
protected MslChannel(final MessageInputStream input, final MessageOutputStream output) {
this.input = input;
this.output = output;
}
/** Message input stream to read from the remote entity. */
public final MessageInputStream input;
/** Message output stream to write to the remote entity. */
public final MessageOutputStream output;
}
/**
* A map key based off a MSL context and master token pair.
*/
private static class MslContextMasterTokenKey {
/**
* Create a new MSL context and master token map key.
*
* @param ctx MSL context.
* @param masterToken master token.
*/
public MslContextMasterTokenKey(final MslContext ctx, final MasterToken masterToken) {
this.ctx = ctx;
this.masterToken = masterToken;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.ctx.hashCode() ^ this.masterToken.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof MslContextMasterTokenKey)) return false;
final MslContextMasterTokenKey that = (MslContextMasterTokenKey)obj;
return this.ctx.equals(that.ctx) && this.masterToken.equals(that.masterToken);
}
/** MSL context. */
private final MslContext ctx;
/** Master token. */
private final MasterToken masterToken;
}
/**
* This class executes all tasks synchronously on the calling thread.
*/
private static class SynchronousExecutor extends AbstractExecutorService {
/* (non-Javadoc)
* @see java.util.concurrent.Executor#execute(java.lang.Runnable)
*/
@Override
public void execute(final Runnable command) {
// All the AbstractExecutorService methods eventually end up here
// so checking for shutdown and executing on the caller should be
// okay for this implementation.
if (shutdown)
throw new RejectedExecutionException("Synchronous executor already shut down.");
command.run();
}
/* (non-Javadoc)
* @see java.util.concurrent.ExecutorService#awaitTermination(long, java.util.concurrent.TimeUnit)
*/
@Override
public boolean awaitTermination(final long timeout, final TimeUnit unit) {
return false;
}
/* (non-Javadoc)
* @see java.util.concurrent.ExecutorService#isShutdown()
*/
@Override
public boolean isShutdown() {
return shutdown;
}
/* (non-Javadoc)
* @see java.util.concurrent.ExecutorService#isTerminated()
*/
@Override
public boolean isTerminated() {
return shutdown;
}
/* (non-Javadoc)
* @see java.util.concurrent.ExecutorService#shutdown()
*/
@Override
public void shutdown() {
shutdown = true;
}
/* (non-Javadoc)
* @see java.util.concurrent.ExecutorService#shutdownNow()
*/
@Override
public List<Runnable> shutdownNow() {
shutdown = true;
return Collections.emptyList();
}
/** Shutdown? */
private boolean shutdown = false;
}
/**
* A dummy MSL context only used for our dummy
* {@link MslControl#NULL_MASTER_TOKEN}.
*/
private static class DummyMslContext extends MslContext {
/** A dummy MSL encoder factory. */
private static class DummyMslEncoderFactory extends MslEncoderFactory {
@Override
public MslEncoderFormat getPreferredFormat(final Set<MslEncoderFormat> formats) {
return MslEncoderFormat.JSON;
}
@Override
protected MslTokenizer generateTokenizer(final InputStream source, final MslEncoderFormat format) {
throw new MslInternalException("DummyMslEncoderFactory.generateTokenizer() not supported.");
}
@Override
public MslObject parseObject(final byte[] encoding) {
throw new MslInternalException("DummyMslEncoderFactory.parseObject() not supported.");
}
@Override
public byte[] encodeObject(final MslObject object, final MslEncoderFormat format) {
throw new MslInternalException("DummyMslEncoderFactory.encodeObject() not supported.");
}
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getTime()
*/
@Override
public long getTime() {
return System.currentTimeMillis();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getRandom()
*/
@Override
public Random getRandom() {
return new Random();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#isPeerToPeer()
*/
@Override
public boolean isPeerToPeer() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMessageCapabilities()
*/
@Override
public MessageCapabilities getMessageCapabilities() {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getEntityAuthenticationData(com.netflix.msl.util.MslContext.ReauthCode)
*/
@Override
public EntityAuthenticationData getEntityAuthenticationData(final MslContext.ReauthCode reauth) {
return new UnauthenticatedAuthenticationData("dummy");
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslCryptoContext()
*/
@Override
public ICryptoContext getMslCryptoContext() throws MslCryptoException {
return new NullCryptoContext();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getEntityAuthenticationScheme(java.lang.String)
*/
@Override
public EntityAuthenticationScheme getEntityAuthenticationScheme(final String name) {
return EntityAuthenticationScheme.getScheme(name);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getEntityAuthenticationFactory(com.netflix.msl.entityauth.EntityAuthenticationScheme)
*/
@Override
public EntityAuthenticationFactory getEntityAuthenticationFactory(final EntityAuthenticationScheme scheme) {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getUserAuthenticationScheme(java.lang.String)
*/
@Override
public UserAuthenticationScheme getUserAuthenticationScheme(final String name) {
return UserAuthenticationScheme.getScheme(name);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getUserAuthenticationFactory(com.netflix.msl.userauth.UserAuthenticationScheme)
*/
@Override
public UserAuthenticationFactory getUserAuthenticationFactory(final UserAuthenticationScheme scheme) {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getTokenFactory()
*/
@Override
public TokenFactory getTokenFactory() {
throw new MslInternalException("Dummy token factory should never actually get used.");
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getKeyExchangeScheme(java.lang.String)
*/
@Override
public KeyExchangeScheme getKeyExchangeScheme(final String name) {
return KeyExchangeScheme.getScheme(name);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getKeyExchangeFactory(com.netflix.msl.keyx.KeyExchangeScheme)
*/
@Override
public KeyExchangeFactory getKeyExchangeFactory(final KeyExchangeScheme scheme) {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getKeyExchangeFactories()
*/
@Override
public SortedSet<KeyExchangeFactory> getKeyExchangeFactories() {
return new TreeSet<KeyExchangeFactory>();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslStore()
*/
@Override
public MslStore getMslStore() {
return new NullMslStore();
}
/* (non-Javadoc)
* @see com.netflix.msl.util.MslContext#getMslEncoderFactory()
*/
@Override
public MslEncoderFactory getMslEncoderFactory() {
return new DummyMslEncoderFactory();
}
}
/**
* A dummy error message registry that always returns null for the user
* message.
*/
private static class DummyMessageRegistry implements ErrorMessageRegistry {
/* (non-Javadoc)
* @see com.netflix.msl.msg.ErrorMessageRegistry#getUserMessage(com.netflix.msl.MslError, java.util.List)
*/
@Override
public String getUserMessage(final MslError err, final List<String> languages) {
return null;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.ErrorMessageRegistry#getUserMessage(java.lang.Throwable, java.util.List)
*/
@Override
public String getUserMessage(final Throwable err, final List<String> languages) {
return null;
}
}
/**
* Base class for custom message contexts. All methods are passed through
* to the backing message context.
*/
private static class FilterMessageContext implements MessageContext {
/**
* Creates a message context that passes through calls to the backing
* message context.
*
* @param appCtx the application's message context.
*/
protected FilterMessageContext(final MessageContext appCtx) {
this.appCtx = appCtx;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getCryptoContexts()
*/
@Override
public Map<String, ICryptoContext> getCryptoContexts() {
return appCtx.getCryptoContexts();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getRemoteEntityIdentity()
*/
@Override
public String getRemoteEntityIdentity() {
return appCtx.getRemoteEntityIdentity();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return appCtx.isEncrypted();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
return appCtx.isIntegrityProtected();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return appCtx.isNonReplayable();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isRequestingTokens()
*/
@Override
public boolean isRequestingTokens() {
return appCtx.isRequestingTokens();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUserId()
*/
@Override
public String getUserId() {
return appCtx.getUserId();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUserAuthData(com.netflix.msl.msg.MessageContext.ReauthCode, boolean, boolean)
*/
@Override
public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required) {
return appCtx.getUserAuthData(reauthCode, renewable, required);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getUser()
*/
@Override
public MslUser getUser() {
return appCtx.getUser();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getKeyRequestData()
*/
@Override
public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException {
return appCtx.getKeyRequestData();
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#updateServiceTokens(com.netflix.msl.msg.MessageServiceTokenBuilder, boolean)
*/
@Override
public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) throws MslMessageException, MslEncodingException, MslCryptoException, MslException {
appCtx.updateServiceTokens(builder, handshake);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#write(com.netflix.msl.msg.MessageOutputStream)
*/
@Override
public void write(final MessageOutputStream output) throws IOException {
appCtx.write(output);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#getDebugContext()
*/
@Override
public MessageDebugContext getDebugContext() {
return appCtx.getDebugContext();
}
/** The backing application message context. */
protected final MessageContext appCtx;
}
/**
* This message context is used to re-send a message.
*/
private static class ResendMessageContext extends FilterMessageContext {
/**
* Creates a message context used to re-send a message after an error
* or handshake. If the payloads are null the application's message
* context will be asked to write its data. Otherwise the provided
* payloads will be used for the message's application data.
*
* @param payloads original request payload chunks. May be null.
* @param appCtx the application's message context.
*/
public ResendMessageContext(final List<PayloadChunk> payloads, final MessageContext appCtx) {
super(appCtx);
this.payloads = payloads;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MslControl.FilterMessageContext#write(com.netflix.msl.msg.MessageOutputStream)
*/
@Override
public void write(final MessageOutputStream output) throws IOException {
// If there are no payloads ask the application message context to
// write its data.
if (payloads == null || payloads.isEmpty()) {
appCtx.write(output);
return;
}
// Rewrite the payloads one-by-one.
for (final PayloadChunk chunk : payloads) {
output.setCompressionAlgorithm(chunk.getCompressionAlgo());
output.write(chunk.getData());
if (chunk.isEndOfMessage())
output.close();
else
output.flush();
}
}
/** The application data to resend. */
private final List<PayloadChunk> payloads;
}
/**
* This message context is used to send messages that will not expect a
* response.
*/
private static class SendMessageContext extends FilterMessageContext {
/**
* Creates a message context used to send messages that do not expect a
* response by ensuring that the message context conforms to those
* expectations.
*
* @param appCtx the application's message context.
*/
public SendMessageContext(final MessageContext appCtx) {
super(appCtx);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MslControl.FilterMessageContext#isRequestingTokens()
*/
@Override
public boolean isRequestingTokens() {
return false;
}
}
/**
* This message context is used to send a handshake response.
*/
private static class KeyxResponseMessageContext extends FilterMessageContext {
/**
* Creates a message context used for automatically generated handshake
* responses.
*
* @param appCtx the application's message context.
*/
public KeyxResponseMessageContext(final MessageContext appCtx) {
super(appCtx);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
// Key exchange responses cannot require encryption otherwise key
// exchange could never succeed in some cases.
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MslControl.FilterMessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
// Key exchange responses cannot require integrity protection
// otherwise key exchange could never succeed in some cases.
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MslControl.FilterMessageContext#write(com.netflix.msl.msg.MessageOutputStream)
*/
@Override
public void write(final MessageOutputStream output) throws IOException {
// No application data.
}
}
/**
* <p>Returns true if the current thread has been interrupted as indicated
* by the {@code Thread#isInterrupted()} method or the type of caught
* throwable.</p>
*
* <p>The following {@code Throwable} types are considered interruptions that the application
* initiated or should otherwise be aware of:
* <ul>
* <li>{@link InterruptedException}</li>
* <li>{@link InterruptedIOException} except for {@link SocketTimeoutException}</li>
* <li>{@link FileLockInterruptionException}</li>
* <li>{@link ClosedByInterruptException}</li>
* </ul></p>
*
* @param t caught throwable. May be null.
* @return true if this thread was interrupted or the exception indicates
* an operation was interrupted.
*/
protected static boolean cancelled(Throwable t) {
// Clear the interrupted state so we continue to be cancelled if the
// thread is re-used.
if (Thread.interrupted())
return true;
while (t != null) {
if (t instanceof InterruptedException ||
(t instanceof InterruptedIOException && !(t instanceof SocketTimeoutException)) ||
t instanceof FileLockInterruptionException ||
t instanceof ClosedByInterruptException)
{
return true;
}
t = t.getCause();
}
return false;
}
/**
* Create a new instance of MSL control with the specified number of
* threads. A thread count of zero will cause all operations to execute on
* the calling thread.
*
* @param numThreads number of worker threads to create.
*/
public MslControl(final int numThreads) {
this(numThreads, null, null);
}
/**
* Create a new instance of MSL control with the specified number of
* threads and user error message registry. A thread count of zero will
* cause all operations to execute on the calling thread.
*
* @param numThreads number of worker threads to create.
* @param messageFactory message factory. May be {@code null}.
* @param messageRegistry error message registry. May be {@code null}.
*/
public MslControl(final int numThreads, final MessageFactory messageFactory, final ErrorMessageRegistry messageRegistry) {
if (numThreads < 0)
throw new IllegalArgumentException("Number of threads must be non-negative.");
// Set the stream factory.
this.messageFactory = (messageFactory != null) ? messageFactory : new MessageFactory();
// Set the message registry.
this.messageRegistry = (messageRegistry != null) ? messageRegistry : new DummyMessageRegistry();
// Create the thread pool if requested.
if (numThreads > 0)
executor = Executors.newFixedThreadPool(numThreads);
else
executor = new SynchronousExecutor();
// Create the dummy master token used as a special value when releasing
// the renewal lock without a new master token.
try {
final MslContext ctx = new DummyMslContext();
final MslObject dummy = ctx.getMslEncoderFactory().createObject();
final byte[] keydata = new byte[16];
final SecretKey encryptionKey = new SecretKeySpec(keydata, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(keydata, JcaAlgorithm.HMAC_SHA256);
NULL_MASTER_TOKEN = new MasterToken(ctx, new Date(), new Date(), 1L, 1L, dummy, "dummy", encryptionKey, hmacKey);
} catch (final MslEncodingException e) {
throw new MslInternalException("Unexpected exception when constructing dummy master token.", e);
} catch (final MslCryptoException e) {
throw new MslInternalException("Unexpected exception when constructing dummy master token.", e);
}
}
/**
* Assigns a filter stream factory that will be used to filter any incoming
* or outgoing messages. The filters will be placed between the MSL message
* and MSL control, meaning they will see the actual MSL message data as it
* is being read from or written to the remote entity.
*
* @param factory filter stream factory. May be null.
*/
public void setFilterFactory(final FilterStreamFactory factory) {
filterFactory = factory;
}
/**
* Gracefully shutdown the MSL control instance. No additional messages may
* be processed. Any messages pending or in process will be completed.
*/
public void shutdown() {
executor.shutdown();
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
executor.shutdownNow();
super.finalize();
}
/**
* <p>Returns the newest master token from the MSL store and acquires the
* master token's read lock.</p>
*
* <p>When the caller no longer requires the master token or its crypto
* context to exist (i.e. it does not expect to receive a response that
* uses the same master token) then it must release the lock.</p>
*
* @param ctx MSL context.
* @return the newest master token or null if there is none.
* @throws InterruptedException if the thread is interrupted while trying
* to acquire the master token's read lock.
* @see #releaseMasterToken(MasterToken)
*/
private MasterToken getNewestMasterToken(final MslContext ctx) throws InterruptedException {
do {
// Get the newest master token. If there is none then immediately
// return.
final MslStore store = ctx.getMslStore();
final MasterToken masterToken = store.getMasterToken();
if (masterToken == null) return null;
// Acquire the master token read lock, creating it if necessary.
final MslContextMasterTokenKey key = new MslContextMasterTokenKey(ctx, masterToken);
final ReadWriteLock newLock = new ReentrantReadWriteLock();
final ReadWriteLock oldLock = masterTokenLocks.putIfAbsent(key, newLock);
final ReadWriteLock finalLock = (oldLock != null) ? oldLock : newLock;
finalLock.readLock().lockInterruptibly();
// Now we have to be tricky and make sure the master token we just
// acquired is still the newest master token. This is necessary
// just in case the master token was deleted between grabbing it
// from the MSL store and acquiring the read lock.
final MasterToken newestMasterToken = store.getMasterToken();
if (masterToken.equals(newestMasterToken))
return masterToken;
// If the master tokens are not the same then release the read
// lock, acquire the write lock, and then delete the master token
// lock (it may already be deleted). Then try again.
finalLock.readLock().unlock();
finalLock.writeLock().lockInterruptibly();
masterTokenLocks.remove(key);
finalLock.writeLock().unlock();
} while (true);
}
/**
* Deletes the provided master token from the MSL store. Doing so requires
* acquiring the master token's write lock.
*
* @param ctx MSL context.
* @param masterToken master token to delete. May be null.
* @throws InterruptedException if the thread is interrupted while trying
* to acquire the master token's write lock.
*/
private void deleteMasterToken(final MslContext ctx, final MasterToken masterToken) throws InterruptedException {
// Do nothing if the master token is null.
if (masterToken == null)
return;
// Acquire the write lock and delete the master token from the store.
//
// TODO it would be nice to do this on another thread to avoid delaying
// the application.
final MslContextMasterTokenKey key = new MslContextMasterTokenKey(ctx, masterToken);
final ReadWriteLock newLock = new ReentrantReadWriteLock();
final ReadWriteLock oldLock = masterTokenLocks.putIfAbsent(key, newLock);
// ReentrantReadWriteLock requires us to release the read lock if
// we are holding it before acquiring the write lock. If there is
// an old lock then we are already holding the read lock. Otherwise
// no one is holding any locks.
final Lock writeLock;
if (oldLock != null) {
oldLock.readLock().unlock();
writeLock = oldLock.writeLock();
} else {
writeLock = newLock.writeLock();
}
writeLock.lockInterruptibly();
try {
ctx.getMslStore().removeCryptoContext(masterToken);
} finally {
// It should be okay to delete this read/write lock because no
// one should be using the deleted master token anymore; a new
// master token would have been received before deleting the
// old one.
masterTokenLocks.remove(key);
writeLock.unlock();
}
}
/**
* Release the read lock of the provided master token. If no master token
* is provided then this method is a no-op.
*
* @param ctx MSL context.
* @param masterToken the master token. May be null.
* @see #getNewestMasterToken(MslContext)
*/
private void releaseMasterToken(final MslContext ctx, final MasterToken masterToken) {
if (masterToken != null) {
final MslContextMasterTokenKey key = new MslContextMasterTokenKey(ctx, masterToken);
final ReadWriteLock lock = masterTokenLocks.get(key);
// The lock may be null if the master token was deleted.
if (lock != null)
lock.readLock().unlock();
}
}
/**
* Update the MSL store crypto contexts with the crypto contexts of the
* message being sent. Only crypto contexts for master tokens used by the
* local entity for message authentication are saved.
*
* @param ctx MSL context.
* @param messageHeader outgoing message header.
* @param keyExchangeData outgoing message key exchange data.
* @throws InterruptedException if the thread is interrupted while trying
* to delete an old master token.
*/
private void updateCryptoContexts(final MslContext ctx, final MessageHeader messageHeader, final KeyExchangeData keyExchangeData) throws InterruptedException {
// In trusted network mode save the crypto context of the message's key
// response data as an optimization.
final MslStore store = ctx.getMslStore();
if (!ctx.isPeerToPeer() && keyExchangeData != null) {
final KeyResponseData keyResponseData = keyExchangeData.keyResponseData;
final ICryptoContext keyxCryptoContext = keyExchangeData.cryptoContext;
final MasterToken keyxMasterToken = keyResponseData.getMasterToken();
store.setCryptoContext(keyxMasterToken, keyxCryptoContext);
// Delete the old master token. Even if we receive future messages
// with this master token we can reconstruct the crypto context.
deleteMasterToken(ctx, messageHeader.getMasterToken());
}
}
/**
* Update the MSL store crypto contexts with the crypto contexts provided
* by received message.
*
* @param ctx MSL context.
* @param request previous message the response was received for.
* @param response received message input stream.
* @throws InterruptedException if the thread is interrupted while trying
* to delete an old master token.
*/
private void updateCryptoContexts(final MslContext ctx, final MessageHeader request, final MessageInputStream response) throws InterruptedException {
// Do nothing for error messages.
final MessageHeader messageHeader = response.getMessageHeader();
if (messageHeader == null)
return;
// Save the crypto context of the message's key response data.
final MslStore store = ctx.getMslStore();
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null) {
final MasterToken keyxMasterToken = keyResponseData.getMasterToken();
store.setCryptoContext(keyxMasterToken, response.getKeyExchangeCryptoContext());
// Delete the old master token. We won't use it anymore to build
// messages.
deleteMasterToken(ctx, request.getMasterToken());
}
}
/**
* Update the MSL store by removing any service tokens marked for deletion
* and adding/replacing any other service tokens contained in the message
* header.
*
* @param ctx MSL context.
* @param masterToken master for the service tokens.
* @param userIdToken user ID token for the service tokens.
* @param serviceTokens the service tokens to update.
* @throws MslException if a token cannot be removed or added/replaced
* because of a master token or user ID token mismatch.
*/
private static void storeServiceTokens(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken, final Set<ServiceToken> serviceTokens) throws MslException {
// Remove deleted service tokens from the store. Update stored
// service tokens.
final MslStore store = ctx.getMslStore();
final Set<ServiceToken> storeTokens = new HashSet<ServiceToken>();
for (final ServiceToken token : serviceTokens) {
// Skip service tokens that are bound to a master token if the
// local entity issued the master token.
if (token.isBoundTo(masterToken) && masterToken.isVerified())
continue;
final byte[] data = token.getData();
if (data != null && data.length == 0)
store.removeServiceTokens(token.getName(), token.isMasterTokenBound() ? masterToken : null, token.isUserIdTokenBound() ? userIdToken : null);
else
storeTokens.add(token);
}
store.addServiceTokens(storeTokens);
}
/**
* <p>Create a new message builder that will craft a new message.</p>
*
* <p>If a master token is available it will be used to build the new
* message and its read lock will be acquired. The caller must release the
* read lock after it has either received a response to the built request
* or after sending the message if no response is expected.</p>
*
* <p>If a master token is available and a user ID is provided by the
* message context the user ID token for that user ID will be used to build
* the message if the user ID token is bound to the master token.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @return the message builder.
* @throws InterruptedException if the thread is interrupted while trying
* to acquire the master token's read lock.
*/
private MessageBuilder buildRequest(final MslContext ctx, final MessageContext msgCtx) throws InterruptedException {
final MslStore store = ctx.getMslStore();
// Grab the newest master token.
final MasterToken masterToken = getNewestMasterToken(ctx);
try {
final UserIdToken userIdToken;
if (masterToken != null) {
// Grab the user ID token for the message's user. It may not be bound
// to the newest master token if the newest master token invalidated
// it.
final String userId = msgCtx.getUserId();
final UserIdToken storedUserIdToken = (userId != null) ? store.getUserIdToken(userId) : null;
userIdToken = (storedUserIdToken != null && storedUserIdToken.isBoundTo(masterToken)) ? storedUserIdToken : null;
} else {
userIdToken = null;
}
final MessageBuilder builder = messageFactory.createRequest(ctx, masterToken, userIdToken);
builder.setNonReplayable(msgCtx.isNonReplayable());
return builder;
} catch (final MslException e) {
// Release the master token lock.
releaseMasterToken(ctx, masterToken);
throw new MslInternalException("User ID token not bound to master token despite internal check.", e);
} catch (final RuntimeException re) {
// Release the master token lock.
releaseMasterToken(ctx, masterToken);
throw re;
}
}
/**
* <p>Create a new message builder that will craft a new message in
* response to another message. The constructed message may be used as a
* request.</p>
*
* <p>In peer-to-peer mode if the response does not have a primary master
* token and a master token is available then it will be used to build the
* new message and its read lock will be acquired. The caller must release
* the read lock after it has either received a response to the built
* request or after sending the message if no response is expected.</p>
*
* <p>In peer-to-peer mode if a master token is being used to build the new
* message and a user ID is provided by the message context, the user ID
* token for that user ID will be used to build the message if the user ID
* token is bound to the master token.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param request message header to respond to.
* @return the message builder.
* @throws MslMasterTokenException if the provided message's master token
* is not trusted.
* @throws MslCryptoException if the crypto context from a key exchange
* cannot be created.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created.
* @throws MslUserAuthException if there is an error with the user
* authentication data or the user ID token cannot be created.
* @throws MslException if a user ID token in the message header is not
* bound to its corresponding master token.
* @throws InterruptedException if the thread is interrupted while trying
* to acquire the master token's read lock. (Only applicable in
* peer-to-peer mode.)
*/
private MessageBuilder buildResponse(final MslContext ctx, final MessageContext msgCtx, final MessageHeader request) throws MslKeyExchangeException, MslCryptoException, MslMasterTokenException, MslUserAuthException, MslException, InterruptedException {
// Create the response.
final MessageBuilder builder = messageFactory.createResponse(ctx, request);
builder.setNonReplayable(msgCtx.isNonReplayable());
// Trusted network clients should use the newest master token. Trusted
// network servers must not use a newer master token. This method is
// only called by trusted network clients after a handshake response is
// received so if the request does not contain key response data then
// we know the local entity is a trusted network server and should
// return immediately.
if (!ctx.isPeerToPeer() && request.getKeyResponseData() == null)
return builder;
// In peer-to-peer mode the primary master token may no longer be known
// if it was renewed between calls to receive() and respond()
// (otherwise we would have held a lock). In this case, we need to
// use the newest primary authentication tokens.
//
// Likewise, if the primary authentication tokens are not already set
// then use what we have received.
//
// Either way we should be able to use the newest master token,
// acquiring the read lock at the same time which we definitely want.
final MasterToken masterToken = getNewestMasterToken(ctx);
try {
final UserIdToken userIdToken;
if (masterToken != null) {
// Grab the user ID token for the message's user. It may not be
// bound to the newest master token if the newest master token
// invalidated it.
final String userId = msgCtx.getUserId();
final MslStore store = ctx.getMslStore();
final UserIdToken storedUserIdToken = (userId != null) ? store.getUserIdToken(userId) : null;
userIdToken = (storedUserIdToken != null && storedUserIdToken.isBoundTo(masterToken)) ? storedUserIdToken : null;
} else {
userIdToken = null;
}
// Set the authentication tokens.
builder.setAuthTokens(masterToken, userIdToken);
return builder;
} catch (final RuntimeException e) {
// Release the master token lock.
releaseMasterToken(ctx, masterToken);
throw e;
}
}
/**
* <p>Create a new message builder that will craft a new message based on
* another message. The constructed message will have a randomly assigned
* message ID, thus detaching it from the message being responded to, and
* may be used as a request.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param request message header to respond to.
* @return the message builder.
* @throws MslCryptoException if there is an error accessing the remote
* entity identity.
* @throws MslException if any of the request's user ID tokens is not bound
* to its master token.
*/
private MessageBuilder buildDetachedResponse(final MslContext ctx, final MessageContext msgCtx, final MessageHeader request) throws MslCryptoException, MslException {
// Create an idempotent response. Assign a random message ID.
final MessageBuilder builder = messageFactory.createIdempotentResponse(ctx, request);
builder.setNonReplayable(msgCtx.isNonReplayable());
builder.setMessageId(MslUtils.getRandomLong(ctx));
return builder;
}
/**
* The result of building an error response.
*/
private static class ErrorResult {
/**
* Create a new result with the provided request builder and message
* context.
*
* @param builder
* @param msgCtx
*/
public ErrorResult(final MessageBuilder builder, final MessageContext msgCtx) {
this.builder = builder;
this.msgCtx = msgCtx;
}
/** The new request to send. */
public final MessageBuilder builder;
/** The new message context to use. */
public final MessageContext msgCtx;
}
/**
* Creates a message builder and message context appropriate for re-sending
* the original message in response to the received error.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param sent result of original sent message.
* @param errorHeader received error header.
* @return the message builder and message context that should be used to
* re-send the original request in response to the received error
* or null if the error cannot be handled (i.e. should be returned
* to the application).
* @throws MslException if there is an error creating the message.
* @throws InterruptedException if the thread is interrupted while trying
* to acquire the master token lock (user re-authentication only).
*/
private ErrorResult buildErrorResponse(final MslContext ctx, final MessageContext msgCtx, final SendResult sent, final ErrorHeader errorHeader) throws MslException, InterruptedException {
// Handle the error.
final MessageHeader requestHeader = sent.request.getMessageHeader();
final List<PayloadChunk> payloads = sent.request.getPayloads();
final MslConstants.ResponseCode errorCode = errorHeader.getErrorCode();
switch (errorCode) {
case ENTITYDATA_REAUTH:
case ENTITY_REAUTH:
{
// If the MSL context cannot provide new entity authentication
// data then return null. This function should never return
// null.
try {
final MslContext.ReauthCode reauthCode = MslContext.ReauthCode.valueOf(errorCode);
if (ctx.getEntityAuthenticationData(reauthCode) == null)
return null;
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Unsupported response code mapping onto entity re-authentication codes.", e);
}
// Resend the request without a master token or user ID token.
// Make sure the use the error header message ID + 1.
final long messageId = MessageBuilder.incrementMessageId(errorHeader.getMessageId());
final MessageContext resendMsgCtx = new ResendMessageContext(payloads, msgCtx);
final MessageBuilder requestBuilder = messageFactory.createRequest(ctx, null, null, messageId);
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
requestBuilder.setPeerAuthTokens(peerMasterToken, peerUserIdToken);
}
requestBuilder.setNonReplayable(resendMsgCtx.isNonReplayable());
return new ErrorResult(requestBuilder, resendMsgCtx);
}
case USERDATA_REAUTH:
case SSOTOKEN_REJECTED:
{
// If the message context cannot provide user authentication
// data then return null.
try {
final MessageContext.ReauthCode reauthCode = MessageContext.ReauthCode.valueOf(errorCode);
if (msgCtx.getUserAuthData(reauthCode, false, true) == null)
return null;
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Unsupported response code mapping onto user re-authentication codes.", e);
}
// Otherwise we have now triggered the need for new user
// authentication data. Fall through.
}
case USER_REAUTH:
{
// Grab the newest master token and its read lock.
final MasterToken masterToken = getNewestMasterToken(ctx);
// Resend the request without a user ID token.
// Make sure the use the error header message ID + 1.
final long messageId = MessageBuilder.incrementMessageId(errorHeader.getMessageId());
final MessageContext resendMsgCtx = new ResendMessageContext(payloads, msgCtx);
final MessageBuilder requestBuilder = messageFactory.createRequest(ctx, masterToken, null, messageId);
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
requestBuilder.setPeerAuthTokens(peerMasterToken, peerUserIdToken);
}
requestBuilder.setNonReplayable(resendMsgCtx.isNonReplayable());
return new ErrorResult(requestBuilder, resendMsgCtx);
}
case KEYX_REQUIRED:
{
// This error will only be received by trusted network clients
// and peer-to-peer entities that do not have a master token.
// Make sure the use the error header message ID + 1.
final long messageId = MessageBuilder.incrementMessageId(errorHeader.getMessageId());
final MessageContext resendMsgCtx = new ResendMessageContext(payloads, msgCtx);
final MessageBuilder requestBuilder = messageFactory.createRequest(ctx, null, null, messageId);
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
requestBuilder.setPeerAuthTokens(peerMasterToken, peerUserIdToken);
}
// Mark the message as renewable to make sure the response can
// be encrypted. During renewal lock acquisition we will either
// block until we acquire the renewal lock or receive a master
// token.
requestBuilder.setRenewable(true);
requestBuilder.setNonReplayable(resendMsgCtx.isNonReplayable());
return new ErrorResult(requestBuilder, resendMsgCtx);
}
case EXPIRED:
{
// Grab the newest master token and its read lock.
final MasterToken masterToken = getNewestMasterToken(ctx);
final UserIdToken userIdToken;
if (masterToken != null) {
// Grab the user ID token for the message's user. It may not be bound
// to the newest master token if the newest master token invalidated
// it.
final String userId = msgCtx.getUserId();
final MslStore store = ctx.getMslStore();
final UserIdToken storedUserIdToken = (userId != null) ? store.getUserIdToken(userId) : null;
userIdToken = (storedUserIdToken != null && storedUserIdToken.isBoundTo(masterToken)) ? storedUserIdToken : null;
} else {
userIdToken = null;
}
// Resend the request.
final long messageId = MessageBuilder.incrementMessageId(errorHeader.getMessageId());
final MessageContext resendMsgCtx = new ResendMessageContext(payloads, msgCtx);
final MessageBuilder requestBuilder = messageFactory.createRequest(ctx, masterToken, userIdToken, messageId);
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
requestBuilder.setPeerAuthTokens(peerMasterToken, peerUserIdToken);
}
// If the newest master token is equal to the previous
// request's master token then mark this message as renewable.
// During renewal lock acquisition we will either block until
// we acquire the renewal lock or receive a master token.
//
// Check for a missing master token in case the remote entity
// returned an incorrect error code.
final MasterToken requestMasterToken = requestHeader.getMasterToken();
if (requestMasterToken == null || requestMasterToken.equals(masterToken))
requestBuilder.setRenewable(true);
requestBuilder.setNonReplayable(resendMsgCtx.isNonReplayable());
return new ErrorResult(requestBuilder, resendMsgCtx);
}
case REPLAYED:
{
// This error will be received if the previous request's non-
// replayable ID is not accepted by the remote entity. In this
// situation simply try again.
//
// Grab the newest master token and its read lock.
final MasterToken masterToken = getNewestMasterToken(ctx);
final UserIdToken userIdToken;
if (masterToken != null) {
// Grab the user ID token for the message's user. It may not be bound
// to the newest master token if the newest master token invalidated
// it.
final String userId = msgCtx.getUserId();
final MslStore store = ctx.getMslStore();
final UserIdToken storedUserIdToken = (userId != null) ? store.getUserIdToken(userId) : null;
userIdToken = (storedUserIdToken != null && storedUserIdToken.isBoundTo(masterToken)) ? storedUserIdToken : null;
} else {
userIdToken = null;
}
// Resend the request.
final long messageId = MessageBuilder.incrementMessageId(errorHeader.getMessageId());
final MessageContext resendMsgCtx = new ResendMessageContext(payloads, msgCtx);
final MessageBuilder requestBuilder = messageFactory.createRequest(ctx, masterToken, userIdToken, messageId);
if (ctx.isPeerToPeer()) {
final MasterToken peerMasterToken = requestHeader.getPeerMasterToken();
final UserIdToken peerUserIdToken = requestHeader.getPeerUserIdToken();
requestBuilder.setPeerAuthTokens(peerMasterToken, peerUserIdToken);
}
// Mark the message as replayable or not as dictated by the
// message context.
requestBuilder.setNonReplayable(resendMsgCtx.isNonReplayable());
return new ErrorResult(requestBuilder, resendMsgCtx);
}
default:
// Nothing to do. Return null.
return null;
}
}
/**
* Called after successfully handling an error message to delete the old
* invalid crypto contexts and bound service tokens associated with the
* invalid master token or user ID token.
*
* @param ctx MSL context.
* @param requestHeader initial request that generated the error.
* @param errorHeader error response received and successfully handled.
* @throws MslException if the user ID token is not bound to the master
* token. (This should not happen.)
* @throws InterruptedException if the thread is interrupted while trying
* to delete the old master token.
*/
private void cleanupContext(final MslContext ctx, final MessageHeader requestHeader, final ErrorHeader errorHeader) throws MslException, InterruptedException {
// The data-reauth error codes also delete tokens in case those errors
// are returned when a token does exist.
switch (errorHeader.getErrorCode()) {
case ENTITY_REAUTH:
case ENTITYDATA_REAUTH:
{
// The old master token is invalid. Delete the old
// crypto context and any bound service tokens.
deleteMasterToken(ctx, requestHeader.getMasterToken());
break;
}
case USER_REAUTH:
case USERDATA_REAUTH:
{
// The old user ID token is invalid. Delete the old user ID
// token and any bound service tokens. It is okay to stomp on
// other requests when doing this because automatically
// generated messages and replies to outstanding requests that
// use the user ID token and service tokens will work fine.
//
// This will be a no-op if we received a new user ID token that
// overwrote the old one.
final MasterToken masterToken = requestHeader.getMasterToken();
final UserIdToken userIdToken = requestHeader.getUserIdToken();
if (masterToken != null && userIdToken != null) {
final MslStore store = ctx.getMslStore();
store.removeUserIdToken(userIdToken);
}
break;
}
default:
// No cleanup required.
break;
}
}
/**
* The result of sending a message.
*/
private static class SendResult {
/**
* Create a new result with the provided message output stream
* containing the cached application data (which was not sent if the
* message was a handshake).
*
* @param request request message output stream.
* @param handshake true if a handshake message was sent and the
* application data was not sent.
*/
private SendResult(final MessageOutputStream request, final boolean handshake) {
this.request = request;
this.handshake = handshake;
}
/** The request message output stream. */
public final MessageOutputStream request;
/** True if the message was a handshake (application data was not sent). */
public final boolean handshake;
}
/**
* <p>Send a message. The message context will be used to build the message.
* If the message will be sent then the stored master token crypto contexts
* and service tokens will be updated just prior to sending.</p>
*
* <p>If the application data must be encrypted but the message does not
* support payload encryption then a handshake message will be sent. This
* will be indicated by the returned result.</p>
*
* <p>N.B. The message builder must be set renewable and non-replayable
* before calling this method. If the application data must be delayed then
* this specific message will be sent replayable regardless of the builder
* non-replayable value.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param out remote entity output stream.
* @param builder message builder.
* @param closeDestination true if the remote entity output stream must
* be closed when the constructed message output stream is closed.
* @return a result containing the sent message header and a copy of the
* application data.
* @throws IOException if there is an error writing the message.
* @throws MslMessageException if there is an error building the request.
* @throws MslEncodingException if there is an error encoding the JSON
* data.
* @throws MslCryptoException if there is an error encrypting or signing
* the message.
* @throws MslMasterTokenException if the header master token is not
* trusted and needs to be to accept this message header.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
* @throws MslKeyExchangeException if there is an error generating the key
* request data.
* @throws MslException if there was an error updating the service tokens
* or building the message header.
* @throws InterruptedException if the thread is interrupted while trying
* to delete an old master token the sent message is replacing.
*/
private SendResult send(final MslContext ctx, final MessageContext msgCtx, final OutputStream out, final MessageBuilder builder, final boolean closeDestination) throws IOException, MslMessageException, MslEncodingException, MslCryptoException, MslMasterTokenException, MslEntityAuthException, MslKeyExchangeException, MslException, InterruptedException {
final MasterToken masterToken = builder.getMasterToken();
UserIdToken userIdToken = builder.getUserIdToken();
final UserIdToken peerUserIdToken = builder.getPeerUserIdToken();
// Ask the message context for user authentication data.
boolean userAuthDataDelayed = false;
final String userId = msgCtx.getUserId();
if (userId != null) {
// If we are not including a user ID token, the user authentication
// data is required.
final boolean required = (userIdToken == null);
final UserAuthenticationData userAuthData = msgCtx.getUserAuthData(null, builder.isRenewable(), required);
if (userAuthData != null) {
// We can only include user authentication data if the message
// header will be encrypted and integrity protected.
if (builder.willEncryptHeader() && builder.willIntegrityProtectHeader())
builder.setUserAuthenticationData(userAuthData);
// If the message should include user authentication data but
// cannot at this time then we also cannot send the application
// data as it may be user-specific. There is also no user ID token
// otherwise the header will be encrypted.
else
userAuthDataDelayed = true;
}
// If user authentication data is required but was not provided
// then this message may be associated with a user but not have any
// user authentication data. For example upon user creation.
}
// If there is no user ID token for the remote user then check if a
// user ID token should be created and attached.
if (!ctx.isPeerToPeer() && userIdToken == null ||
ctx.isPeerToPeer() && peerUserIdToken == null)
{
final MslUser user = msgCtx.getUser();
if (user != null) {
builder.setUser(user);
// The user ID token may have changed and we need the latest one to
// store the service tokens below.
userIdToken = builder.getUserIdToken();
}
}
// If we have not delayed the user authentication data, and the message
// payloads either do not need to be encrypted or can be encrypted with
// this message, and the message payloads either do not need to be
// integrity protected or can be integrity protected with this message,
// and the message is either replayable or the message will be sent non-
// replayable and has a master token, then we can write the application
// data now.
final boolean writeData = !userAuthDataDelayed &&
(!msgCtx.isEncrypted() || builder.willEncryptPayloads()) &&
(!msgCtx.isIntegrityProtected() || builder.willIntegrityProtectPayloads()) &&
(!msgCtx.isNonReplayable() || (builder.isNonReplayable() && masterToken != null));
final boolean handshake = !writeData;
// Set the message handshake flag.
builder.setHandshake(handshake);
// If this message is renewable...
final Set<KeyRequestData> keyRequests = new HashSet<KeyRequestData>();
if (builder.isRenewable()) {
// Ask for key request data if we are using entity authentication
// data or if the master token needs renewing or if the message is
// non-replayable.
final Date now = ctx.getRemoteTime();
if (masterToken == null || masterToken.isRenewable(now) || msgCtx.isNonReplayable()) {
keyRequests.addAll(msgCtx.getKeyRequestData());
for (final KeyRequestData keyRequest : keyRequests)
builder.addKeyRequestData(keyRequest);
}
}
// Ask the caller to perform any final modifications to the
// message and then build the message.
final MessageServiceTokenBuilder serviceTokenBuilder = new MessageServiceTokenBuilder(ctx, msgCtx, builder);
msgCtx.updateServiceTokens(serviceTokenBuilder, handshake);
final MessageHeader requestHeader = builder.getHeader();
// Deliver the header that will be sent to the debug context.
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
if (debugCtx != null) debugCtx.sentHeader(requestHeader);
// Update the stored crypto contexts just before sending the
// message so we can receive new messages immediately after it is
// sent.
final KeyExchangeData keyExchangeData = builder.getKeyExchangeData();
updateCryptoContexts(ctx, requestHeader, keyExchangeData);
// Update the stored service tokens.
final MasterToken tokenVerificationMasterToken = (keyExchangeData != null) ? keyExchangeData.keyResponseData.getMasterToken() : masterToken;
final Set<ServiceToken> serviceTokens = requestHeader.getServiceTokens();
storeServiceTokens(ctx, tokenVerificationMasterToken, userIdToken, serviceTokens);
// We will either use the header crypto context or the key exchange
// data crypto context in trusted network mode to process the message
// payloads.
final ICryptoContext payloadCryptoContext;
if (!ctx.isPeerToPeer() && keyExchangeData != null)
payloadCryptoContext = keyExchangeData.cryptoContext;
else
payloadCryptoContext = requestHeader.getCryptoContext();
// Send the request.
final OutputStream os = (filterFactory != null) ? filterFactory.getOutputStream(out) : out;
final MessageOutputStream request = messageFactory.createOutputStream(ctx, os, requestHeader, payloadCryptoContext);
request.closeDestination(closeDestination);
// If it is okay to write the data then ask the application to write it
// and return the real output stream. Otherwise it will be asked to do
// so after the handshake is completed.
if (!handshake)
msgCtx.write(request);
// Return the result.
return new SendResult(request, handshake);
}
/**
* <p>Receive a message.</p>
*
* <p>If a message is received the stored master tokens, crypto contexts,
* user ID tokens, and service tokens will be updated.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param request message header of the previously sent message, if any,
* the received message is responding to. May be null.
* @return the received message.
* @throws IOException if there is a problem reading from the input stream.
* @throws MslEncodingException if there is an error parsing the message.
* @throws MslCryptoException if there is an error decrypting or verifying
* the header or creating the message payload crypto context.
* @throws MslEntityAuthException if unable to create the entity
* authentication data.
* @throws MslUserAuthException if unable to create the user authentication
* data.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be.
* @throws MslKeyExchangeException if there is an error with the key
* request data or key response data or the key exchange scheme is
* not supported.
* @throws MslException if the message does not contain an entity
* authentication data or a master token, or a token is improperly
* bound to another token, or there is an error updating the
* service tokens.
* @throws MslMessageException if the message does not contain an entity
* authentication data or a master token, or a token is improperly
* bound to another token, or there is an error updating the
* service tokens, or the header data is missing or invalid, or the
* message ID is negative, or the message is not encrypted and
* contains user authentication data, or if the message master
* token is expired and the message is not renewable.
* @throws InterruptedException if the thread is interrupted while trying
* to delete an old master token the received message is replacing.
*/
private MessageInputStream receive(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final MessageHeader request) throws IOException, MslEncodingException, MslEntityAuthException, MslCryptoException, MslUserAuthException, MslMessageException, MslKeyExchangeException, MslMasterTokenException, MslException, InterruptedException {
// Grab the response.
final Set<KeyRequestData> keyRequestData = new HashSet<KeyRequestData>();
if (request != null)
keyRequestData.addAll(request.getKeyRequestData());
final Map<String,ICryptoContext> cryptoContexts = msgCtx.getCryptoContexts();
final InputStream is = (filterFactory != null) ? filterFactory.getInputStream(in) : in;
final MessageInputStream response = messageFactory.createInputStream(ctx, is, keyRequestData, cryptoContexts);
// Deliver the received header to the debug context.
final MessageHeader responseHeader = response.getMessageHeader();
final ErrorHeader errorHeader = response.getErrorHeader();
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
if (debugCtx != null) debugCtx.receivedHeader((responseHeader != null) ? responseHeader : errorHeader);
// Pull the response master token or entity authentication data and
// user ID token or user authentication data to attach them to any
// thrown exceptions.
final MasterToken masterToken;
final EntityAuthenticationData entityAuthData;
final UserIdToken userIdToken;
final UserAuthenticationData userAuthData;
if (responseHeader != null) {
masterToken = responseHeader.getMasterToken();
entityAuthData = responseHeader.getEntityAuthenticationData();
userIdToken = responseHeader.getUserIdToken();
userAuthData = responseHeader.getUserAuthenticationData();
} else {
masterToken = null;
entityAuthData = errorHeader.getEntityAuthenticationData();
userIdToken = null;
userAuthData = null;
}
try {
// If there is a request make sure the response message ID equals
// the request message ID + 1.
if (request != null) {
// Only enforce this for message headers and error headers that are
// not entity re-authenticate or entity data re-authenticate (as in
// those cases the remote entity is not always able to extract the
// request message ID).
final ResponseCode errorCode = (errorHeader != null) ? errorHeader.getErrorCode() : null;
if (responseHeader != null ||
(errorCode != ResponseCode.FAIL && errorCode != ResponseCode.TRANSIENT_FAILURE && errorCode != ResponseCode.ENTITY_REAUTH && errorCode != ResponseCode.ENTITYDATA_REAUTH))
{
final long responseMessageId = (responseHeader != null) ? responseHeader.getMessageId() : errorHeader.getMessageId();
final long expectedMessageId = MessageBuilder.incrementMessageId(request.getMessageId());
if (responseMessageId != expectedMessageId)
throw new MslMessageException(MslError.UNEXPECTED_RESPONSE_MESSAGE_ID, "expected " + expectedMessageId + "; received " + responseMessageId);
}
}
// Verify expected identity if specified.
final String expectedIdentity = msgCtx.getRemoteEntityIdentity();
if (expectedIdentity != null) {
// Reject if the remote entity identity is not equal to the
// message entity authentication data identity.
if (entityAuthData != null) {
final String entityAuthIdentity = entityAuthData.getIdentity();
if (entityAuthIdentity != null && !expectedIdentity.equals(entityAuthIdentity))
throw new MslMessageException(MslError.MESSAGE_SENDER_MISMATCH, "expected " + expectedIdentity + "; received " + entityAuthIdentity);
}
// Reject if in peer-to-peer mode and the message sender does
// not match.
if (ctx.isPeerToPeer()) {
final String sender = response.getIdentity();
if (sender != null && !expectedIdentity.equals(sender))
throw new MslMessageException(MslError.MESSAGE_SENDER_MISMATCH, "expected " + expectedIdentity + "; received " + sender);
}
}
// Process the response.
if (responseHeader != null) {
// If there is a request update the stored crypto contexts.
if (request != null)
updateCryptoContexts(ctx, request, response);
// In trusted network mode the local tokens are the primary tokens.
// In peer-to-peer mode they are the peer tokens. The master token
// might be in the key response data.
final KeyResponseData keyResponseData = responseHeader.getKeyResponseData();
final MasterToken tokenVerificationMasterToken;
final UserIdToken localUserIdToken;
final Set<ServiceToken> serviceTokens;
if (!ctx.isPeerToPeer()) {
tokenVerificationMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : responseHeader.getMasterToken();
localUserIdToken = responseHeader.getUserIdToken();
serviceTokens = responseHeader.getServiceTokens();
} else {
tokenVerificationMasterToken = (keyResponseData != null) ? keyResponseData.getMasterToken() : responseHeader.getPeerMasterToken();
localUserIdToken = responseHeader.getPeerUserIdToken();
serviceTokens = responseHeader.getPeerServiceTokens();
}
// Save any returned user ID token if the local entity is not the
// issuer of the user ID token.
final String userId = msgCtx.getUserId();
if (userId != null && localUserIdToken != null && !localUserIdToken.isVerified())
ctx.getMslStore().addUserIdToken(userId, localUserIdToken);
// Update the stored service tokens.
storeServiceTokens(ctx, tokenVerificationMasterToken, localUserIdToken, serviceTokens);
}
// Update the synchronized clock if we are a trusted network client
// (there is a request) or peer-to-peer entity.
final Date timestamp = (responseHeader != null) ? responseHeader.getTimestamp() : errorHeader.getTimestamp();
if (timestamp != null && (request != null || ctx.isPeerToPeer()))
ctx.updateRemoteTime(timestamp);
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setUserIdToken(userIdToken);
e.setUserAuthenticationData(userAuthData);
throw e;
}
// Return the result.
return response;
}
/**
* Indicates response expectations for a specific request.
*/
private static enum Receive {
/** A response is always expected. */
ALWAYS,
/** A response is only expected if tokens are being renewed. */
RENEWING,
/** A response is never expected. */
NEVER
}
/**
* The result of sending and receiving messages.
*/
private static class SendReceiveResult extends SendResult {
/**
* Create a new result with the provided response and send result.
*
* @param response response message input stream. May be {@code null}.
* @param sent sent message result.
*/
public SendReceiveResult(final MessageInputStream response, final SendResult sent) {
super(sent.request, sent.handshake);
this.response = response;
}
/** The response message input stream. */
public final MessageInputStream response;
}
/**
* <p>Send the provided request and optionally receive a response from the
* remote entity. The method will attempt to receive a response if one of
* the following is met:
* <ul>
* <li>the caller indicates a response is expected</li>
* <li>a handshake message was sent</li>
* <li>key request data appears in the request</li>
* <li>a renewable message with user authentication data was sent</li>
* </ul></p>
*
* <p>This method is only used from trusted network clients and peer-to-
* peer entities.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param builder request message builder.
* @param receive indicates if a response should always be expected, should
* only be expected if the master token or user ID token will be
* renewed, or should never be expected.
* @param closeStreams true if the remote entity input and output streams
* must be closed when the constructed message input and output
* streams are closed.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @return the received message or {@code null} if cancelled or interrupted.
* @throws IOException if there was an error reading or writing a
* message.
* @throws MslEncodingException if there is an error parsing or encoding a
* message.
* @throws MslCryptoException if there is an error encrypting/decrypting or
* signing/verifying a message header or creating the message
* payload crypto context.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
* @throws MslUserAuthException if unable to create the user authentication
* data.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be.
* @throws MslKeyExchangeException if there is an error with the key
* request data or key response data or the key exchange scheme is
* not supported.
* @throws MslMessageException if the message master token is expired and
* the message is not renewable, if there is an error building the
* request, or if the response message ID does not equal the
* expected value, or the header data is missing or invalid, or the
* message ID is negative, or the message is not encrypted and
* contains user authentication data.
* @throws MslException if the message does not contain an entity
* authentication data or a master token, or a token is improperly
* bound to another token, or there is an error updating the
* service tokens, or there was an error building the message
* header.
* @throws InterruptedException if the thread is interrupted while trying
* to delete an old master token the received message is replacing.
* @throws TimeoutException if the thread timed out while trying to acquire
* a master token from a renewing thread.
*/
private SendReceiveResult sendReceive(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageBuilder builder, final Receive receive, final boolean closeStreams, final int timeout) throws IOException, MslEncodingException, MslCryptoException, MslEntityAuthException, MslUserAuthException, MslMessageException, MslMasterTokenException, MslKeyExchangeException, MslException, InterruptedException, TimeoutException {
// Attempt to acquire the renewal lock.
final BlockingQueue<MasterToken> renewalQueue = new ArrayBlockingQueue<MasterToken>(1, true);
final boolean renewing;
try {
renewing = acquireRenewalLock(ctx, msgCtx, renewalQueue, builder, timeout);
} catch (final InterruptedException e) {
// Release the master token lock.
releaseMasterToken(ctx, builder.getMasterToken());
// This should only be if we were cancelled so return null.
return null;
} catch (final TimeoutException | RuntimeException e) {
// Release the master token lock.
releaseMasterToken(ctx, builder.getMasterToken());
throw e;
}
// Send the request and receive the response.
final SendResult sent;
MessageInputStream response = null;
try {
// Send the request.
builder.setRenewable(renewing);
sent = send(ctx, msgCtx, out, builder, closeStreams);
// Receive the response if expected, if we sent a handshake request,
// or if we expect a response when renewing tokens and either key
// request data was included or a master token and user
// authentication data was included in a renewable message.
final MessageHeader requestHeader = sent.request.getMessageHeader();
final Set<KeyRequestData> keyRequestData = requestHeader.getKeyRequestData();
if (receive == Receive.ALWAYS || sent.handshake ||
(receive == Receive.RENEWING &&
(!keyRequestData.isEmpty() ||
(requestHeader.isRenewable() && requestHeader.getMasterToken() != null && requestHeader.getUserAuthenticationData() != null))))
{
response = receive(ctx, msgCtx, in, requestHeader);
response.closeSource(closeStreams);
// If we received an error response then cleanup.
final ErrorHeader errorHeader = response.getErrorHeader();
if (errorHeader != null)
cleanupContext(ctx, requestHeader, errorHeader);
}
} finally {
// Release the renewal lock.
if (renewing)
releaseRenewalLock(ctx, renewalQueue, response);
// Release the master token lock.
releaseMasterToken(ctx, builder.getMasterToken());
}
// Return the response.
return new SendReceiveResult(response, sent);
}
/**
* <p>Attempt to acquire the renewal lock if the message will need it using
* the given blocking queue.</p>
*
* <p>If anti-replay is required then this method will block until the
* renewal lock is acquired.</p>
*
* <p>If the message has already been marked renewable then this method
* will block until the renewal lock is acquired or a renewing thread
* delivers a new master token to this builder.</p>
*
* <p>If encryption is required but the builder will not be able to encrypt
* the message payloads, or if integrity protection is required but the
* builder will not be able to integrity protect the message payloads, or
* if the builder's master token is expired, or if there is no user ID
* token but the message is associated with a user and the builder will not
* be able to encrypt and integrity protect the message header, then this
* method will block until the renewal lock is acquired or a renewing
* thread delivers a master token to this builder.</p>
*
* <p>If the message is requesting tokens in response but there is no
* master token, or there is no user ID token but the message is associated
* with a user, then this method will block until the renewal lock is
* acquired or a renewing thread delivers a master token to this builder
* and a user ID token is also available if the message is associated with
* a user.</p>
*
* <p>If there is no master token, or either the master token or the user
* ID token is renewable, or there is no user ID token but the message is
* associated with a user and the builder will be able to encrypt the
* message header then this method will attempt to acquire the renewal
* lock. If unable to do so, it returns null.</p>
*
* <p>If this method returns true, then the renewal lock must be released by
* calling {@code releaseRenewalLock()}.</p>
*
* <p>This method is only used from trusted network clients and peer-to-
* peer entities.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param queue caller's blocking queue.
* @param builder message builder for the message to be sent.
* @param timeout timeout in milliseconds for acquiring the renewal lock
* or receiving a master token.
* @return true if the renewal lock was acquired, false if the builder's
* message is now capable of encryption or the renewal lock is not
* needed.
* @throws InterruptedException if interrupted while waiting to acquire
* a master token from a renewing thread.
* @throws TimeoutException if timed out while waiting to acquire a master
* token from a renewing thread.
* @see #releaseRenewalLock(MslContext, BlockingQueue, MessageInputStream)
*/
private boolean acquireRenewalLock(final MslContext ctx, final MessageContext msgCtx, final BlockingQueue<MasterToken> queue, final MessageBuilder builder, final long timeout) throws InterruptedException, TimeoutException {
MasterToken masterToken = builder.getMasterToken();
UserIdToken userIdToken = builder.getUserIdToken();
final String userId = msgCtx.getUserId();
// If the application data needs to be encrypted and the builder will
// not encrypt payloads, or the application data needs to be integrity
// protected and the builder will not integrity protect payloads, or if
// the master token is expired, or if the message is to be sent with
// user authentication data and the builder will not encrypt and
// integrity protect the header, then we must either mark this message
// as renewable to perform a handshake or get a master token from a
// renewing thread.
//
// If the message has been marked renewable then we must either mark
// this message as renewable or receive a new master token.
//
// If the message must be marked non-replayable and we do not have a
// master token then we must mark this message as renewable to perform
// a handshake or receive a new master token.
final Date startTime = ctx.getRemoteTime();
if ((msgCtx.isEncrypted() && !builder.willEncryptPayloads()) ||
(msgCtx.isIntegrityProtected() && !builder.willIntegrityProtectPayloads()) ||
builder.isRenewable() ||
(masterToken == null && msgCtx.isNonReplayable()) ||
(masterToken != null && masterToken.isExpired(startTime)) ||
(userIdToken == null && userId != null && (!builder.willEncryptHeader() || !builder.willIntegrityProtectHeader())) ||
(msgCtx.isRequestingTokens() && (masterToken == null || (userId != null && userIdToken == null))))
{
do {
// We do not have a master token or this message is non-
// replayable. Try to acquire the renewal lock on this MSL
// context so we can send a handshake message.
final BlockingQueue<MasterToken> ctxRenewingQueue = renewingContexts.putIfAbsent(ctx, queue);
// If there is no one else already renewing then our queue has
// acquired the renewal lock.
if (ctxRenewingQueue == null)
return true;
// Otherwise we need to wait for a master token from the
// renewing request.
final MasterToken newMasterToken = ctxRenewingQueue.poll(timeout, TimeUnit.MILLISECONDS);
// If timed out throw an exception.
if (newMasterToken == null)
throw new TimeoutException("acquireRenewalLock timed out.");
// Put the same master token back on the renewing queue so
// anyone else waiting can also proceed.
ctxRenewingQueue.add(newMasterToken);
// If the renewing request did not acquire a master token then
// try again to acquire renewal ownership.
if (newMasterToken == NULL_MASTER_TOKEN)
continue;
// If the new master token is not equal to the previous master
// token then release the previous master token and get the
// newest master token.
//
// We cannot simply use the new master token directly since we
// have not acquired its master token lock.
final MasterToken previousMasterToken = masterToken;
if (masterToken == null || !masterToken.equals(newMasterToken)) {
releaseMasterToken(ctx, masterToken);
masterToken = getNewestMasterToken(ctx);
// If there is no newest master token (it could have been
// deleted despite just being delivered to us) then try
// again to acquire renewal ownership.
if (masterToken == null)
continue;
}
// The renewing request may have acquired a new user ID token.
// Attach it to this message if the message is associated with
// a user and we do not already have a user ID token.
//
// Unless the previous master token was thrown out, any user ID
// token should still be bound to this new master token. If the
// master token serial number has changed then our user ID
// token is no longer valid and the new one should be attached.
if ((userId != null && userIdToken == null) ||
(userIdToken != null && !userIdToken.isBoundTo(masterToken)))
{
final UserIdToken storedUserIdToken = ctx.getMslStore().getUserIdToken(userId);
userIdToken = (storedUserIdToken != null && storedUserIdToken.isBoundTo(masterToken)) ? storedUserIdToken : null;
}
// Update the message's master token and user ID token.
builder.setAuthTokens(masterToken, userIdToken);
// If the new master token is still expired then try again to
// acquire renewal ownership.
final Date updateTime = ctx.getRemoteTime();
if (masterToken.isExpired(updateTime))
continue;
// If this message is already marked renewable and the received
// master token is the same as the previous master token then
// we must still attempt to acquire the renewal lock.
if (builder.isRenewable() && masterToken.equals(previousMasterToken))
continue;
// If this message is requesting tokens and is associated with
// a user but there is no user ID token then we must still
// attempt to acquire the renewal lock.
if (msgCtx.isRequestingTokens() && userIdToken == null)
continue;
// We may still want to renew, but it is not required. Fall
// through.
break;
} while (true);
}
// If we do not have a master token or the master token should be
// renewed, or we do not have a user ID token but the message is
// associated with a user, or if the user ID token should be renewed,
// then try to mark this message as renewable.
final Date finalTime = ctx.getRemoteTime();
if ((masterToken == null || masterToken.isRenewable(finalTime)) ||
(userIdToken == null && msgCtx.getUserId() != null) ||
(userIdToken != null && userIdToken.isRenewable(finalTime)))
{
// Try to acquire the renewal lock on this MSL context.
final BlockingQueue<MasterToken> ctxRenewingQueue = renewingContexts.putIfAbsent(ctx, queue);
// If there is no one else already renewing then our queue has
// acquired the renewal lock.
if (ctxRenewingQueue == null)
return true;
// Otherwise proceed without acquiring the lock.
return false;
}
// Otherwise we do not need to acquire the renewal lock.
return false;
}
/**
* <p>Release the renewal lock.</p>
*
* <p>Delivers any received master token to the blocking queue. This may be
* a null value if an error message was received or if the received message
* does not contain a master token for the local entity.</p>
*
* <p>If no message was received a null master token will be delivered.</p>
*
* <p>This method is only used from trusted network clients and peer-to-
* peer entities.</p>
*
* @param ctx MSL context.
* @param queue caller's blocking queue.
* @param message received message. May be null if no message was received.
*/
private void releaseRenewalLock(final MslContext ctx, final BlockingQueue<MasterToken> queue, final MessageInputStream message) {
// Sanity check.
if (renewingContexts.get(ctx) != queue)
throw new IllegalStateException("Attempt to release renewal lock that is not owned by this queue.");
// If no message was received then deliver a null master token, release
// the lock, and return immediately.
if (message == null) {
queue.add(NULL_MASTER_TOKEN);
renewingContexts.remove(ctx);
return;
}
// If we received an error message then deliver a null master token,
// release the lock, and return immediately.
final MessageHeader messageHeader = message.getMessageHeader();
if (messageHeader == null) {
queue.add(NULL_MASTER_TOKEN);
renewingContexts.remove(ctx);
return;
}
// If we performed key exchange then the renewed master token should be
// delivered.
final KeyResponseData keyResponseData = messageHeader.getKeyResponseData();
if (keyResponseData != null) {
queue.add(keyResponseData.getMasterToken());
}
// In trusted network mode deliver the header master token. This may be
// null.
else if (!ctx.isPeerToPeer()) {
final MasterToken masterToken = messageHeader.getMasterToken();
if (masterToken != null)
queue.add(masterToken);
else
queue.add(NULL_MASTER_TOKEN);
}
// In peer-to-peer mode deliver the peer master token. This may be
// null.
else {
final MasterToken masterToken = messageHeader.getPeerMasterToken();
if (masterToken != null)
queue.add(masterToken);
else
queue.add(NULL_MASTER_TOKEN);
}
// Release the lock.
renewingContexts.remove(ctx);
}
/**
* Send an error response over the provided output stream.
*
* @param ctx MSL context.
* @param debugCtx message debug context.
* @param requestHeader message the error is being sent in response to. May
* be {@code null}.
* @param messageId request message ID. May be {@code null}.
* @param error the MSL error.
* @param userMessage localized user-consumable error message. May be
* {@code null}.
* @param out message output stream.
* @throws MslEncodingException if there is an error encoding the message.
* @throws MslCryptoException if there is an error encrypting or signing
* the message.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
* @throws MslMessageException if no entity authentication data was
* returned by the MSL context.
* @throws IOException if there is an error sending the error response.
*/
private void sendError(final MslContext ctx, final MessageDebugContext debugCtx, final MessageHeader requestHeader, final Long messageId, final MslError error, final String userMessage, final OutputStream out) throws MslEncodingException, MslCryptoException, MslEntityAuthException, MslMessageException, IOException {
// Create error header.
final ErrorHeader errorHeader = messageFactory.createErrorResponse(ctx, messageId, error, userMessage);
if (debugCtx != null) debugCtx.sentHeader(errorHeader);
// Determine encoder format.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MessageCapabilities capabilities = (requestHeader != null)
? MessageCapabilities.intersection(ctx.getMessageCapabilities(), requestHeader.getMessageCapabilities())
: ctx.getMessageCapabilities();
final Set<MslEncoderFormat> formats = (capabilities != null) ? capabilities.getEncoderFormats() : null;
final MslEncoderFormat format = encoder.getPreferredFormat(formats);
// Send error response.
final MessageOutputStream response = messageFactory.createOutputStream(ctx, out, errorHeader, format);
response.close();
}
/**
* <p>This service receives a request from a remote entity, and either
* returns the received message or automatically generates a reply (and
* returns null).</p>
*
* <p>This class will only be used by trusted-network servers and peer-to-
* peer servers.</p>
*/
private class ReceiveService implements Callable<MessageInputStream> {
/** MSL context. */
private final MslContext ctx;
/** Message context. */
private final MessageContext msgCtx;
/** Remote entity input stream. */
private final InputStream in;
/** Remote entity output stream. */
private final OutputStream out;
/** Read timeout in milliseconds. */
private final int timeout;
/**
* Create a new message receive service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param timeout renewal lock aquisition timeout in milliseconds.
*/
public ReceiveService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final int timeout) {
this.ctx = ctx;
this.msgCtx = msgCtx;
this.in = in;
this.out = out;
this.timeout = timeout;
}
/**
* @return the received message or {@code null} if cancelled.
* @throws MslException if there was an error with the received message
* or an error creating an automatically generated response.
* @throws MslErrorResponseException if there was an error sending an
* automatically generated error response.
* @throws IOException if there was an error reading or writing a
* message.
* @throws TimeoutException if the thread timed out while trying to
* acquire the renewal lock.
* @see java.util.concurrent.Callable#call()
*/
@Override
public MessageInputStream call() throws MslException, MslErrorResponseException, IOException, TimeoutException {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
// Read the incoming message.
final MessageInputStream request;
try {
request = receive(ctx, msgCtx, in, null);
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Try to send an error response.
try {
final MslError error = e.getError();
final String userMessage = messageRegistry.getUserMessage(error, null);
sendError(ctx, debugCtx, null, e.getMessageId(), error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error receiving the message header.", rt, e);
}
throw e;
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
sendError(ctx, debugCtx, null, null, MslError.MSL_COMMS_FAILURE, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error receiving the message header.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Try to send an error response.
try {
sendError(ctx, debugCtx, null, null, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error receiving the message header.", rt, t);
}
throw new MslInternalException("Error receiving the message header.", t);
}
// Return error headers to the caller.
final MessageHeader requestHeader = request.getMessageHeader();
if (requestHeader == null)
return request;
// If the message is not a handshake message deliver it to the
// caller.
try {
if (!request.isHandshake())
return request;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Try to send an error response.
try {
final MslError error = e.getError();
final String userMessage = messageRegistry.getUserMessage(error, null);
sendError(ctx, debugCtx, requestHeader, e.getMessageId(), error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error peeking into the message payloads.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Try to send an error response.
try {
final Long requestMessageId = requestHeader.getMessageId();
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error peeking into the message payloads.", rt, t);
}
throw new MslInternalException("Error peeking into the message payloads.", t);
}
// This is a handshake request so automatically return a response.
final MessageBuilder responseBuilder;
try {
// In peer-to-peer mode this will acquire the local entity's
// master token read lock.
responseBuilder = buildResponse(ctx, msgCtx, request.getMessageHeader());
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Try to send an error response.
try {
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, e.getMessageId(), error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error creating an automatic handshake response.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Try to send an error response.
try {
final Long requestMessageId = requestHeader.getMessageId();
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error creating an automatic handshake response.", rt, t);
}
throw new MslInternalException("Error creating an automatic handshake response.", t);
} finally {
try { request.close(); } catch (final IOException e) {}
}
// If we are in trusted services mode then no additional data is
// expected. Send the handshake response and return null. The next
// message from the remote entity can be retrieved by another call
// to receive.
final MessageContext keyxMsgCtx = new KeyxResponseMessageContext(msgCtx);
if (!ctx.isPeerToPeer()) {
try {
responseBuilder.setRenewable(false);
send(ctx, keyxMsgCtx, out, responseBuilder, false);
return null;
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Try to send an error response.
try {
final Long requestMessageId = requestHeader.getMessageId();
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, requestMessageId, error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending an automatic handshake response.", rt, e);
}
throw e;
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
final Long requestMessageId = requestHeader.getMessageId();
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.MSL_COMMS_FAILURE, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending an automatic handshake response.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Try to send an error response.
try {
final Long requestMessageId = requestHeader.getMessageId();
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending an automatic handshake response.", rt, t);
}
throw new MslInternalException("Error sending an automatic handshake response.", t);
}
}
// Since we are in peer-to-peer mode our response may contain key
// request data. Therefore we may receive another request after the
// remote entity's key exchange completes containing peer
// authentication tokens for the local entity.
//
// The master token lock acquired from buildResponse() will be
// released when the service executes.
//
// We have received one message.
final RequestService service = new RequestService(ctx, keyxMsgCtx, in, out, responseBuilder, timeout, 1);
final MslChannel channel = service.call();
// The MSL channel message output stream can be discarded since it
// only contained a handshake response.
if (channel != null)
return channel.input;
return null;
}
}
/**
* <p>This service sends a response to the remote entity.</p>
*
* <p>This class will only be used trusted network servers and peer-to-peer
* servers.</p>
*/
private class RespondService implements Callable<MslChannel> {
/** MSL context. */
protected final MslContext ctx;
/** Message context. */
protected final MessageContext msgCtx;
/** Request message input stream. */
protected final MessageInputStream request;
/** Remote entity input stream. */
protected final InputStream in;
/** Remote entity output stream. */
protected final OutputStream out;
/** Read timeout in milliseconds. */
protected final int timeout;
/**
* Create a new message respond service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param request request message input stream.
* @param timeout renewal lock acquisition timeout in milliseconds.
*/
public RespondService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageInputStream request, final int timeout) {
if (request.getErrorHeader() != null)
throw new MslInternalException("Respond service created for an error message.");
this.ctx = ctx;
this.msgCtx = msgCtx;
this.in = in;
this.out = out;
this.request = request;
this.timeout = timeout;
}
/**
* Send the response as a trusted network server.
*
* @param builder response message builder.
* @param msgCount number of messages that have already been sent or
* received.
* @return the MSL channel if the response was sent or null if
* cancelled, interrupted, if the response could not be sent
* encrypted or integrity protected when required, a user could
* not be attached due to lack of a master token, or if the
* maximum message count is hit.
* @throws MslException if there was an error creating the response.
* @throws MslErrorResponseException if there was an error sending an
* automatically generated error response.
* @throws IOException if there was an error writing the message.
* @throws InterruptedException if the thread is interrupted while
* trying to delete an old master token the sent message is
* replacing.
*/
protected MslChannel trustedNetworkExecute(final MessageBuilder builder, final int msgCount) throws MslException, MslErrorResponseException, IOException, InterruptedException {
try {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
final MessageHeader requestHeader = request.getMessageHeader();
// Do nothing if we cannot send one more message.
if (msgCount + 1 > MslConstants.MAX_MESSAGES)
return null;
// If the response must be encrypted or integrity protected but
// cannot then send an error requesting it. The client must re-
// initiate the transaction.
final MslError securityRequired;
if (msgCtx.isIntegrityProtected() && !builder.willIntegrityProtectPayloads())
securityRequired = MslError.RESPONSE_REQUIRES_INTEGRITY_PROTECTION;
else if (msgCtx.isEncrypted() && !builder.willEncryptPayloads())
securityRequired = MslError.RESPONSE_REQUIRES_ENCRYPTION;
else
securityRequired = null;
if (securityRequired != null) {
// Try to send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, securityRequired, null, out);
return null;
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Response requires encryption or integrity protection but cannot be protected: " + securityRequired, rt, null);
}
}
// If the response wishes to attach a user ID token but there is no
// master token then send an error requesting the master token. The
// client must re-initiate the transaction.
if (msgCtx.getUser() != null && builder.getMasterToken() == null && builder.getKeyExchangeData() == null) {
// Try to send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.RESPONSE_REQUIRES_MASTERTOKEN, null, out);
return null;
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Response wishes to attach a user ID token but there is no master token.", rt, null);
}
}
// Otherwise simply send the response.
builder.setRenewable(false);
final SendResult result = send(ctx, msgCtx, out, builder, false);
return new MslChannel(request, result.request);
} finally {
// Release the master token lock.
releaseMasterToken(ctx, builder.getMasterToken());
}
}
/**
* Send the response as a peer-to-peer entity.
*
* @param msgCtx message context.
* @param builder response message builder.
* @param msgCount number of messages sent or received so far.
* @return a MSL channel if the response was sent or null if cancelled,
* interrupted, or if the response could not be sent encrypted
* or integrity protected when required, a user could not be
* attached due to lack of a master token, or if the maximum
* message count is hit.
* @throws MslException if there was an error creating or processing a
* message.
* @throws MslErrorResponseException if there was an error sending an
* automatically generated error response.
* @throws IOException if there was an error writing the message.
* @throws InterruptedException if the thread is interrupted while
* trying to acquire the master token lock.
* @throws TimeoutException if the thread timed out while trying to
* acquire the renewal lock.
*/
protected MslChannel peerToPeerExecute(final MessageContext msgCtx, final MessageBuilder builder, int msgCount) throws MslException, IOException, InterruptedException, MslErrorResponseException, TimeoutException {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
final MessageHeader requestHeader = request.getMessageHeader();
// Do nothing if we cannot send and receive two more messages.
//
// Make sure to release the master token lock.
if (msgCount + 2 > MslConstants.MAX_MESSAGES) {
releaseMasterToken(ctx, builder.getMasterToken());
return null;
}
// If the response wishes to attach a user ID token but there is no
// master token then send an error requesting the master token. The
// client must re-initiate the transaction.
if (msgCtx.getUser() != null && builder.getPeerMasterToken() == null && builder.getKeyExchangeData() == null) {
// Release the master token lock and try to send an error
// response.
releaseMasterToken(ctx, builder.getMasterToken());
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.RESPONSE_REQUIRES_MASTERTOKEN, null, out);
return null;
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Response wishes to attach a user ID token but there is no master token.", rt, null);
}
}
// Send the response. A reply is not expected, but may be received.
// This adds two to our message count.
//
// This will release the master token lock.
final SendReceiveResult result = sendReceive(ctx, msgCtx, in, out, builder, Receive.RENEWING, false, timeout);
final MessageInputStream response = result.response;
msgCount += 2;
// If we did not receive a response then we're done. Return the
// original message input stream and the new message output stream.
if (response == null)
return new MslChannel(request, result.request);
// If the response is an error see if we can handle the error and
// retry.
final MessageHeader responseHeader = response.getMessageHeader();
if (responseHeader == null) {
// Close the response. We have everything we need.
try {
response.close();
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Otherwise we don't care about an exception on close.
}
// Build the error response. This will acquire the master token
// lock.
final ErrorHeader errorHeader = response.getErrorHeader();
final ErrorResult errMsg = buildErrorResponse(ctx, msgCtx, result, errorHeader);
// If there is no error response then return the error.
if (errMsg == null)
return null;
// Send the error response. Recursively execute this because it
// may take multiple messages to succeed with sending the
// response.
//
// The master token lock will be released by the recursive call
// to peerToPeerExecute().
final MessageBuilder requestBuilder = errMsg.builder;
final MessageContext resendMsgCtx = errMsg.msgCtx;
return peerToPeerExecute(resendMsgCtx, requestBuilder, msgCount);
}
// If we performed a handshake then re-send the message over the
// same connection so this time the application can send its data.
if (result.handshake) {
// Close the response as we are discarding it.
try {
response.close();
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Otherwise we don't care about an exception on close.
}
// This will acquire the local entity's master token read lock.
// The master token lock will be released by the recursive call
// to peerToPeerExecute().
final MessageContext resendMsgCtx = new ResendMessageContext(null, msgCtx);
final MessageBuilder requestBuilder = buildResponse(ctx, resendMsgCtx, responseHeader);
return peerToPeerExecute(resendMsgCtx, requestBuilder, msgCount);
}
// Otherwise we did send our application data (which may have been
// zero-length) so we do not need to re-send our message. Return
// the new message input stream and the new message output stream.
return new MslChannel(result.response, result.request);
}
/**
* @return a {@link MslChannel} on success or {@code null} if cancelled,
* interrupted, if an error response was received (peer-to-peer
* mode only), if the response could not be sent encrypted or
* integrity protected when required (trusted network-mode
* only), or if the maximum number of messages is hit.
* @throws MslException if there was an error creating the response.
* @throws MslErrorResponseException if there was an error sending an
* automatically generated error response.
* @throws IOException if there was an error writing the message.
* @see java.util.concurrent.Callable#call()
*/
@Override
public MslChannel call() throws MslException, MslErrorResponseException, IOException {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
final MessageHeader requestHeader = request.getMessageHeader();
final MessageBuilder builder;
try {
// In peer-to-peer mode this will acquire the local entity's
// master token read lock.
builder = buildResponse(ctx, msgCtx, requestHeader);
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
try {
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, e.getMessageId(), error, userMessage, out);
} catch (final Throwable rt) {
throw new MslErrorResponseException("Error building the response.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
try {
sendError(ctx, debugCtx, requestHeader, null, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
throw new MslErrorResponseException("Error building the response.", rt, t);
}
throw new MslInternalException("Error building the response.", t);
}
// At most three messages would have been involved in the original
// receive.
try {
// Send the response. This will release the master token lock.
final MslChannel channel;
if (!ctx.isPeerToPeer())
channel = trustedNetworkExecute(builder, 3);
else
channel = peerToPeerExecute(msgCtx, builder, 3);
// Clear any cached payloads.
if (channel != null)
channel.output.stopCaching();
// Return the established channel.
return channel;
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.MSL_COMMS_FAILURE, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending the response.", rt, e);
}
throw e;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, requestMessageId, error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending the response.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error sending the response.", rt, t);
}
throw new MslInternalException("Error sending the response.", t);
}
}
}
/**
* <p>This service sends an error response to the remote entity.</p>
*
* <p>This class will only be used trusted network servers and peer-to-peer
* entities.</p>
*/
private class ErrorService implements Callable<Boolean> {
/** MSL context. */
private final MslContext ctx;
/** Message context. */
private final MessageContext msgCtx;
/** Application error. */
private final ApplicationError appError;
/** Request message input stream. */
private final MessageInputStream request;
/** Remote entity output stream. */
private final OutputStream out;
/**
* Create a new error service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param err the application error.
* @param out remote entity output stream.
* @param request request message input stream.
*/
public ErrorService(final MslContext ctx, final MessageContext msgCtx, final ApplicationError err, final OutputStream out, final MessageInputStream request) {
if (request.getErrorHeader() != null)
throw new MslInternalException("Error service created for an error message.");
this.ctx = ctx;
this.msgCtx = msgCtx;
this.appError = err;
this.out = out;
this.request = request;
}
/**
* @return true on success or false if cancelled or interrupted.
* @throws MslException if there was an error creating the response.
* @throws IOException if there was an error writing the message.
* @see java.util.concurrent.Callable#call()
*/
@Override
public Boolean call() throws MslException {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
final MessageHeader header = request.getMessageHeader();
try {
// Identify the correct MSL error.
final MslError error;
switch (appError) {
case ENTITY_REJECTED:
error = (header.getMasterToken() != null)
? MslError.MASTERTOKEN_REJECTED_BY_APP
: MslError.ENTITY_REJECTED_BY_APP;
break;
case USER_REJECTED:
error = (header.getUserIdToken() != null)
? MslError.USERIDTOKEN_REJECTED_BY_APP
: MslError.USER_REJECTED_BY_APP;
break;
default:
throw new MslInternalException("Unhandled application error " + appError + ".");
}
// Build and send the error response.
final MessageCapabilities caps = header.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, header, header.getMessageId(), error, userMessage, out);
// Success.
return Boolean.TRUE;
} catch (final MslException e) {
// If we were cancelled then return false.
if (cancelled(e)) return false;
// We failed to return an error response. Deliver the exception
// to the application.
throw e;
} catch (final Throwable t) {
// If we were cancelled then return false.
if (cancelled(t)) return false;
// An unexpected exception occurred.
throw new MslInternalException("Error building the error response.", t);
}
}
}
/**
* <p>This service sends a request to the remote entity and returns the
* response.</p>
*
* <p>This class will only be used by trusted network clients, peer-to-peer
* clients, and peer-to-peer servers.</p>
*/
private class RequestService implements Callable<MslChannel> {
/** MSL context. */
private final MslContext ctx;
/** Message context. */
private final MessageContext msgCtx;
/** Remote entity URL. */
private final Url remoteEntity;
/** Remote entity input stream. */
private InputStream in;
/** Remote entity output stream. */
private OutputStream out;
/** True if we opened the streams. */
private boolean openedStreams;
/** Request message builder. */
private MessageBuilder builder;
/** Response expectation. */
private final Receive expectResponse;
/** Connect and read timeout in milliseconds. */
private final int timeout;
/** Number of messages sent or received so far. */
private final int msgCount;
/** True if the maximum message count is hit. */
private boolean maxMessagesHit = false;
/**
* Create a new message request service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param remoteEntity remote entity URL.
* @param expectResponse response expectation.
* @param timeout connect, read, and renewal lock acquisition timeout
* in milliseconds.
*/
public RequestService(final MslContext ctx, final MessageContext msgCtx, final Url remoteEntity, final Receive expectResponse, final int timeout) {
this.ctx = ctx;
this.msgCtx = msgCtx;
this.remoteEntity = remoteEntity;
this.in = null;
this.out = null;
this.openedStreams = false;
this.builder = null;
this.expectResponse = expectResponse;
this.timeout = timeout;
this.msgCount = 0;
}
/**
* Create a new message request service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param expectResponse response expectation.
* @param timeout read and renewal lock acquisition timeout in
* milliseconds.
*/
public RequestService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final Receive expectResponse, final int timeout) {
this.ctx = ctx;
this.msgCtx = msgCtx;
this.remoteEntity = null;
this.in = in;
this.out = out;
this.openedStreams = false;
this.builder = null;
this.expectResponse = expectResponse;
this.timeout = timeout;
this.msgCount = 0;
}
/**
* Create a new message request service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param remoteEntity remote entity URL.
* @param builder request message builder.
* @param expectResponse response expectation.
* @param timeout connect, read, and renewal lock acquisition timeout
* in milliseconds.
* @param msgCount number of messages that have already been sent or
* received.
*/
private RequestService(final MslContext ctx, final MessageContext msgCtx, final Url remoteEntity, final MessageBuilder builder, final Receive expectResponse, final int timeout, final int msgCount) {
this.ctx = ctx;
this.msgCtx = msgCtx;
this.remoteEntity = remoteEntity;
this.in = null;
this.out = null;
this.openedStreams = false;
this.builder = builder;
this.expectResponse = expectResponse;
this.timeout = timeout;
this.msgCount = msgCount;
}
/**
* Create a new message request service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param builder request message builder.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @param msgCount number of messages that have already been sent or
* received.
*/
public RequestService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageBuilder builder, final int timeout, final int msgCount) {
this.ctx = ctx;
this.msgCtx = msgCtx;
this.remoteEntity = null;
this.in = in;
this.out = out;
this.openedStreams = false;
this.builder = builder;
this.expectResponse = Receive.ALWAYS;
this.timeout = timeout;
this.msgCount = msgCount;
}
/**
* <p>Send the provided request and receive a response from the remote
* entity. Any necessary handshake messages will be sent.</p>
*
* <p>If an error was received and cannot be handled the returned MSL
* channel will have {@code null} for its message output stream.</p>
*
* @param msgCtx message context.
* @param builder request message builder.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @param msgCount number of messages sent or received so far.
* @return the established MSL channel or {@code null} if cancelled or
* if the maximum message count is hit.
* @throws MslException if there was an error creating or processing
* a message.
* @throws IOException if there was an error reading or writing a
* message.
* @throws InterruptedException if the thread is interrupted while
* trying to acquire a master token's read lock.
* @throws TimeoutException if the thread timed out while trying to
* acquire the renewal lock.
*/
private MslChannel execute(final MessageContext msgCtx, final MessageBuilder builder, final int timeout, int msgCount) throws MslException, IOException, InterruptedException, TimeoutException {
// Do not do anything if cannot send and receive two more messages.
//
// Make sure to release the master token lock.
if (msgCount + 2 > MslConstants.MAX_MESSAGES) {
releaseMasterToken(ctx, builder.getMasterToken());
maxMessagesHit = true;
return null;
}
// Send the request and receive the response. This adds two to our
// message count.
//
// This will release the master token lock.
final SendReceiveResult result = sendReceive(ctx, msgCtx, in, out, builder, expectResponse, openedStreams, timeout);
final MessageOutputStream request = result.request;
final MessageInputStream response = result.response;
msgCount += 2;
// If we did not receive a response then we're done. Return the
// new message output stream.
if (response == null)
return new MslChannel(response, request);
// If the response is an error see if we can handle the error and
// retry.
final MessageHeader responseHeader = response.getMessageHeader();
if (responseHeader == null) {
// Close the request and response. The response is an error and
// the request is not usable.
try {
request.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
try {
response.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
// Build the error response. This will acquire the master token
// lock.
final ErrorHeader errorHeader = response.getErrorHeader();
final ErrorResult errMsg = buildErrorResponse(ctx, msgCtx, result, errorHeader);
// If there is no error response then return the error.
if (errMsg == null)
return new MslChannel(response, null);
// In trusted network mode send the response in a new request.
// In peer-to-peer mode reuse the connection.
final MslChannel newChannel;
final MessageBuilder requestBuilder = errMsg.builder;
final MessageContext resendMsgCtx = errMsg.msgCtx;
if (!ctx.isPeerToPeer()) {
// The master token lock acquired from buildErrorResponse()
// will be released when the service executes.
final RequestService service = new RequestService(ctx, resendMsgCtx, remoteEntity, requestBuilder, expectResponse, timeout, msgCount);
newChannel = service.call();
maxMessagesHit = service.maxMessagesHit;
} else {
// Send the error response. Recursively execute this
// because it may take multiple messages to succeed with
// sending the request.
//
// The master token lock will be released by the recursive
// call to execute().
newChannel = execute(resendMsgCtx, requestBuilder, timeout, msgCount);
}
// If the maximum message count was hit or if there is no new
// response then return the original error response.
if (maxMessagesHit || (newChannel != null && newChannel.input == null))
return new MslChannel(response, null);
// Return the new channel, which may contain an error or be
// null if cancelled or interrupted.
return newChannel;
}
// If we are in trusted network mode...
if (!ctx.isPeerToPeer()) {
// If we did not perform a handshake then we're done. Deliver
// the response.
if (!result.handshake)
return new MslChannel(response, request);
// We did perform a handshake. Re-send the message over a new
// connection to allow the application to send its data.
//
// Close the request and response. The response will be
// discarded and we will be issuing a new request.
try {
request.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
try {
response.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
// The master token lock acquired from buildResponse() will be
// released when the service executes.
final MessageContext resendMsgCtx = new ResendMessageContext(null, msgCtx);
final MessageBuilder requestBuilder = buildResponse(ctx, msgCtx, responseHeader);
final RequestService service = new RequestService(ctx, resendMsgCtx, remoteEntity, requestBuilder, expectResponse, timeout, msgCount);
return service.call();
}
// We are in peer-to-peer mode...
//
// If we did perform a handshake. Re-send the message over the same
// connection to allow the application to send its data. This may
// also return key response data.
if (result.handshake) {
// Close the request and response. The response will be
// discarded and we will be issuing a new request.
try {
request.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
try {
response.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
// Now resend.
//
// The master token lock acquired from buildResponse() will be
// released by the recursive call to execute().
final MessageContext resendMsgCtx = new ResendMessageContext(null, msgCtx);
final MessageBuilder requestBuilder = buildResponse(ctx, msgCtx, responseHeader);
return execute(resendMsgCtx, requestBuilder, timeout, msgCount);
}
// Otherwise we did send our application data (which may have been
// zero-length) so we do not need to re-send our message.
//
// If the response contains key request data, or is renewable and
// contains a master token and user authentication data, then we
// need to return a response to perform key exchange and/or provide
// a user ID token.
final Set<KeyRequestData> responseKeyxData = responseHeader.getKeyRequestData();
if (!responseKeyxData.isEmpty() ||
(responseHeader.isRenewable() && responseHeader.getMasterToken() != null && responseHeader.getUserAuthenticationData() != null))
{
// Build the response. This will acquire the master token lock.
final MessageContext keyxMsgCtx = new KeyxResponseMessageContext(msgCtx);
final MessageBuilder keyxBuilder = buildResponse(ctx, keyxMsgCtx, responseHeader);
// We should release the master token lock when finished, but
// there is one case where we should not.
boolean releaseLock = true;
try {
// If the response is not a handshake message then we do not
// expect a reply.
if (!response.isHandshake()) {
// Close the request as we are issuing a new request.
try {
request.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
// The remote entity is expecting a response. We need
// to send it even if this exceeds the maximum number of
// messages. We're guaranteed to stop sending more
// messages after this response.
//
// Return the original message input stream and the new
// message output stream to the caller.
keyxBuilder.setRenewable(false);
final SendResult newResult = send(ctx, keyxMsgCtx, out, keyxBuilder, openedStreams);
return new MslChannel(response, newResult.request);
}
// Otherwise the remote entity may still have to send us the
// application data in a reply.
else {
// Close the request and response. The response will be
// discarded and we will be issuing a new request.
try {
request.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
try {
response.close();
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Otherwise we don't care about an I/O exception on close.
}
// The master token lock acquired from buildResponse() will be
// released by the recursive call to execute().
releaseLock = false;
return execute(keyxMsgCtx, keyxBuilder, timeout, msgCount);
}
} finally {
// Release the master token read lock if necessary.
if (releaseLock)
releaseMasterToken(ctx, keyxBuilder.getMasterToken());
}
}
// Return the established MSL channel to the caller.
return new MslChannel(response, request);
}
/**
* @return the established MSL channel or {@code null} if cancelled or
* interrupted.
* @throws MslException if there was an error creating or processing
* a message.
* @throws IOException if there was an error reading or writing a
* message.
* @throws TimeoutException if the thread timed out while trying to
* acquire the renewal lock.
* @see java.util.concurrent.Callable#call()
*/
@Override
public MslChannel call() throws MslException, IOException, TimeoutException {
// If we do not already have a connection then establish one.
final int lockTimeout;
if (in == null || out == null) {
try {
// Set up the connection.
remoteEntity.setTimeout(timeout);
// Connect. Keep track of how much time this takes to subtract
// that from the lock timeout timeout.
final long start = System.currentTimeMillis();
final Connection conn = remoteEntity.openConnection();
out = conn.getOutputStream();
in = conn.getInputStream();
lockTimeout = timeout - (int)(System.currentTimeMillis() - start);
openedStreams = true;
} catch (final IOException e) {
// If a message builder was provided then release the
// master token read lock.
if (builder != null)
releaseMasterToken(ctx, builder.getMasterToken());
// Close any open streams.
// We don't care about an I/O exception on close.
if (out != null) try { out.close(); } catch (final IOException ioe) { }
if (in != null) try { in.close(); } catch (final IOException ioe) { }
// If we were cancelled then return null.
if (cancelled(e)) return null;
throw e;
} catch (final RuntimeException e) {
// If a message builder was provided then release the
// master token read lock.
if (builder != null)
releaseMasterToken(ctx, builder.getMasterToken());
// Close any open streams.
// We don't care about an I/O exception on close.
if (out != null) try { out.close(); } catch (final IOException ioe) { }
if (in != null) try { in.close(); } catch (final IOException ioe) { }
throw e;
}
} else {
lockTimeout = timeout;
}
// If no builder was provided then build a new request. This will
// acquire the master token lock.
if (builder == null) {
try {
builder = buildRequest(ctx, msgCtx);
} catch (final InterruptedException e) {
// Close the streams if we opened them.
// We don't care about an I/O exception on close.
if (openedStreams) {
try { out.close(); } catch (final IOException ioe) { }
try { in.close(); } catch (final IOException ioe) { }
}
// We were cancelled so return null.
return null;
}
}
try {
// Execute. This will release the master token lock.
final MslChannel channel = execute(msgCtx, builder, lockTimeout, msgCount);
// If the channel was established clear the cached payloads.
if (channel != null && channel.output != null)
channel.output.stopCaching();
// Close the input stream if we opened it and there is no
// response. This may be necessary to transmit data
// buffered in the output stream, and the caller will not
// be given a message input stream by which to close it.
//
// We don't care about an I/O exception on close.
if (openedStreams && (channel == null || channel.input == null))
try { in.close(); } catch (final IOException ioe) { }
// Return the established channel.
return channel;
} catch (final InterruptedException e) {
// Close the streams if we opened them.
// We don't care about an I/O exception on close.
if (openedStreams) {
try { out.close(); } catch (final IOException ioe) { }
try { in.close(); } catch (final IOException ioe) { }
}
// We were cancelled so return null.
return null;
} catch (final MslException | IOException | RuntimeException | TimeoutException e) {
// Close the streams if we opened them.
// We don't care about an I/O exception on close.
if (openedStreams) {
try { out.close(); } catch (final IOException ioe) { }
try { in.close(); } catch (final IOException ioe) { }
}
// If we were cancelled then return null.
if (cancelled(e)) return null;
throw e;
}
}
}
/**
* <p>This service sends a message to a remote entity.</p>
*
* <p>This class is only used from trusted network clients and peer-to-peer
* entities.</p>
*/
private class SendService implements Callable<MessageOutputStream> {
/** The request service. */
private final RequestService requestService;
/**
* Create a new message send service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param remoteEntity remote entity URL.
* @param timeout connect, read, and renewal lock acquisition timeout
* in milliseconds.
*/
public SendService(final MslContext ctx, final MessageContext msgCtx, final Url remoteEntity, final int timeout) {
this.requestService = new RequestService(ctx, msgCtx, remoteEntity, Receive.NEVER, timeout);
}
/**
* Create a new message send service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param timeout read and renewal lock acquisition timeout in
* milliseconds.
*/
public SendService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final int timeout) {
this.requestService = new RequestService(ctx, msgCtx, in, out, Receive.NEVER, timeout);
}
/**
* @return the established MSL channel or {@code null} if cancelled or
* interrupted.
* @throws MslException if there was an error creating or processing
* a message.
* @throws IOException if there was an error reading or writing a
* message.
* @throws TimeoutException if the thread timed out while trying to
* acquire the renewal lock.
* @see java.util.concurrent.Callable#call()
*/
@Override
public MessageOutputStream call() throws MslException, IOException, TimeoutException {
final MslChannel channel = this.requestService.call();
return (channel != null) ? channel.output : null;
}
}
/**
* <p>This service sends a message to the remote entity using a request as
* the basis for the response.</p>
*
* <p>This class will only be used trusted network servers.</p>
*/
public class PushService extends RespondService {
/**
* Create a new message push service.
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param request request message input stream.
* @param timeout renewal lock acquisition timeout in milliseconds.
*/
public PushService(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageInputStream request, final int timeout) {
super(ctx, msgCtx, in, out, request, timeout);
}
/**
* @return a {@link MslChannel} on success or {@code null} if cancelled,
* interrupted, if the response could not be sent encrypted or
* integrity protected when required, or if the maximum number
* of messages is hit.
* @throws MslException if there was an error creating the response.
* @throws MslErrorResponseException if there was an error sending an
* automatically generated error response.
* @throws IOException if there was an error writing the message.
* @see java.util.concurrent.Callable#call()
*/
@Override
public MslChannel call() throws MslException, MslErrorResponseException, IOException {
final MessageDebugContext debugCtx = msgCtx.getDebugContext();
final MessageHeader requestHeader = request.getMessageHeader();
final MessageBuilder builder;
try {
builder = buildDetachedResponse(ctx, msgCtx, requestHeader);
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
try {
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, e.getMessageId(), error, userMessage, out);
} catch (final Throwable rt) {
throw new MslErrorResponseException("Error building the message.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
try {
sendError(ctx, debugCtx, requestHeader, null, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
throw new MslErrorResponseException("Error building the message.", rt, t);
}
throw new MslInternalException("Error building the message.", t);
}
try {
// Send the message. This will release the master token lock.
final MslChannel channel = trustedNetworkExecute(builder, 0);
// Clear any cached payloads.
if (channel != null)
channel.output.stopCaching();
// Return the established channel.
return channel;
} catch (final InterruptedException e) {
// We were cancelled so return null.
return null;
} catch (final IOException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.MSL_COMMS_FAILURE, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error pushing the message.", rt, e);
}
throw e;
} catch (final MslException e) {
// If we were cancelled then return null.
if (cancelled(e)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
final MslError error = e.getError();
final MessageCapabilities caps = requestHeader.getMessageCapabilities();
final List<String> languages = (caps != null) ? caps.getLanguages() : null;
final String userMessage = messageRegistry.getUserMessage(error, languages);
sendError(ctx, debugCtx, requestHeader, requestMessageId, error, userMessage, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error pushing the message.", rt, e);
}
throw e;
} catch (final Throwable t) {
// If we were cancelled then return null.
if (cancelled(t)) return null;
// Maybe we can send an error response.
try {
final long requestMessageId = MessageBuilder.decrementMessageId(builder.getMessageId());
sendError(ctx, debugCtx, requestHeader, requestMessageId, MslError.INTERNAL_EXCEPTION, null, out);
} catch (final Throwable rt) {
// If we were cancelled then return null.
if (cancelled(rt)) return null;
throw new MslErrorResponseException("Error pushing the message.", rt, t);
}
throw new MslInternalException("Error pushing the message.", t);
}
}
}
/**
* <p>Send a message to the entity at the provided URL.</p>
*
* <p>Use of this method is not recommended as it does not confirm delivery
* or acceptance of the message. Establishing a MSL channel to send
* application data without requiring the remote entity to acknowledge
* receipt in the response application data is the recommended approach.
* Only use this method if guaranteed receipt is not required.</p>
*
* <p>This method should only be used by trusted network clients and per-
* to-peer entities when no response is expected from the remote entity.
* The remote entity should be using
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}
* and should not attempt to send a response.</p>
*
* <p>The returned {@code Future} will return a {@code MessageOutputStream}
* containing the final {@code MessageOutputStream} that should be used to
* send any additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)}.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) cancelled or interrupted}, if an error
* response was received resulting in a failure to send the message, or if
* the maximum number of messages is hit without sending the message.</p>
*
* <p>The {@code Future} may throw an {@code ExecutionException} whose
* cause is a {@code MslException}, {@code IOException}, or
* {@code TimeoutException}.</p>
*
* <p>The caller must close the returned message output stream.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param remoteEntity remote entity URL.
* @param timeout connect, read, and renewal lock acquisition timeout in
* milliseconds.
* @return a future for the message output stream.
*/
public Future<MessageOutputStream> send(final MslContext ctx, final MessageContext msgCtx, final Url remoteEntity, final int timeout) {
final MessageContext sendMsgCtx = new SendMessageContext(msgCtx);
final SendService service = new SendService(ctx, sendMsgCtx, remoteEntity, timeout);
return executor.submit(service);
}
/**
* <p>Send a message over the provided output stream.</p>
*
* <p>Use of this method is not recommended as it does not confirm delivery
* or acceptance of the message. Establishing a MSL channel to send
* application data without requiring the remote entity to acknowledge
* receipt in the response application data is the recommended approach.
* Only use this method if guaranteed receipt is not required.</p>
*
* <p>This method should only be used by trusted network clients and peer-
* to-peer entities when no response is expected from the remote entity.
* The remote entity should be using
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}
* and should not attempt to send a response.</p>
*
* <p>The returned {@code Future} will return a {@code MessageOutputStream}
* containing the final {@code MessageOutputStream} that should be used to
* send any additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)}.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) cancelled or interrupted}, if an error
* response was received resulting in a failure to send the message, or if
* the maximum number of messages is hit without sending the message.</p>
*
* <p>The {@code Future} may throw an {@code ExecutionException} whose
* cause is a {@code MslException}, {@code IOException}, or
* {@code TimeoutException}.</p>
*
* <p>The caller must close the returned message output stream. The remote
* entity output stream will not be closed when the message output stream
* is closed, in case the caller wishes to reuse them.</p>
*
* TODO once Java supports the WebSocket protocol we can remove this method
* in favor of the one accepting a URL parameter. (Or is it the other way
* around?)
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param timeout connect, read, and renewal lock acquisition timeout in
* milliseconds.
* @return a future for the message output stream.
*/
public Future<MessageOutputStream> send(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final int timeout) {
final MessageContext sendMsgCtx = new SendMessageContext(msgCtx);
final SendService service = new SendService(ctx, sendMsgCtx, in, out, timeout);
return executor.submit(service);
}
/**
* <p>Push a message over the provided output stream based on a message
* received from the remote entity.</p>
*
* <p>Use of this method is not recommended as it does not perform master
* token or user ID token issuance or renewal which the remote entity may
* be attempting to perform. Only use this method if there is some other
* means by which the client will be able to acquire and renew its master
* token or user ID token on a regular basis.</p>
*
* <p>This method should only be used by trusted network servers that wish
* to send multiple responses to a trusted network client. The remote
* entity should be using
* {@link #send(MslContext, MessageContext, Url, int)} or
* {@link #send(MslContext, MessageContext, InputStream, OutputStream, int)}
* and
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}.</p>
*
* <p>This method must not be used if
* {@link MslControl#respond(MslContext, MessageContext, InputStream, OutputStream, MessageInputStream, int)}
* has already been used with the same {@code MessageInputStream}.</p>
*
* <p>The returned {@code Future} will return a {@code MslChannel}
* containing the same {@code MessageInputStream} that was provided and the
* final {@code MessageOutputStream} that should be used to send any
* additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)} to the remote
* entity.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) canncelled or interrupted}, if the message
* could not be sent with encryption or integrity protection when required,
* if a user cannot be attached to the respond to the response due to lack
* of a master token, or if the maximum number of messages is hit without
* sending the message. In these cases the local entity should wait for a
* new message from the remote entity to be received by a call to
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}
* before attempting to push another message.</p>
*
* <p>The {@code Future} may throw an {@code ExecutionException} whose
* cause is a {@code MslException}, {@code MslErrorResponseException},
* {@code IOException}, or {@code TimeoutException}.</p>
*
* <p>The remote entity input and output streams will not be closed in case
* the caller wishes to reuse them.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param request message input stream used to create the message.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @return a future for the communication channel.
* @throws IllegalStateException if used in peer-to-peer mode.
* @throws IllegalArgumentException if the request message input stream is
* an error message.
*/
public Future<MslChannel> push(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageInputStream request, final int timeout) {
if (ctx.isPeerToPeer())
throw new IllegalStateException("This method cannot be used in peer-to-peer mode.");
if (request.getErrorHeader() != null)
throw new IllegalArgumentException("Request message input stream cannot be for an error message.");
final PushService service = new PushService(ctx, msgCtx, in, out, request, timeout);
return executor.submit(service);
}
/**
* <p>Receive a request over the provided input stream.</p>
*
* <p>If there is an error with the message an error response will be sent
* over the provided output stream.</p>
*
* <p>This method should only be used to receive a request initiated by the
* remote entity. The remote entity should have used one of the request
* methods
* {@link #request(MslContext, MessageContext, Url, int)} or
* {@link #request(MslContext, MessageContext, InputStream, OutputStream, int)}
* or one of the send methods
* {@link #send(MslContext, MessageContext, Url, int)} or
* {@link #send(MslContext, MessageContext, InputStream, OutputStream, int)}.<p>
*
* <p>The returned {@code Future} will return the received
* {@code MessageInputStream} on completion or {@code null} if a reply was
* automatically sent (for example in response to a handshake request) or
* if the operation was
* {@link #cancelled(Throwable) cancelled or interrupted}. The returned
* message may be an error message if the maximum number of messages is hit
* without successfully receiving the final message. The {@code Future} may
* throw an {@code ExecutionException} whose cause is a
* {@code MslException}, {@code MslErrorResponseException},
* {@code IOException}, or {@code TimeoutException}.</p>
*
* <p>The remote entity input and output streams will not be closed in case
* the caller wishes to reuse them.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param timeout renewal acquisition lock timeout in milliseconds.
* @return a future for the message.
*/
public Future<MessageInputStream> receive(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final int timeout) {
final ReceiveService service = new ReceiveService(ctx, msgCtx, in, out, timeout);
return executor.submit(service);
}
/**
* <p>Send a response over the provided output stream.</p>
*
* <p>This method should only be used by trusted network servers and peer-
* to-peer entities after receiving a request via
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}.
* The remote entity should have used one of the request methods
* {@link #request(MslContext, MessageContext, Url, int)} or
* {@link #request(MslContext, MessageContext, InputStream, OutputStream, int)}.</p>
*
* <p>The returned {@code Future} will return a {@code MslChannel}
* containing the final {@code MessageOutputStream} that should be used to
* send any additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)} to the remote entity,
* and in peer-to-peer mode may also contain a {@code MessageInputStream}
* as described below.</p>
*
* <p>In peer-to-peer mode a new {@code MessageInputStream} may be returned
* which should be used in place of the previous {@code MessageInputStream}
* being responded to. This will only occur if the initial response sent
* could not include application data and was instead a handshake message.
* The new {@code MessageInputStream} will not include any application data
* already read off of the previous {@code MessageInputStream}; it will
* only contain new application data that is a continuation of the previous
* message's application data.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) cancelled or interrupted}, if an error
* response was received (peer-to-peer only) resulting in a failure to
* establish the communication channel, if the response could not be sent
* with encryption or integrity protection when required (trusted network-
* mode only), if a user cannot be attached to the response due to lack of
* a master token, or if the maximum number of messages is hit without
* sending the message. In these cases the remote entity's next message can
* be received by another call to
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}.</p>
*
* <p>The {@code Future} may throw an {@code ExecutionException} whose
* cause is a {@code MslException}, {@code MslErrorResponseException},
* {@code IOException}, or {@code TimeoutException}.</p>
*
* <p>The remote entity input and output streams will not be closed in case
* the caller wishes to reuse them.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param request message input stream to create the response for.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @return a future for the communication channel.
* @throws IllegalArgumentException if the request message input stream is
* an error message.
*/
public Future<MslChannel> respond(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final MessageInputStream request, final int timeout) {
if (request.getErrorHeader() != null)
throw new IllegalArgumentException("Request message input stream cannot be for an error message.");
final RespondService service = new RespondService(ctx, msgCtx, in, out, request, timeout);
return executor.submit(service);
}
/**
* <p>Send an error response over the provided output stream. Any replies
* to the error response may be received by a subsequent call to
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}.</p>
*
* <p>This method should only be used by trusted network servers and peer-
* to-peer entities after receiving a request via
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}.
* The remote entity should have used
* {@link #request(MslContext, MessageContext, Url, int)}.</p>
*
* <p>The returned {@code Future} will return true on success or false if
* {@link #cancelled(Throwable) cancelled or interrupted}. The
* {@code Future} may throw an {@code ExecutionException} whose cause is a
* {@code MslException} or {@code IOException}.</p>
*
* <p>The remote entity input and output streams will not be closed in case
* the caller wishes to reuse them.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param err error type.
* @param out remote entity output stream.
* @param request request input srtream to create the response for.
* @return a future for the operation.
* @throws IllegalArgumentException if the request message input stream is
* an error message.
*/
public Future<Boolean> error(final MslContext ctx, final MessageContext msgCtx, final ApplicationError err, final OutputStream out, final MessageInputStream request) {
if (request.getErrorHeader() != null)
throw new IllegalArgumentException("Request message input stream cannot be for an error message.");
final ErrorService service = new ErrorService(ctx, msgCtx, err, out, request);
return executor.submit(service);
}
/**
* <p>Send a request to the entity at the provided URL.</p>
*
* <p>This method should only be used by trusted network clients when
* initiating a new request. The remote entity should be using
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}
* and
* {@link #respond(MslContext, MessageContext, InputStream, OutputStream, MessageInputStream, int)}.</p>
*
* <p>The returned {@code Future} will return a {@code MslChannel}
* containing the final {@code MessageOutputStream} that should be used to
* send any additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)} and the
* {@code MessageInputStream} of the established MSL communication
* channel. If an error message was received then the MSL channel's message
* output stream will be {@code null}.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) cancelled or interrupted}. The returned
* message may be an error message if the maximum number of messages is hit
* without successfully sending the request and receiving the response. The
* {@code Future} may throw an {@code ExecutionException} whose cause is a
* {@code MslException}, {@code IOException}, or
* {@code TimeoutException}.</p>
*
* <p>The caller must close the returned message input stream and message
* outut stream.</p>
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param remoteEntity remote entity URL.
* @param timeout connect, read, and renewal lock acquisition timeout in
* milliseconds.
* @return a future for the communication channel.
* @throws IllegalStateException if used in peer-to-peer mode.
*/
public Future<MslChannel> request(final MslContext ctx, final MessageContext msgCtx, final Url remoteEntity, final int timeout) {
if (ctx.isPeerToPeer())
throw new IllegalStateException("This method cannot be used in peer-to-peer mode.");
final RequestService service = new RequestService(ctx, msgCtx, remoteEntity, Receive.ALWAYS, timeout);
return executor.submit(service);
}
/**
* <p>Send a request to the remote entity over the provided output stream
* and receive a resposne over the provided input stream.</p>
*
* <p>This method should only be used by peer-to-peer entities when
* initiating a new request. The remote entity should be using
* {@link #receive(MslContext, MessageContext, InputStream, OutputStream, int)}
* and
* {@link #respond(MslContext, MessageContext, InputStream, OutputStream, MessageInputStream, int)}.</p>
*
* <p>The returned {@code Future} will return a {@code MslChannel}
* containing the final {@code MessageOutputStream} that should be used to
* send any additional application data not already sent via
* {@link MessageContext#write(MessageOutputStream)} and the
* {@code MessageInputStream} of the established MSL communication
* channel. If an error message was received then the MSL channel's message
* output stream will be {@code null}.</p>
*
* <p>The returned {@code Future} will return {@code null} if
* {@link #cancelled(Throwable) cancelled or interrupted}. The returned
* message may be an error message if the maximum number of messages is hit
* without successfully sending the request and receiving the response. The
* {@code Future} may throw an {@code ExecutionException} whose cause is a
* {@code MslException}, {@code IOException}, or
* {@code TimeoutException}.</p>
*
* <p>The caller must close the returned message input stream and message
* outut stream. The remote entity input and output streams will not be
* closed when the message input and output streams are closed, in case the
* caller wishes to reuse them.</p>
*
* TODO once Java supports the WebSocket protocol we can remove this method
* in favor of the one accepting a URL parameter. (Or is it the other way
* around?)
*
* @param ctx MSL context.
* @param msgCtx message context.
* @param in remote entity input stream.
* @param out remote entity output stream.
* @param timeout renewal lock acquisition timeout in milliseconds.
* @return a future for the communication channel.
* @throws IllegalStateException if used in trusted network mode.
*/
public Future<MslChannel> request(final MslContext ctx, final MessageContext msgCtx, final InputStream in, final OutputStream out, final int timeout) {
if (!ctx.isPeerToPeer())
throw new IllegalStateException("This method cannot be used in trusted network mode.");
final RequestService service = new RequestService(ctx, msgCtx, in, out, Receive.ALWAYS, timeout);
return executor.submit(service);
}
/** MSL executor. */
private final ExecutorService executor;
/** Message factory. */
private final MessageFactory messageFactory;
/** Error message registry. */
private final ErrorMessageRegistry messageRegistry;
/** Filter stream factory. May be null. */
private FilterStreamFactory filterFactory = null;
/**
* Map tracking outstanding renewable messages by MSL context. The blocking
* queue is used to wait for a master token from a different thread if the
* message requires one.
*/
private final ConcurrentHashMap<MslContext,BlockingQueue<MasterToken>> renewingContexts = new ConcurrentHashMap<MslContext,BlockingQueue<MasterToken>>();
/** Dummy master token used to release the renewal lock. */
private final MasterToken NULL_MASTER_TOKEN;
/**
* Map of in-flight master token read-write locks by MSL context and master
* token.
*/
private final ConcurrentHashMap<MslContextMasterTokenKey,ReadWriteLock> masterTokenLocks = new ConcurrentHashMap<MslContextMasterTokenKey,ReadWriteLock>();
}
| 9,861 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageCapabilities.java | /**
* Copyright (c) 2013-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.netflix.msl.MslConstants.CompressionAlgorithm;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.io.MslArray;
import com.netflix.msl.io.MslEncodable;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
/**
* <p>The message capabilities identify the features supported by the message
* sender.</p>
*
* <p>The message capabilities are represented as
* {@code
* capabilities = {
* "compressionalgos" : [ enum(GZIP|LZW) ],
* "languages" : [ "string" ],
* "encoderformats" : [ "string" ],
* }} where:
* <ul>
* <li>{@code compressionalgos} is the set of supported compression algorithms</li>
* <li>{@code languages} is the preferred list of BCP-47 languages in descending order</li>
* <li>{@code encoderformats} is the preferred list of MSL encoder formats in descending order</li>
* </ul></p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MessageCapabilities implements MslEncodable {
/** Key compression algorithms. */
private static final String KEY_COMPRESSION_ALGOS = "compressionalgos";
/** Key languages. */
private static final String KEY_LANGUAGES = "languages";
/** Key encoder formats. */
private static final String KEY_ENCODER_FORMATS = "encoderformats";
/**
* Computes and returns the intersection of two message capabilities.
*
* @param mc1 first message capabilities. May be {@code null}.
* @param mc2 second message capabilities. May be {@code null}.
* @return the intersection of message capabilities or {@code null} if one
* of the message capabilities is {@code null}.
*/
public static MessageCapabilities intersection(final MessageCapabilities mc1, final MessageCapabilities mc2) {
if (mc1 == null || mc2 == null)
return null;
// Compute the intersection of compression algorithms.
final Set<CompressionAlgorithm> compressionAlgos = EnumSet.noneOf(CompressionAlgorithm.class);
compressionAlgos.addAll(mc1.compressionAlgos);
compressionAlgos.retainAll(mc2.compressionAlgos);
// Compute the intersection of languages. This may not respect order.
final List<String> languages = new ArrayList<String>(mc1.languages);
languages.retainAll(mc2.languages);
// Compute the intersection of encoder formats. This may not respect
// order.
final Set<MslEncoderFormat> encoderFormats = new HashSet<MslEncoderFormat>();
encoderFormats.addAll(mc1.encoderFormats);
encoderFormats.retainAll(mc2.encoderFormats);
return new MessageCapabilities(compressionAlgos, languages, encoderFormats);
}
/**
* Create a new message capabilities object with the specified supported
* features.
*
* @param compressionAlgos supported payload compression algorithms. May be
* {@code null}.
* @param languages preferred languages as BCP-47 codes in descending
* order. May be {@code null}.
* @param encoderFormats supported encoder formats. May be {@code null}.
*/
public MessageCapabilities(final Set<CompressionAlgorithm> compressionAlgos, final List<String> languages, final Set<MslEncoderFormat> encoderFormats) {
this.compressionAlgos = Collections.unmodifiableSet(compressionAlgos != null ? compressionAlgos : EnumSet.noneOf(CompressionAlgorithm.class));
this.languages = Collections.unmodifiableList(languages != null ? languages : new ArrayList<String>());
this.encoderFormats = Collections.unmodifiableSet(encoderFormats != null ? encoderFormats : new HashSet<MslEncoderFormat>());
}
/**
* Construct a new message capabilities object from the provided MSL
* object.
*
* @param capabilitiesMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
*/
public MessageCapabilities(final MslObject capabilitiesMo) throws MslEncodingException {
try {
// Extract compression algorithms.
final Set<CompressionAlgorithm> compressionAlgos = EnumSet.noneOf(CompressionAlgorithm.class);
final MslArray algos = capabilitiesMo.optMslArray(KEY_COMPRESSION_ALGOS);
for (int i = 0; algos != null && i < algos.size(); ++i) {
final String algo = algos.getString(i);
// Ignore unsupported algorithms.
try {
compressionAlgos.add(CompressionAlgorithm.valueOf(algo));
} catch (final IllegalArgumentException e) {}
}
this.compressionAlgos = Collections.unmodifiableSet(compressionAlgos);
// Extract languages.
final List<String> languages = new ArrayList<String>();
final MslArray langs = capabilitiesMo.optMslArray(KEY_LANGUAGES);
for (int i = 0; langs != null && i < langs.size(); ++i)
languages.add(langs.getString(i));
this.languages = Collections.unmodifiableList(languages);
// Extract encoder formats.
final Set<MslEncoderFormat> encoderFormats = new HashSet<MslEncoderFormat>();
final MslArray formats = capabilitiesMo.optMslArray(KEY_ENCODER_FORMATS);
for (int i = 0; formats != null && i < formats.size(); ++i) {
final String format = formats.getString(i);
final MslEncoderFormat encoderFormat = MslEncoderFormat.getFormat(format);
// Ignore unsupported formats.
if (encoderFormat != null)
encoderFormats.add(encoderFormat);
}
this.encoderFormats = Collections.unmodifiableSet(encoderFormats);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "capabilities " + capabilitiesMo, e);
}
}
/**
* @return the supported compression algorithms.
*/
public Set<CompressionAlgorithm> getCompressionAlgorithms() {
return this.compressionAlgos;
}
/**
* @return the preferred languages as BCP-47 codes in descending order.
*/
public List<String> getLanguages() {
return this.languages;
}
/**
* @return the supported encoder formats.
*/
public Set<MslEncoderFormat> getEncoderFormats() {
return this.encoderFormats;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_COMPRESSION_ALGOS, encoder.createArray(compressionAlgos));
mo.put(KEY_LANGUAGES, languages);
final MslArray formats = encoder.createArray();
for (final MslEncoderFormat encoderFormat : encoderFormats)
formats.put(-1, encoderFormat.name());
mo.put(KEY_ENCODER_FORMATS, formats);
return encoder.encodeObject(mo, format);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (!(obj instanceof MessageCapabilities)) return false;
final MessageCapabilities that = (MessageCapabilities)obj;
return this.compressionAlgos.equals(that.compressionAlgos) &&
this.languages.equals(that.languages) &&
this.encoderFormats.equals(that.encoderFormats);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.compressionAlgos.hashCode() ^ this.languages.hashCode() ^ this.encoderFormats.hashCode();
}
/** Supported payload compression algorithms. */
private final Set<CompressionAlgorithm> compressionAlgos;
/** Preferred languages as BCP-47 codes in descending order. */
private final List<String> languages;
/** Supported encoder formats. */
private final Set<MslEncoderFormat> encoderFormats;
}
| 9,862 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/SecretMessageContext.java | /**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
/**
* <p>A message context implementation that can be extended for use with
* messages that have secret contents which must be protected from the view of
* unauthorized parties. The contents will be encrypted and integrity protected
* but still replayable.</p>
*
* <p>Most messages should be considered secret messages. Examples would
* private conversations between individuals or the transmission of personal
* information.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class SecretMessageContext implements MessageContext {
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return false;
}
}
| 9,863 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/MessageHeader.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.SessionCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.io.MslArray;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslEncoderUtils;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.keyx.KeyResponseData;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.UserAuthenticationData;
import com.netflix.msl.userauth.UserAuthenticationFactory;
import com.netflix.msl.userauth.UserAuthenticationScheme;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>If a master token exists, the header data chunks will be encrypted and
* verified using the master token. If no master token exists, the header data
* will be verified and encrypted based on the entity authentication
* scheme.</p>
*
* <p>If peer tokens exist, the message recipient is expected to use the peer
* master token to secure its response and send the peer user ID token and peer
* service tokens back in the header data. The request's tokens should be
* included as the response's peer tokens.</p>
*
* <p>If key response data exists, it applies to the token set the receiving
* entity uses to identify itself. In a trusted services network the key
* response data applies to the primary tokens. In a peer-to-peer network the
* key response data applies to the peer tokens.</p>
*
* <p>The header data is represented as
* {@code
* headerdata = {
* "#mandatory" : [ "messageid", "renewable", "handshake" ],
* "timestamp" : "int64(0,2^53^)",
* "messageid" : "int64(0,2^53^)",
* "nonreplayableid" : "int64(0,2^53^)",
* "renewable" : "boolean",
* "handshake" : "boolean",
* "capabilities" : capabilities,
* "keyrequestdata" : [ keyrequestdata ],
* "keyresponsedata" : keyresponsedata,
* "userauthdata" : userauthdata,
* "useridtoken" : useridtoken,
* "servicetokens" : [ servicetoken ],
* "peermastertoken" : mastertoken,
* "peeruseridtoken" : useridtoken,
* "peerservicetokens" : [ servicetoken ]
* }} where:
* <ul>
* <li>{@code timestamp} is the sender time when the header is created in seconds since the UNIX epoch</li>
* <li>{@code messageid} is the message ID</li>
* <li>{@code nonreplayableid} is the non-replayable ID</li>
* <li>{@code renewable} indicates if the master token and user ID are renewable</li>
* <li>{@code handshake} indicates a handshake message</li>
* <li>{@code capabilities} lists the sender's message capabilities</li>
* <li>{@code keyrequestdata} is session key request data</li>
* <li>{@code keyresponsedata} is the session key response data</li>
* <li>{@code userauthdata} is the user authentication data</li>
* <li>{@code useridtoken} is the user ID token</li>
* <li>{@code servicetokens} are the service tokens</li>
* <li>{@code peermastertoken} is the peer master token</li>
* <li>{@code peeruseridtoken} is the peer user ID token</li>
* <li>{@code peerservicetokens} are the peer service tokens</li>
* </ul></p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MessageHeader extends Header {
/** Milliseconds per second. */
private static final long MILLISECONDS_PER_SECOND = 1000;
// Message header data.
/** Key sender. */
private static final String KEY_SENDER = "sender";
/** Key timestamp. */
private static final String KEY_TIMESTAMP = "timestamp";
/** Key message ID. */
private static final String KEY_MESSAGE_ID = "messageid";
/** Key non-replayable ID. */
private static final String KEY_NON_REPLAYABLE_ID = "nonreplayableid";
/** Key non-replayable flag. */
private static final String KEY_NON_REPLAYABLE = "nonreplayable";
/** Key renewable flag. */
private static final String KEY_RENEWABLE = "renewable";
/** Key handshake flag */
private static final String KEY_HANDSHAKE = "handshake";
/** Key capabilities. */
private static final String KEY_CAPABILITIES = "capabilities";
/** Key key exchange request. */
private static final String KEY_KEY_REQUEST_DATA = "keyrequestdata";
/** Key key exchange response. */
private static final String KEY_KEY_RESPONSE_DATA = "keyresponsedata";
/** Key user authentication data. */
private static final String KEY_USER_AUTHENTICATION_DATA = "userauthdata";
/** Key user ID token. */
private static final String KEY_USER_ID_TOKEN = "useridtoken";
/** Key service tokens. */
private static final String KEY_SERVICE_TOKENS = "servicetokens";
// Message header peer data.
/** Key peer master token. */
private static final String KEY_PEER_MASTER_TOKEN = "peermastertoken";
/** Key peer user ID token. */
private static final String KEY_PEER_USER_ID_TOKEN = "peeruseridtoken";
/** Key peer service tokens. */
private static final String KEY_PEER_SERVICE_TOKENS = "peerservicetokens";
/**
* Container struct for message header data.
*/
public static class HeaderData {
/**
* @param messageId the message ID.
* @param nonReplayableId the message's non-replayable ID. May be null.
* @param renewable the message's renewable flag.
* @param handshake the message's handshake flag.
* @param capabilities the sender's message capabilities.
* @param keyRequestData session key request data. May be null or
* empty.
* @param keyResponseData session key response data. May be null.
* @param userAuthData the user authentication data. May be null if a
* user ID token is provided or there is no user authentication
* for this message.
* @param userIdToken the user ID token. May be null if user
* authentication data is provided or there is no user
* authentication for this message.
* @param serviceTokens the service tokens. May be null or empty.
*/
public HeaderData(final long messageId, final Long nonReplayableId,
final boolean renewable, final boolean handshake,
final MessageCapabilities capabilities,
final Set<KeyRequestData> keyRequestData, final KeyResponseData keyResponseData,
final UserAuthenticationData userAuthData, final UserIdToken userIdToken,
final Set<ServiceToken> serviceTokens)
{
this.messageId = messageId;
this.nonReplayableId = nonReplayableId;
this.renewable = renewable;
this.handshake = handshake;
this.capabilities = capabilities;
this.keyRequestData = keyRequestData;
this.keyResponseData = keyResponseData;
this.userAuthData = userAuthData;
this.userIdToken = userIdToken;
this.serviceTokens = serviceTokens;
}
public final long messageId;
public final Long nonReplayableId;
public final boolean renewable;
public final boolean handshake;
public final MessageCapabilities capabilities;
public final Set<KeyRequestData> keyRequestData;
public final KeyResponseData keyResponseData;
public final UserAuthenticationData userAuthData;
public final UserIdToken userIdToken;
public final Set<ServiceToken> serviceTokens;
}
/**
* Container struct for header peer data.
*/
public static class HeaderPeerData {
/**
* @param peerMasterToken peer master token. May be null.
* @param peerUserIdToken peer user ID token. May be null if there is
* no user authentication for the peer.
* @param peerServiceTokens peer service tokens. May be empty.
*/
public HeaderPeerData(final MasterToken peerMasterToken, final UserIdToken peerUserIdToken,
final Set<ServiceToken> peerServiceTokens)
{
this.peerMasterToken = peerMasterToken;
this.peerUserIdToken = peerUserIdToken;
this.peerServiceTokens = peerServiceTokens;
}
public final MasterToken peerMasterToken;
public final UserIdToken peerUserIdToken;
public final Set<ServiceToken> peerServiceTokens;
}
/**
* <p>Construct a new message header with the provided message data.</p>
*
* <p>Headers are encrypted and signed. If a master token is provided, it
* will be used for this purpose. Otherwise the crypto context appropriate
* for the entity authentication scheme will be used. N.B. Either the
* entity authentication data or the master token must be provided.</p>
*
* <p>Peer tokens are only processed if operating in peer-to-peer mode.</p>
*
* @param ctx MSL context.
* @param entityAuthData the entity authentication data. May be null if a
* master token is provided.
* @param masterToken the master token. May be null if entity
* authentication data is provided.
* @param headerData message header data container.
* @param peerData message header peer data container.
* @throws MslEncodingException if there is an error encoding the data.
* @throws MslCryptoException if there is an error encrypting or signing
* the message.
* @throws MslMasterTokenException if the header master token is not
* trusted and needs to be to accept this message header.
* @throws MslEntityAuthException if there is an error with the entity
* authentication data.
*/
public MessageHeader(final MslContext ctx, final EntityAuthenticationData entityAuthData, final MasterToken masterToken, final HeaderData headerData, final HeaderPeerData peerData) throws MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException {
// Message ID must be within range.
if (headerData.messageId < 0 || headerData.messageId > MslConstants.MAX_LONG_VALUE)
throw new MslInternalException("Message ID " + headerData.messageId + " is out of range.");
// Message entity must be provided.
if (entityAuthData == null && masterToken == null)
throw new MslInternalException("Message entity authentication data or master token must be provided.");
// Do not allow user authentication data to be included if the message
// will not be encrypted.
final boolean encrypted;
if (masterToken != null) {
encrypted = true;
} else {
final EntityAuthenticationScheme scheme = entityAuthData.getScheme();
encrypted = scheme.encrypts();
}
if (!encrypted && headerData.userAuthData != null)
throw new MslInternalException("User authentication data cannot be included if the message is not encrypted.");
// Older MSL stacks expect the sender if a master token is being used.
//
// If the local entity does not know its entity identity, then use the
// empty string. This will work except for the case where the old MSL
// stack is receiving a message for which it is also the issuer of the
// master token. That scenario will continue to fail.
final String sender;
if (masterToken != null) {
final String localIdentity = ctx.getEntityAuthenticationData(null).getIdentity();
sender = (localIdentity != null) ? localIdentity : "";
} else {
sender = null;
}
this.entityAuthData = (masterToken == null) ? entityAuthData : null;
this.masterToken = masterToken;
this.nonReplayableId = headerData.nonReplayableId;
this.renewable = headerData.renewable;
this.handshake = headerData.handshake;
this.capabilities = headerData.capabilities;
this.timestamp = ctx.getTime() / MILLISECONDS_PER_SECOND;
this.messageId = headerData.messageId;
this.keyRequestData = Collections.unmodifiableSet((headerData.keyRequestData != null) ? headerData.keyRequestData : new HashSet<KeyRequestData>());
this.keyResponseData = headerData.keyResponseData;
this.userAuthData = headerData.userAuthData;
this.userIdToken = headerData.userIdToken;
this.serviceTokens = Collections.unmodifiableSet((headerData.serviceTokens != null) ? headerData.serviceTokens : new HashSet<ServiceToken>());
if (ctx.isPeerToPeer()) {
this.peerMasterToken = peerData.peerMasterToken;
this.peerUserIdToken = peerData.peerUserIdToken;
this.peerServiceTokens = Collections.unmodifiableSet((peerData.peerServiceTokens != null) ? peerData.peerServiceTokens : new HashSet<ServiceToken>());
} else {
this.peerMasterToken = null;
this.peerUserIdToken = null;
this.peerServiceTokens = Collections.emptySet();
}
// Grab token verification master tokens.
final MasterToken tokenVerificationMasterToken, peerTokenVerificationMasterToken;
if (this.keyResponseData != null) {
// The key response data is used for token verification in a
// trusted services network and peer token verification in a peer-
// to-peer network.
if (!ctx.isPeerToPeer()) {
tokenVerificationMasterToken = this.keyResponseData.getMasterToken();
peerTokenVerificationMasterToken = this.peerMasterToken;
} else {
tokenVerificationMasterToken = this.masterToken;
peerTokenVerificationMasterToken = this.keyResponseData.getMasterToken();
}
} else {
tokenVerificationMasterToken = this.masterToken;
peerTokenVerificationMasterToken = this.peerMasterToken;
}
// Check token combinations.
if (this.userIdToken != null && (tokenVerificationMasterToken == null || !this.userIdToken.isBoundTo(tokenVerificationMasterToken)))
throw new MslInternalException("User ID token must be bound to a master token.");
if (this.peerUserIdToken != null && (peerTokenVerificationMasterToken == null || !this.peerUserIdToken.isBoundTo(peerTokenVerificationMasterToken)))
throw new MslInternalException("Peer user ID token must be bound to a peer master token.");
// Grab the user.
if (this.userIdToken != null)
this.user = this.userIdToken.getUser();
else
this.user = null;
// All service tokens must be unbound or if bound, bound to the
// provided tokens.
for (final ServiceToken serviceToken : this.serviceTokens) {
if (serviceToken.isMasterTokenBound() && (tokenVerificationMasterToken == null || !serviceToken.isBoundTo(tokenVerificationMasterToken)))
throw new MslInternalException("Master token bound service tokens must be bound to the provided master token.");
if (serviceToken.isUserIdTokenBound() && (this.userIdToken == null || !serviceToken.isBoundTo(this.userIdToken)))
throw new MslInternalException("User ID token bound service tokens must be bound to the provided user ID token.");
}
for (final ServiceToken peerServiceToken : this.peerServiceTokens) {
if (peerServiceToken.isMasterTokenBound() && (peerTokenVerificationMasterToken == null || !peerServiceToken.isBoundTo(peerTokenVerificationMasterToken)))
throw new MslInternalException("Master token bound peer service tokens must be bound to the provided peer master token.");
if (peerServiceToken.isUserIdTokenBound() && (this.peerUserIdToken == null || !peerServiceToken.isBoundTo(this.peerUserIdToken)))
throw new MslInternalException("User ID token bound peer service tokens must be bound to the provided peer user ID token.");
}
// Construct the header data.
try {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final Set<MslEncoderFormat> formats = (capabilities != null) ? capabilities.getEncoderFormats() : null;
final MslEncoderFormat format = encoder.getPreferredFormat(formats);
headerdata = encoder.createObject();
if (sender != null) headerdata.put(KEY_SENDER, sender);
headerdata.put(KEY_TIMESTAMP, this.timestamp);
headerdata.put(KEY_MESSAGE_ID, this.messageId);
headerdata.put(KEY_NON_REPLAYABLE, this.nonReplayableId != null);
if (this.nonReplayableId != null) headerdata.put(KEY_NON_REPLAYABLE_ID, this.nonReplayableId);
headerdata.put(KEY_RENEWABLE, this.renewable);
headerdata.put(KEY_HANDSHAKE, this.handshake);
if (this.capabilities != null) headerdata.put(KEY_CAPABILITIES, this.capabilities);
if (this.keyRequestData.size() > 0) headerdata.put(KEY_KEY_REQUEST_DATA, MslEncoderUtils.createArray(ctx, format, this.keyRequestData));
if (this.keyResponseData != null) headerdata.put(KEY_KEY_RESPONSE_DATA, this.keyResponseData);
if (this.userAuthData != null) headerdata.put(KEY_USER_AUTHENTICATION_DATA, this.userAuthData);
if (this.userIdToken != null) headerdata.put(KEY_USER_ID_TOKEN, this.userIdToken);
if (this.serviceTokens.size() > 0) headerdata.put(KEY_SERVICE_TOKENS, MslEncoderUtils.createArray(ctx, format, this.serviceTokens));
if (this.peerMasterToken != null) headerdata.put(KEY_PEER_MASTER_TOKEN, this.peerMasterToken);
if (this.peerUserIdToken != null) headerdata.put(KEY_PEER_USER_ID_TOKEN, this.peerUserIdToken);
if (this.peerServiceTokens.size() > 0) headerdata.put(KEY_PEER_SERVICE_TOKENS, MslEncoderUtils.createArray(ctx, format, this.peerServiceTokens));
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_ENCODE_ERROR, "headerdata", e)
.setMasterToken(this.masterToken)
.setEntityAuthenticationData(this.entityAuthData)
.setUserIdToken(this.userIdToken)
.setUserAuthenticationData(this.userAuthData)
.setMessageId(this.messageId);
}
// Create the correct crypto context.
if (this.masterToken != null) {
// Use a stored master token crypto context if we have one.
final ICryptoContext cachedCryptoContext = ctx.getMslStore().getCryptoContext(this.masterToken);
// If there was no stored crypto context try making one from
// the master token. We can only do this if we can open up the
// master token.
if (cachedCryptoContext == null) {
if (!this.masterToken.isVerified() || !this.masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, this.masterToken).setUserIdToken(this.userIdToken).setUserAuthenticationData(this.userAuthData).setMessageId(this.messageId);
this.messageCryptoContext = new SessionCryptoContext(ctx, this.masterToken);
} else {
this.messageCryptoContext = cachedCryptoContext;
}
} else {
try {
final EntityAuthenticationScheme scheme = this.entityAuthData.getScheme();
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(scheme);
if (factory == null)
throw new MslEntityAuthException(MslError.ENTITYAUTH_FACTORY_NOT_FOUND, scheme.name());
this.messageCryptoContext = factory.getCryptoContext(ctx, this.entityAuthData);
} catch (final MslCryptoException e) {
e.setEntityAuthenticationData(this.entityAuthData);
e.setUserIdToken(this.userIdToken);
e.setUserAuthenticationData(this.userAuthData);
e.setMessageId(this.messageId);
throw e;
} catch (final MslEntityAuthException e) {
e.setEntityAuthenticationData(this.entityAuthData);
e.setUserIdToken(this.userIdToken);
e.setUserAuthenticationData(this.userAuthData);
e.setMessageId(this.messageId);
throw e;
}
}
}
/**
* <p>Construct a new message from the provided JSON object.</p>
*
* <p>Headers are encrypted and signed. If a master token is found, it will
* be used for this purpose. Otherwise the crypto context appropriate for
* the entity authentication scheme will be used. Either the master token
* or entity authentication data must be found.</p>
*
* <p>If user authentication data is included user authentication will be
* performed. If a user ID token is included then its user information is
* considered to be trusted.</p>
*
* <p>Service tokens will be decrypted and verified with the provided crypto
* contexts identified by token name. A default crypto context may be
* provided by using the empty string as the token name; if a token name is
* not explicitly mapped onto a crypto context, the default crypto context
* will be used.</p>
*
* @param ctx MSL context.
* @param headerdataBytes encoded header data.
* @param entityAuthData the entity authentication data. May be null if a
* master token is provided.
* @param masterToken the master token. May be null if entity
* authentication data is provided.
* @param signature the header signature.
* @param cryptoContexts the map of service token names onto crypto
* contexts used to decrypt and verify service tokens.
* @throws MslEncodingException if there is an error parsing the JSON.
* @throws MslCryptoException if there is an error decrypting or verifying
* the header or creating the key exchange crypto context.
* @throws MslEntityAuthException if unable to create the entity
* authentication data or there is an error with the entity
* authentication data.
* @throws MslKeyExchangeException if unable to create the key request data
* or key response data.
* @throws MslUserAuthException if unable to create the user authentication
* data or authenticate the user.
* @throws MslMasterTokenException if the header master token is not
* trusted and needs to be to accept this message header.
* @throws MslMessageException if the message does not contain an entity
* authentication data or a master token, the header data is
* missing or invalid, or the message ID is negative, or the
* message is not encrypted and contains user authentication data.
* @throws MslException if a token is improperly bound to another token.
*/
protected MessageHeader(final MslContext ctx, final byte[] headerdataBytes, final EntityAuthenticationData entityAuthData, final MasterToken masterToken, final byte[] signature, final Map<String,ICryptoContext> cryptoContexts) throws MslEncodingException, MslCryptoException, MslKeyExchangeException, MslUserAuthException, MslMasterTokenException, MslMessageException, MslEntityAuthException, MslException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] plaintext;
try {
this.entityAuthData = (masterToken == null) ? entityAuthData : null;
this.masterToken = masterToken;
if (entityAuthData == null && masterToken == null)
throw new MslMessageException(MslError.MESSAGE_ENTITY_NOT_FOUND);
// Create the correct crypto context.
if (masterToken != null) {
// Use a stored master token crypto context if we have one.
final ICryptoContext cachedCryptoContext = ctx.getMslStore().getCryptoContext(masterToken);
// If there was no stored crypto context try making one from
// the master token. We can only do this if we can open up the
// master token.
if (cachedCryptoContext == null) {
if (!masterToken.isVerified() || !masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
this.messageCryptoContext = new SessionCryptoContext(ctx, masterToken);
} else {
this.messageCryptoContext = cachedCryptoContext;
}
} else {
try {
final EntityAuthenticationScheme scheme = entityAuthData.getScheme();
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(scheme);
if (factory == null)
throw new MslEntityAuthException(MslError.ENTITYAUTH_FACTORY_NOT_FOUND, scheme.name());
this.messageCryptoContext = factory.getCryptoContext(ctx, entityAuthData);
} catch (final MslCryptoException e) {
e.setEntityAuthenticationData(entityAuthData);
throw e;
} catch (final MslEntityAuthException e) {
e.setEntityAuthenticationData(entityAuthData);
throw e;
}
}
// Verify and decrypt the header data.
//
// Throw different errors depending on whether or not a master
// token was used.
if (!this.messageCryptoContext.verify(headerdataBytes, signature, encoder)) {
if (masterToken != null)
throw new MslCryptoException(MslError.MESSAGE_MASTERTOKENBASED_VERIFICATION_FAILED);
else
throw new MslCryptoException(MslError.MESSAGE_ENTITYDATABASED_VERIFICATION_FAILED);
}
plaintext = this.messageCryptoContext.decrypt(headerdataBytes, encoder);
} catch (final MslCryptoException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
throw e;
} catch (final MslEntityAuthException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
throw e;
}
try {
headerdata = encoder.parseObject(plaintext);
// Pull the message ID first because any error responses need to
// use it.
this.messageId = headerdata.getLong(KEY_MESSAGE_ID);
if (this.messageId < 0 || this.messageId > MslConstants.MAX_LONG_VALUE)
throw new MslMessageException(MslError.MESSAGE_ID_OUT_OF_RANGE, "headerdata " + headerdata).setMasterToken(masterToken).setEntityAuthenticationData(entityAuthData);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "headerdata " + Base64.encode(plaintext), e).setMasterToken(masterToken).setEntityAuthenticationData(entityAuthData);
}
try {
this.timestamp = (headerdata.has(KEY_TIMESTAMP)) ? headerdata.getLong(KEY_TIMESTAMP) : null;
// Pull key response data.
final MasterToken tokenVerificationMasterToken;
if (headerdata.has(KEY_KEY_RESPONSE_DATA)) {
this.keyResponseData = KeyResponseData.create(ctx, headerdata.getMslObject(KEY_KEY_RESPONSE_DATA, encoder));
// The key response data master token is used for token
// verification in a trusted services network. Otherwise it
// will be used for peer token verification, which is handled
// below.
tokenVerificationMasterToken = (!ctx.isPeerToPeer())
? this.keyResponseData.getMasterToken()
: masterToken;
} else {
this.keyResponseData = null;
tokenVerificationMasterToken = masterToken;
}
// User ID tokens are always authenticated by a master token.
this.userIdToken = (headerdata.has(KEY_USER_ID_TOKEN))
? new UserIdToken(ctx, headerdata.getMslObject(KEY_USER_ID_TOKEN, encoder), tokenVerificationMasterToken)
: null;
// Pull user authentication data.
this.userAuthData = (headerdata.has(KEY_USER_AUTHENTICATION_DATA))
? UserAuthenticationData.create(ctx, tokenVerificationMasterToken, headerdata.getMslObject(KEY_USER_AUTHENTICATION_DATA, encoder))
: null;
// Identify the user if any.
if (this.userAuthData != null) {
// Reject unencrypted messages containing user authentication data.
final boolean encrypted = (masterToken != null) ? true : entityAuthData.getScheme().encrypts();
if (!encrypted)
throw new MslMessageException(MslError.UNENCRYPTED_MESSAGE_WITH_USERAUTHDATA).setUserIdToken(userIdToken).setUserAuthenticationData(userAuthData);
// Verify the user authentication data.
final UserAuthenticationScheme scheme = this.userAuthData.getScheme();
final UserAuthenticationFactory factory = ctx.getUserAuthenticationFactory(scheme);
if (factory == null)
throw new MslUserAuthException(MslError.USERAUTH_FACTORY_NOT_FOUND, scheme.name()).setUserIdToken(userIdToken).setUserAuthenticationData(userAuthData);
final String identity = (this.masterToken != null) ? this.masterToken.getIdentity() : this.entityAuthData.getIdentity();
this.user = factory.authenticate(ctx, identity, this.userAuthData, this.userIdToken);
} else if (this.userIdToken != null) {
this.user = this.userIdToken.getUser();
} else {
this.user = null;
}
// Service tokens are authenticated by the master token if it
// exists or by the application crypto context.
final Set<ServiceToken> serviceTokens = new HashSet<ServiceToken>();
if (headerdata.has(KEY_SERVICE_TOKENS)) {
final MslArray tokens = headerdata.getMslArray(KEY_SERVICE_TOKENS);
for (int i = 0; i < tokens.size(); ++i) {
try {
serviceTokens.add(new ServiceToken(ctx, tokens.getMslObject(i, encoder), tokenVerificationMasterToken, this.userIdToken, cryptoContexts));
} catch (final MslException e) {
e.setMasterToken(tokenVerificationMasterToken).setUserIdToken(this.userIdToken).setUserAuthenticationData(userAuthData);
throw e;
}
}
}
this.serviceTokens = Collections.unmodifiableSet(serviceTokens);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "headerdata " + headerdata, e).setMasterToken(masterToken).setEntityAuthenticationData(entityAuthData).setMessageId(this.messageId);
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setMessageId(this.messageId);
throw e;
}
try {
this.nonReplayableId = (headerdata.has(KEY_NON_REPLAYABLE_ID)) ? headerdata.getLong(KEY_NON_REPLAYABLE_ID) : null;
this.renewable = headerdata.getBoolean(KEY_RENEWABLE);
// FIXME: Make handshake required once all MSL stacks are updated.
this.handshake = (headerdata.has(KEY_HANDSHAKE)) ? headerdata.getBoolean(KEY_HANDSHAKE) : false;
// Verify values.
if (nonReplayableId != null && (nonReplayableId < 0 || nonReplayableId > MslConstants.MAX_LONG_VALUE))
throw new MslMessageException(MslError.NONREPLAYABLE_ID_OUT_OF_RANGE, "headerdata " + headerdata);
// Pull message capabilities.
if (headerdata.has(KEY_CAPABILITIES)) {
final MslObject capabilitiesMo = headerdata.getMslObject(KEY_CAPABILITIES, encoder);
this.capabilities = new MessageCapabilities(capabilitiesMo);
} else {
this.capabilities = null;
}
// Pull key request data containers.
final Set<KeyRequestData> keyRequestData = new HashSet<KeyRequestData>();
if (headerdata.has(KEY_KEY_REQUEST_DATA)) {
final MslArray keyRequests = headerdata.getMslArray(KEY_KEY_REQUEST_DATA);
for (int i = 0; i < keyRequests.size(); ++i) {
keyRequestData.add(KeyRequestData.create(ctx, keyRequests.getMslObject(i, encoder)));
}
}
this.keyRequestData = Collections.unmodifiableSet(keyRequestData);
// Only process peer-to-peer tokens if in peer-to-peer mode.
if (ctx.isPeerToPeer()) {
// Pull peer master token.
this.peerMasterToken = (headerdata.has(KEY_PEER_MASTER_TOKEN))
? new MasterToken(ctx, headerdata.getMslObject(KEY_PEER_MASTER_TOKEN, encoder))
: null;
// The key response data master token is used for peer token
// verification if in peer-to-peer mode.
final MasterToken peerVerificationMasterToken;
if (this.keyResponseData != null)
peerVerificationMasterToken = this.keyResponseData.getMasterToken();
else
peerVerificationMasterToken = this.peerMasterToken;
// Pull peer user ID token. User ID tokens are always
// authenticated by a master token.
try {
this.peerUserIdToken = (headerdata.has(KEY_PEER_USER_ID_TOKEN))
? new UserIdToken(ctx, headerdata.getMslObject(KEY_PEER_USER_ID_TOKEN, encoder), peerVerificationMasterToken)
: null;
} catch (final MslException e) {
e.setMasterToken(peerVerificationMasterToken);
throw e;
}
// Peer service tokens are authenticated by the peer master
// token if it exists or by the application crypto context.
final Set<ServiceToken> peerServiceTokens = new HashSet<ServiceToken>();
if (headerdata.has(KEY_PEER_SERVICE_TOKENS)) {
final MslArray tokens = headerdata.getMslArray(KEY_PEER_SERVICE_TOKENS);
for (int i = 0; i < tokens.size(); ++i) {
try {
peerServiceTokens.add(new ServiceToken(ctx, tokens.getMslObject(i, encoder), peerVerificationMasterToken, this.peerUserIdToken, cryptoContexts));
} catch (final MslException e) {
e.setMasterToken(peerVerificationMasterToken).setUserIdToken(this.peerUserIdToken);
throw e;
}
}
}
this.peerServiceTokens = Collections.unmodifiableSet(peerServiceTokens);
} else {
this.peerMasterToken = null;
this.peerUserIdToken = null;
this.peerServiceTokens = Collections.emptySet();
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "headerdata " + headerdata.toString(), e)
.setMasterToken(masterToken)
.setEntityAuthenticationData(entityAuthData)
.setUserIdToken(this.userIdToken)
.setUserAuthenticationData(this.userAuthData)
.setMessageId(this.messageId);
} catch (final MslException e) {
e.setMasterToken(masterToken);
e.setEntityAuthenticationData(entityAuthData);
e.setUserIdToken(this.userIdToken);
e.setUserAuthenticationData(this.userAuthData);
e.setMessageId(this.messageId);
throw e;
}
}
/**
* @return true if the message header crypto context provides encryption.
* @see #getCryptoContext()
*/
public boolean isEncrypting() {
return masterToken != null || entityAuthData.getScheme().encrypts();
}
/**
* Returns the crypto context that was used to process the header data.
* This crypto context should also be used to process the payload data if
* no key response data is included in the message.
*
* @return the header data crypto context.
* @see #isEncrypting()
*/
public ICryptoContext getCryptoContext() {
return messageCryptoContext;
}
/**
* Returns the user if the user has been authenticated or a user ID token
* was provided.
*
* @return the user. May be null.
*/
public MslUser getUser() {
return user;
}
/**
* Returns the entity authentication data. May be null if the entity has
* already been authenticated and is using a master token instead.
*
* @return the entity authentication data.
*/
public EntityAuthenticationData getEntityAuthenticationData() {
return entityAuthData;
}
/**
* Returns the primary master token identifying the entity and containing
* the session keys. May be null if the entity has not been authenticated.
*
* @return the master token. May be null.
*/
public MasterToken getMasterToken() {
return masterToken;
}
/**
* @return the timestamp. May be null.
*/
public Date getTimestamp() {
return (timestamp != null) ? new Date(timestamp * MILLISECONDS_PER_SECOND) : null;
}
/**
* @return the message ID.
*/
public long getMessageId() {
return messageId;
}
/**
* @return the non-replayable ID. May be null.
*/
public Long getNonReplayableId() {
return nonReplayableId;
}
/**
* @return true if the message renewable flag is set.
*/
public boolean isRenewable() {
return renewable;
}
/**
* @return true if the message handshake flag is set.
*/
public boolean isHandshake() {
return handshake;
}
/**
* @return the message capabilities. May be null.
*/
public MessageCapabilities getMessageCapabilities() {
return capabilities;
}
/**
* @return key request data. May be empty.
*/
public Set<KeyRequestData> getKeyRequestData() {
return keyRequestData;
}
/**
* @return key response data. May be null.
*/
public KeyResponseData getKeyResponseData() {
return keyResponseData;
}
/**
* Returns the user authentication data. May be null if the user has
* already been authenticated and is using a user ID token or if there is
* no user authentication requested.
*
* @return the user authentication data. May be null.
*/
public UserAuthenticationData getUserAuthenticationData() {
return userAuthData;
}
/**
* Returns the primary user ID token identifying the user. May be null if
* the user has not been authenticated.
*
* @return the user ID token. May be null.
*/
public UserIdToken getUserIdToken() {
return userIdToken;
}
/**
* Returns the primary service tokens included in this message.
*
* The returned list is immutable.
*
* @return the service tokens. May be empty if no there are no service
* tokens.
*/
public Set<ServiceToken> getServiceTokens() {
return serviceTokens;
}
/**
* Returns the master token that should be used by an entity responding to
* this message. Will be null if the responding entity should use its own
* entity authentication data or the primary master token.
*
* @return the peer master token. May be null.
*/
public MasterToken getPeerMasterToken() {
return peerMasterToken;
}
/**
* Returns the user ID token that must be used by an entity responding to
* this message if an peer master token is provided. May be null if peer
* user authentication has not occurred. Will be null if there is no peer
* master token.
*
* @return the peer user ID token. May be null.
*/
public UserIdToken getPeerUserIdToken() {
return peerUserIdToken;
}
/**
* <p>Returns the service tokens that must be used by an entity responding
* to this message. May be null if the responding entity should use the
* primary service tokens.</p>
*
* <p>The returned list is immutable.</p>
*
* @return the peer service tokens. May be empty if no there are no peer
* service tokens.
*/
public Set<ServiceToken> getPeerServiceTokens() {
return peerServiceTokens;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
// Return any cached encoding.
if (encodings.containsKey(format))
return encodings.get(format);
// Encrypt and sign the header data.
final byte[] plaintext = encoder.encodeObject(headerdata, format);
final byte[] ciphertext;
try {
ciphertext = this.messageCryptoContext.encrypt(plaintext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error encrypting the header data.", e);
}
final byte[] signature;
try {
signature = this.messageCryptoContext.sign(ciphertext, encoder, format);
} catch (final MslCryptoException e) {
throw new MslEncoderException("Error signging the header data.", e);
}
// Create the encoding.
final MslObject header = encoder.createObject();
if (masterToken != null)
header.put(Header.KEY_MASTER_TOKEN, masterToken);
else
header.put(Header.KEY_ENTITY_AUTHENTICATION_DATA, entityAuthData);
header.put(Header.KEY_HEADERDATA, ciphertext);
header.put(Header.KEY_SIGNATURE, signature);
final byte[] encoding = encoder.encodeObject(header, format);
// Cache and return the encoding.
encodings.put(format, encoding);
return encoding;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (!(obj instanceof MessageHeader)) return false;
final MessageHeader that = (MessageHeader) obj;
return (masterToken != null && masterToken.equals(that.masterToken) ||
entityAuthData != null && entityAuthData.equals(that.entityAuthData)) &&
(timestamp != null && timestamp.equals(that.timestamp) ||
timestamp == null && that.timestamp == null) &&
messageId == that.messageId &&
(nonReplayableId != null && nonReplayableId.equals(that.nonReplayableId) ||
nonReplayableId == null && that.nonReplayableId == null) &&
renewable == that.renewable &&
handshake == that.handshake &&
(capabilities != null && capabilities.equals(that.capabilities) ||
capabilities == that.capabilities) &&
keyRequestData.equals(that.keyRequestData) &&
(keyResponseData != null && keyResponseData.equals(that.keyResponseData) ||
keyResponseData == that.keyResponseData) &&
(userAuthData != null && userAuthData.equals(that.userAuthData) ||
userAuthData == that.userAuthData) &&
(userIdToken != null && userIdToken.equals(that.userIdToken) ||
userIdToken == that.userIdToken) &&
serviceTokens.equals(that.serviceTokens) &&
(peerMasterToken != null && peerMasterToken.equals(that.peerMasterToken) ||
peerMasterToken == that.peerMasterToken) &&
(peerUserIdToken != null && peerUserIdToken.equals(that.peerUserIdToken) ||
peerUserIdToken == that.peerUserIdToken) &&
peerServiceTokens.equals(that.peerServiceTokens);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return ((masterToken != null) ? masterToken.hashCode() : entityAuthData.hashCode()) ^
((timestamp != null) ? timestamp.hashCode() : 0) ^
Long.valueOf(messageId).hashCode() ^
((nonReplayableId != null) ? nonReplayableId.hashCode() : 0) ^
Boolean.valueOf(renewable).hashCode() ^
Boolean.valueOf(handshake).hashCode() ^
((capabilities != null) ? capabilities.hashCode() : 0) ^
keyRequestData.hashCode() ^
((keyResponseData != null) ? keyResponseData.hashCode() : 0) ^
((userAuthData != null) ? userAuthData.hashCode() : 0) ^
((userIdToken != null) ? userIdToken.hashCode() : 0) ^
serviceTokens.hashCode() ^
((peerMasterToken != null) ? peerMasterToken.hashCode() : 0) ^
((peerUserIdToken != null) ? peerUserIdToken.hashCode() : 0) ^
peerServiceTokens.hashCode();
}
/** Entity authentication data. */
protected final EntityAuthenticationData entityAuthData;
/** Master token. */
protected final MasterToken masterToken;
/** Header data. */
protected final MslObject headerdata;
/** Timestamp in seconds since the epoch. */
private final Long timestamp;
/** Message ID. */
private final long messageId;
/** Non-replayable ID. */
private final Long nonReplayableId;
/** Renewable. */
private final boolean renewable;
/** Handshake message. */
private final boolean handshake;
/** Message capabilities. */
private final MessageCapabilities capabilities;
/** Key request data. */
private final Set<KeyRequestData> keyRequestData;
/** Key response data. */
private final KeyResponseData keyResponseData;
/** User authentication data. */
private final UserAuthenticationData userAuthData;
/** User ID token. */
private final UserIdToken userIdToken;
/** Service tokens (immutable). */
private final Set<ServiceToken> serviceTokens;
/** Peer master token. */
private final MasterToken peerMasterToken;
/** Peer user ID token. */
private final UserIdToken peerUserIdToken;
/** Peer service tokens (immutable). */
private final Set<ServiceToken> peerServiceTokens;
/** User (if authenticated). */
private final MslUser user;
/** Message crypto context. */
protected final ICryptoContext messageCryptoContext;
/** Cached encodings. */
protected final Map<MslEncoderFormat,byte[]> encodings = new HashMap<MslEncoderFormat,byte[]>();
}
| 9,864 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/Header.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.util.Map;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncodable;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* <p>A MSL header contains entity authentication data or a master token
* identifying the message sender and data used to authenticate the header
* data. Portions of the header may be encrypted.</p>
*
* <p>A message header is represented as
* {@code
* header = {
* "#mandatory" : [ "headerdata", "signature" ],
* "#conditions" : [ "entityauthdata xor mastertoken" ],
* "entityauthdata" : entityauthdata,
* "mastertoken" : mastertoken,
* "headerdata" : "binary",
* "signature" : "binary"
* }} where:
* <ul>
* <li>{@code entityauthdata} is the entity authentication data (mutually exclusive with mastertoken)</li>
* <li>{@code mastertoken} is the master token (mutually exclusive with entityauthdata)</li>
* <li>{@code headerdata} is the encrypted header data (headerdata)</li>
* <li>{@code signature} is the verification data of the header data</li>
* </ul></p>
*
* <p>An error header is represented as
* {@code
* errorheader = {
* "#mandatory" : [ "entityauthdata", "errordata", "signature" ],
* "entityauthdata" : entityauthdata,
* "errordata" : "binary",
* "signature" : "binary"
* }} where:
* <ul>
* <li>{@code entityauthdata} is the entity authentication data</li>
* <li>{@code errordata} is the encrypted error data (errordata)</li>
* <li>{@code signature} is the verification data of the error data</li>
* </ul></p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class Header implements MslEncodable {
/** Key entity authentication data. */
public static final String KEY_ENTITY_AUTHENTICATION_DATA = "entityauthdata";
/** Key master token. */
public static final String KEY_MASTER_TOKEN = "mastertoken";
/** Key header data. */
public static final String KEY_HEADERDATA = "headerdata";
/** Key error data. */
public static final String KEY_ERRORDATA = "errordata";
/** Key signature. */
public static final String KEY_SIGNATURE = "signature";
/**
* <p>Construct a new header from the provided MSL object.</p>
*
* <p>Headers are encrypted and signed. If a master token is found, it will
* be used for this purpose. Otherwise the crypto context appropriate for
* the entity authentication scheme will be used.</p>
*
* <p>For message headers the master token or entity authentication data
* must be found. For error headers the entity authentication data must be
* found.</p>
*
* <p>Service tokens will be decrypted and verified with the provided crypto
* contexts identified by token name. A default crypto context may be
* provided by using the empty string as the token name; if a token name is
* not explcitly mapped onto a crypto context, the default crypto context
* will be used.</p>
*
* @param ctx MSL context.
* @param headerMo header MSL object.
* @param cryptoContexts the map of service token names onto crypto
* contexts used to decrypt and verify service tokens.
* @return the header.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException if there is an error decrypting or verifying
* the message.
* @throws MslEntityAuthException if unable to create the entity
* authentication data.
* @throws MslKeyExchangeException if unable to create the key request data
* or key response data.
* @throws MslUserAuthException if unable to create the user authentication
* data.
* @throws MslMessageException if the message does not contain an entity
* authentication data or a master token, the header data is
* missing or invalid, or the message ID is negative, or the
* message is not encrypted and contains user authentication data.
* @throws MslException if the message does not contain an entity
* authentication data or a master token or a token is improperly
* bound to another token.
*/
public static Header parseHeader(final MslContext ctx, final MslObject headerMo, final Map<String,ICryptoContext> cryptoContexts) throws MslEncodingException, MslEntityAuthException, MslCryptoException, MslKeyExchangeException, MslUserAuthException, MslMessageException, MslException {
// Pull authentication data.
final EntityAuthenticationData entityAuthData;
final MasterToken masterToken;
final byte[] signature;
try {
// Pull message data.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
entityAuthData = (headerMo.has(Header.KEY_ENTITY_AUTHENTICATION_DATA))
? EntityAuthenticationData.create(ctx, headerMo.getMslObject(Header.KEY_ENTITY_AUTHENTICATION_DATA, encoder))
: null;
masterToken = (headerMo.has(Header.KEY_MASTER_TOKEN))
? new MasterToken(ctx, headerMo.getMslObject(Header.KEY_MASTER_TOKEN, encoder))
: null;
signature = headerMo.getBytes(Header.KEY_SIGNATURE);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "header/errormsg " + headerMo, e);
}
try {
// Process message headers.
if (headerMo.has(Header.KEY_HEADERDATA)) {
final byte[] headerdata = headerMo.getBytes(Header.KEY_HEADERDATA);
if (headerdata.length == 0)
throw new MslMessageException(MslError.HEADER_DATA_MISSING).setMasterToken(masterToken).setEntityAuthenticationData(entityAuthData);
return new MessageHeader(ctx, headerdata, entityAuthData, masterToken, signature, cryptoContexts);
}
// Process error headers.
else if (headerMo.has(Header.KEY_ERRORDATA)) {
final byte[] errordata = headerMo.getBytes(Header.KEY_ERRORDATA);
if (errordata.length == 0)
throw new MslMessageException(MslError.HEADER_DATA_MISSING).setMasterToken(masterToken).setEntityAuthenticationData(entityAuthData);
return new ErrorHeader(ctx, errordata, entityAuthData, signature);
}
// Unknown header.
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, headerMo.toString());
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "header/errormsg " + headerMo, e);
}
}
}
| 9,865 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/PublicMessageContext.java | /**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
/**
* <p>A message context implementation that can be extended for use with
* messages that do not require contents to be encrypted, only to be integrity
* protected. If encryption is possible the message contents will be
* encrypted.</p>
*
* <p>Example uses of the public message context would be for the broadcast of
* authenticated public announcements or the transmission of information that
* is useless after a short period of time.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class PublicMessageContext implements MessageContext {
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isEncrypted()
*/
@Override
public boolean isEncrypted() {
return false;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isIntegrityProtected()
*/
@Override
public boolean isIntegrityProtected() {
return true;
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.MessageContext#isNonReplayable()
*/
@Override
public boolean isNonReplayable() {
return false;
}
}
| 9,866 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/msg/ConsoleFilterStreamFactory.java | /**
* Copyright (c) 2013-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.msg;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The console filter stream factory will output the wrapped streams data to
* stdout.
*
* This class is thread-safe.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class ConsoleFilterStreamFactory implements FilterStreamFactory {
/**
* A filter input stream that outputs read data to stdout. A new line is
* output when the stream is closed.
*/
private static class ConsoleInputStream extends FilterInputStream {
/**
* Create a new console input stream backed by the provided input
* stream.
*
* @param in the backing input stream.
*/
protected ConsoleInputStream(final InputStream in) {
super(in);
}
/* (non-Javadoc)
* @see java.io.FilterInputStream#close()
*/
@Override
public void close() throws IOException {
System.out.println();
System.out.flush();
super.close();
}
/* (non-Javadoc)
* @see java.io.FilterInputStream#read()
*/
@Override
public int read() throws IOException {
final int c = in.read();
System.out.write(c);
System.out.flush();
return c;
}
/* (non-Javadoc)
* @see java.io.FilterInputStream#read(byte[], int, int)
*/
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
final int r = in.read(b, off, len);
System.out.write(b, off, len);
System.out.flush();
return r;
}
}
/**
* A filter output stream that outputs written data to stdout. A newline is
* output when the stream is closed.
*/
private static class ConsoleOutputStream extends FilterOutputStream {
/**
* Create a new console output stream backed by the provided output
* stream.
*
* @param out the backing output stream.
*/
public ConsoleOutputStream(final OutputStream out) {
super(out);
}
/* (non-Javadoc)
* @see java.io.FilterOutputStream#close()
*/
@Override
public void close() throws IOException {
System.out.println();
System.out.flush();
super.close();
}
/* (non-Javadoc)
* @see java.io.FilterOutputStream#write(byte[], int, int)
*/
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
System.out.write(b, off, len);
System.out.flush();
out.write(b, off, len);
}
/* (non-Javadoc)
* @see java.io.FilterOutputStream#write(int)
*/
@Override
public void write(final int b) throws IOException {
System.out.write(b);
System.out.flush();
out.write(b);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.FilterStreamFactory#getInputStream(java.io.InputStream)
*/
@Override
public InputStream getInputStream(final InputStream in) {
return new ConsoleInputStream(in);
}
/* (non-Javadoc)
* @see com.netflix.msl.msg.FilterStreamFactory#getOutputStream(java.io.OutputStream)
*/
@Override
public OutputStream getOutputStream(final OutputStream out) {
return new ConsoleOutputStream(out);
}
}
| 9,867 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/KeyResponseData.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.keyx;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.io.MslEncodable;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* <p>Key response data contains all the data needed to facilitate a exchange of
* session keys from the responder.</p>
*
* <p>Specific key exchange mechanisms should define their own key response data
* types.</p>
*
* <p>Key response data is represented as
* {@code
* keyresponsedata = {
* "#mandatory" : [ "mastertoken", "scheme", "keydata" ],
* "mastertoken" : mastertoken,
* "scheme" : "string",
* "keydata" : object
* }} where:
* <ul>
* <li>{@code mastertoken} is the master token associated with the session keys</li>
* <li>{@code scheme} is the key exchange scheme</li>
* <li>{@code keydata} is the scheme-specific key data</li>
* </ul></p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class KeyResponseData implements MslEncodable {
/** Key master token. */
private static final String KEY_MASTER_TOKEN = "mastertoken";
/** Key key exchange scheme. */
private static final String KEY_SCHEME = "scheme";
/** Key key data. */
private static final String KEY_KEYDATA = "keydata";
/**
* Create a new key response data object with the specified key exchange
* scheme and associated master token.
*
* @param masterToken the master token.
* @param scheme the key exchange scheme.
*/
protected KeyResponseData(final MasterToken masterToken, final KeyExchangeScheme scheme) {
this.masterToken = masterToken;
this.scheme = scheme;
}
/**
* Construct a new key response data instance of the correct type from the
* provided MSL object.
*
* @param ctx MSL context.
* @param keyResponseDataMo the MSL object.
* @return the key response data concrete instance.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if unable to create the key response
* data.
* @throws MslCryptoException if there is an error verifying the they key
* response data.
* @throws MslException if the key response master token expiration
* timestamp occurs before the renewal window.
*/
public static KeyResponseData create(final MslContext ctx, final MslObject keyResponseDataMo) throws MslEncodingException, MslCryptoException, MslKeyExchangeException, MslException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
try {
// Pull the key data.
final MasterToken masterToken = new MasterToken(ctx, keyResponseDataMo.getMslObject(KEY_MASTER_TOKEN, encoder));
final String schemeName = keyResponseDataMo.getString(KEY_SCHEME);
final KeyExchangeScheme scheme = ctx.getKeyExchangeScheme(schemeName);
if (scheme == null)
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_SCHEME, schemeName);
final MslObject keyData = keyResponseDataMo.getMslObject(KEY_KEYDATA, encoder);
// Construct an instance of the concrete subclass.
final KeyExchangeFactory factory = ctx.getKeyExchangeFactory(scheme);
if (factory == null)
throw new MslKeyExchangeException(MslError.KEYX_FACTORY_NOT_FOUND, scheme.name());
return factory.createResponseData(ctx, masterToken, keyData);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keyresponsedata " + keyResponseDataMo, e);
}
}
/**
* @return the master token.
*/
public MasterToken getMasterToken() {
return masterToken;
}
/**
* @return the key exchange scheme.
*/
public KeyExchangeScheme getKeyExchangeScheme() {
return scheme;
}
/**
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the key data MSL representation.
* @throws MslEncoderException if there was an error constructing the MSL
* representation.
*/
protected abstract MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException;
/** Master token. */
private final MasterToken masterToken;
/** Key exchange scheme. */
private final KeyExchangeScheme scheme;
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_MASTER_TOKEN, masterToken);
mo.put(KEY_SCHEME, scheme.name());
mo.put(KEY_KEYDATA, getKeydata(encoder, format));
return encoder.encodeObject(mo, format);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof KeyResponseData)) return false;
final KeyResponseData that = (KeyResponseData)obj;
return masterToken.equals(that.masterToken) && scheme.equals(that.scheme);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return masterToken.hashCode() ^ scheme.hashCode();
}
}
| 9,868 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/KeyExchangeScheme.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.keyx;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* <p>Key exchange schemes.</p>
*
* <p>The scheme name is used to uniquely identify key exchange schemes.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class KeyExchangeScheme {
/** Map of names onto schemes. */
private static Map<String,KeyExchangeScheme> schemes = new HashMap<String,KeyExchangeScheme>();
/** Asymmetric key wrapped. */
public static final KeyExchangeScheme ASYMMETRIC_WRAPPED = new KeyExchangeScheme("ASYMMETRIC_WRAPPED");
/** Diffie-Hellman exchange (Netflix SHA-384 key derivation). */
public static final KeyExchangeScheme DIFFIE_HELLMAN = new KeyExchangeScheme("DIFFIE_HELLMAN");
/** JSON web encryption ladder exchange. */
public static final KeyExchangeScheme JWE_LADDER = new KeyExchangeScheme("JWE_LADDER");
/** JSON web key ladder exchange. */
public static final KeyExchangeScheme JWK_LADDER = new KeyExchangeScheme("JWK_LADDER");
/** Symmetric key wrapped. */
public static final KeyExchangeScheme SYMMETRIC_WRAPPED = new KeyExchangeScheme("SYMMETRIC_WRAPPED");
/**
* Define a key exchange scheme with the specified name.
*
* @param name the key exchange scheme name.
*/
protected KeyExchangeScheme(final String name) {
this.name = name;
// Add this scheme to the map.
synchronized (schemes) {
schemes.put(name, this);
}
}
/**
* @param name the key exchange scheme name.
* @return the scheme identified by the specified name or {@code null} if
* there is none.
*/
public static KeyExchangeScheme getScheme(final String name) {
return schemes.get(name);
}
/**
* @return all known key exchange schemes.
*/
public static Collection<KeyExchangeScheme> values() {
return schemes.values();
}
/**
* @return the scheme identifier.
*/
public String name() {
return name;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return name();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return name.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof KeyExchangeScheme)) return false;
final KeyExchangeScheme that = (KeyExchangeScheme)obj;
return this.name.equals(that.name);
}
/** Scheme name. */
private final String name;
}
| 9,869 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/DiffieHellmanExchange.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.keyx;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.DHPublicKeySpec;
import javax.crypto.spec.SecretKeySpec;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.CryptoCache;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.SessionCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>Diffie-Hellman key exchange.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class DiffieHellmanExchange extends KeyExchangeFactory {
/** Key Diffie-Hellman parameters ID. */
private static final String KEY_PARAMETERS_ID = "parametersid";
/** Key Diffie-Hellman public key. */
private static final String KEY_PUBLIC_KEY = "publickey";
/**
* If the provided byte array begins with one and only one null byte this
* function simply returns the original array. Otherwise a new array is
* created that is a copy of the original array with exactly one null byte
* in position zero, and this new array is returned.
*
* @param b the original array.
* @return the resulting byte array.
*/
private static byte[] correctNullBytes(final byte[] b) {
// Count the number of leading nulls.
int leadingNulls = 0;
for (int i = 0; i < b.length; ++i) {
if (b[i] != 0x00)
break;
++leadingNulls;
}
// If there is exactly one leading null, return the original array.
if (leadingNulls == 1)
return b;
// Create a copy of the non-null bytes and prepend exactly one null
// byte.
final int copyLength = b.length - leadingNulls;
final byte[] result = new byte[copyLength + 1];
result[0] = 0x00;
System.arraycopy(b, leadingNulls, result, 1, copyLength);
return result;
}
/**
* <p>Diffie-Hellman key request data. </p>
*
* <p>
* {@code {
* "#mandatory" : [ "parametersid", "publickey" ],
* "parametersid" : "string",
* "publickey" : "binary",
* }} where:
* <ul>
* <li>{@code parametersid} identifies the Diffie-Hellman paramters to use</li>
* <li>{@code publickey} the public key used to generate the shared secret</li>
* </ul>
* </p>
*/
public static class RequestData extends KeyRequestData {
/**
* Create a new Diffie-Hellman request data repository with the
* specified parameters ID and public key. The private key is also
* required but is not included in the request data.
*
* @param parametersId the parameters ID.
* @param publicKey the public key Y-value.
* @param privateKey the private key.
*/
public RequestData(final String parametersId, final BigInteger publicKey, final DHPrivateKey privateKey) {
super(KeyExchangeScheme.DIFFIE_HELLMAN);
this.parametersId = parametersId;
this.publicKey = publicKey;
this.privateKey = privateKey;
}
/**
* Create a new Diffie-Hellman request data repository from the
* provided MSL object. The private key will be unknown.
*
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the public key is invalid.
*/
public RequestData(final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
super(KeyExchangeScheme.DIFFIE_HELLMAN);
try {
parametersId = keyDataMo.getString(KEY_PARAMETERS_ID);
final byte[] publicKeyY = keyDataMo.getBytes(KEY_PUBLIC_KEY);
if (publicKeyY.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_INVALID_PUBLIC_KEY, "keydata " + keyDataMo.toString());
publicKey = new BigInteger(correctNullBytes(publicKeyY));
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo.toString(), e);
} catch (final NumberFormatException e) {
throw new MslKeyExchangeException(MslError.KEYX_INVALID_PUBLIC_KEY, "keydata " + keyDataMo.toString(), e);
}
privateKey = null;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_PARAMETERS_ID, parametersId);
final byte[] publicKeyY = publicKey.toByteArray();
mo.put(KEY_PUBLIC_KEY, correctNullBytes(publicKeyY));
return mo;
}
/**
* @return the parameters ID.
*/
public String getParametersId() {
return parametersId;
}
/**
* @return the public key Y-value.
*/
public BigInteger getPublicKey() {
return publicKey;
}
/**
* @return the private key or null if unknown (reconstructed from a
* MSL object).
*/
public DHPrivateKey getPrivateKey() {
return privateKey;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this)
return true;
if (!(obj instanceof RequestData))
return false;
final RequestData that = (RequestData)obj;
final boolean privateKeysEqual =
privateKey == that.privateKey ||
(privateKey != null && that.privateKey != null && Arrays.equals(privateKey.getEncoded(), that.privateKey.getEncoded()));
return super.equals(obj) &&
parametersId.equals(that.parametersId) &&
publicKey.equals(that.publicKey) && privateKeysEqual;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
// Private keys are optional but must be considered.
final int privateKeyHashCode = (privateKey != null) ? Arrays.hashCode(privateKey.getEncoded()) : 0;
return super.hashCode() ^ parametersId.hashCode() ^
publicKey.hashCode() ^ privateKeyHashCode;
}
/** Diffie-Hellman parameters ID. */
private final String parametersId;
/** Diffie-Hellman public key Y-value. */
private final BigInteger publicKey;
/** Diffie-Hellman private key. */
private final DHPrivateKey privateKey;
}
/**
* <p>Diffie-Hellman key response data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "parametersid", "publickey" ],
* "parametersid" : "string",
* "publickey" : "binary",
* }} where:
* <ul>
* <li>{@code parametersid} identifies the Diffie-Hellman paramters to use</li>
* <li>{@code publickey} the public key used to generate the shared secret</li>
* </ul>
* </p>
*/
public static class ResponseData extends KeyResponseData {
/**
* Create a new Diffie-Hellman response data repository with the
* provided master token, specified parameters ID and public key.
*
* @param masterToken the master token.
* @param parametersId the parameters ID.
* @param publicKey the public key Y-value.
*/
public ResponseData(final MasterToken masterToken, final String parametersId, final BigInteger publicKey) {
super(masterToken, KeyExchangeScheme.DIFFIE_HELLMAN);
this.parametersId = parametersId;
this.publicKey = publicKey;
}
/**
* Create a new Diffie-Hellman response data repository with the
* provided master token from the provided MSL object.
*
* @param masterToken the master token.
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the public key is invalid.
*/
public ResponseData(final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
super(masterToken, KeyExchangeScheme.DIFFIE_HELLMAN);
try {
parametersId = keyDataMo.getString(KEY_PARAMETERS_ID);
final byte[] publicKeyY = keyDataMo.getBytes(KEY_PUBLIC_KEY);
if (publicKeyY.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_INVALID_PUBLIC_KEY, "keydata " + keyDataMo);
publicKey = new BigInteger(correctNullBytes(publicKeyY));
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
} catch (final NumberFormatException e) {
throw new MslKeyExchangeException(MslError.KEYX_INVALID_PUBLIC_KEY, "keydata " + keyDataMo, e);
}
}
/**
* @return the parameters ID.
*/
public String getParametersId() {
return parametersId;
}
/**
* @return the public key Y-value.
*/
public BigInteger getPublicKey() {
return publicKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_PARAMETERS_ID, parametersId);
final byte[] publicKeyY = publicKey.toByteArray();
mo.put(KEY_PUBLIC_KEY, correctNullBytes(publicKeyY));
return mo;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this)
return true;
if (!(obj instanceof ResponseData))
return false;
final ResponseData that = (ResponseData) obj;
return super.equals(obj) &&
parametersId.equals(that.parametersId) &&
publicKey.equals(that.publicKey);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ parametersId.hashCode() ^ publicKey.hashCode();
}
/** Diffie-Hellman parameters ID. */
private final String parametersId;
/** Diffie-Hellman public key. */
private final BigInteger publicKey;
}
/**
* Container struct for session keys.
*/
private static class SessionKeys {
/**
* @param encryptionKey the encryption key.
* @param hmacKey the HMAC key.
*/
public SessionKeys(final SecretKey encryptionKey, final SecretKey hmacKey) {
this.encryptionKey = encryptionKey;
this.hmacKey = hmacKey;
}
/** Encryption key. */
public final SecretKey encryptionKey;
/** HMAC key. */
public final SecretKey hmacKey;
}
/**
* Derives the encryption and HMAC session keys from a Diffie-Hellman
* shared secret.
*
* @param publicKey Diffie-Hellman public key.
* @param privateKey Diffie-Hellman private key.
* @param params Diffie-Hellman parameter specification.
* @return the derived session keys.
*/
private static SessionKeys deriveSessionKeys(final PublicKey publicKey, final PrivateKey privateKey, final DHParameterSpec params) {
// Compute Diffie-Hellman shared secret.
final byte[] sharedSecret;
try {
final KeyAgreement agreement = CryptoCache.getKeyAgreement("DiffieHellman");
agreement.init(privateKey, params);
agreement.doPhase(publicKey, true);
sharedSecret = correctNullBytes(agreement.generateSecret());
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidKeyException e) {
throw new MslInternalException("Diffie-Hellman private key or generated public key rejected by Diffie-Hellman key agreement.", e);
} catch (final InvalidAlgorithmParameterException e) {
throw new MslInternalException("Diffie-Hellman algorithm parameters rejected by Diffie-Hellman key agreement.", e);
}
// Derive encryption and HMAC keys.
final MessageDigest sha384;
try {
sha384 = CryptoCache.getMessageDigest("SHA-384");
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("SHA-384 algorithm not found.", e);
}
final byte[] hash = sha384.digest(sharedSecret);
final byte[] kcedata = new byte[128 / Byte.SIZE];
System.arraycopy(hash, 0, kcedata, 0, kcedata.length);
final byte[] kchdata = new byte[256 / Byte.SIZE];
System.arraycopy(hash, kcedata.length, kchdata, 0, kchdata.length);
// Return encryption and HMAC keys.
final SecretKey encryptionKey = new SecretKeySpec(kcedata, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(kchdata, JcaAlgorithm.HMAC_SHA256);
return new SessionKeys(encryptionKey, hmacKey);
}
/**
* Create a new Diffie-Hellman key exchange factory.
*
* @param params Diffie-Hellman parameters.
* @param authutils authentication utilities.
*/
public DiffieHellmanExchange(final DiffieHellmanParameters params, final AuthenticationUtils authutils) {
super(KeyExchangeScheme.DIFFIE_HELLMAN);
this.params = params;
this.authutils = authutils;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createRequestData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslKeyExchangeException, MslCryptoException {
return new RequestData(keyRequestMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createResponseData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
return new ResponseData(masterToken, keyDataMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData) keyRequestData;
// If the master token was not issued by the local entity then we
// should not be generating a key response for it.
if (!masterToken.isVerified())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
// Verify the scheme is permitted.
final String identity = masterToken.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setMasterToken(masterToken);
// Load matching Diffie-Hellman parameter specification.
final String parametersId = request.getParametersId();
final DHParameterSpec paramSpec = params.getParameterSpec(parametersId);
if (paramSpec == null)
throw new MslKeyExchangeException(MslError.UNKNOWN_KEYX_PARAMETERS_ID, parametersId);
// Reconstitute request public key.
final PublicKey requestPublicKey;
try {
final KeyFactory factory = CryptoCache.getKeyFactory("DiffieHellman");
final BigInteger y = request.getPublicKey();
final DHPublicKeySpec publicKeySpec = new DHPublicKeySpec(y, paramSpec.getP(), paramSpec.getG());
requestPublicKey = factory.generatePublic(publicKeySpec);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidKeySpecException e) {
throw new MslInternalException("Diffie-Hellman public key specification rejected by Diffie-Hellman key factory.", e);
}
// Generate public/private key pair.
final DHPublicKey responsePublicKey;
final DHPrivateKey responsePrivateKey;
try {
final KeyPairGenerator generator = CryptoCache.getKeyPairGenerator("DH");
generator.initialize(paramSpec);
final KeyPair keyPair = generator.generateKeyPair();
responsePublicKey = (DHPublicKey)keyPair.getPublic();
responsePrivateKey = (DHPrivateKey)keyPair.getPrivate();
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidAlgorithmParameterException e) {
throw new MslInternalException("Diffie-Hellman algorithm parameters rejected by Diffie-Hellman key agreement.", e);
}
// Construct encryption and HMAC keys.
final SessionKeys sessionKeys = deriveSessionKeys(requestPublicKey, responsePrivateKey, paramSpec);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.renewMasterToken(ctx, masterToken, sessionKeys.encryptionKey, sessionKeys.hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, parametersId, responsePublicKey.getY());
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final EntityAuthenticationData entityAuthData) throws MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = entityAuthData.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setEntityAuthenticationData(entityAuthData);
// Load matching Diffie-Hellman parameter specification.
final String parametersId = request.getParametersId();
final DHParameterSpec paramSpec = params.getParameterSpec(parametersId);
if (paramSpec == null)
throw new MslKeyExchangeException(MslError.UNKNOWN_KEYX_PARAMETERS_ID, parametersId).setEntityAuthenticationData(entityAuthData);
// Reconstitute request public key.
final PublicKey requestPublicKey;
try {
final KeyFactory factory = CryptoCache.getKeyFactory("DiffieHellman");
final BigInteger y = request.getPublicKey();
final DHPublicKeySpec publicKeySpec = new DHPublicKeySpec(y, paramSpec.getP(), paramSpec.getG());
requestPublicKey = factory.generatePublic(publicKeySpec);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidKeySpecException e) {
throw new MslInternalException("Diffie-Hellman public key specification rejected by Diffie-Hellman key factory.", e);
}
// Generate public/private key pair.
final DHPublicKey responsePublicKey;
final DHPrivateKey responsePrivateKey;
try {
final KeyPairGenerator generator = KeyPairGenerator.getInstance("DH");
generator.initialize(paramSpec);
final KeyPair keyPair = generator.generateKeyPair();
responsePublicKey = (DHPublicKey)keyPair.getPublic();
responsePrivateKey = (DHPrivateKey)keyPair.getPrivate();
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidAlgorithmParameterException e) {
throw new MslInternalException("Diffie-Hellman algorithm parameters rejected by Diffie-Hellman key agreement.", e);
}
// Construct encryption and HMAC keys.
final SessionKeys sessionKeys = deriveSessionKeys(requestPublicKey, responsePrivateKey, paramSpec);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken masterToken = tokenFactory.createMasterToken(ctx, entityAuthData, sessionKeys.encryptionKey, sessionKeys.hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext;
try {
cryptoContext = new SessionCryptoContext(ctx, masterToken);
} catch (final MslMasterTokenException e) {
throw new MslInternalException("Master token constructed by token factory is not trusted.", e);
}
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(masterToken, parametersId, responsePublicKey.getY());
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.keyx.KeyResponseData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
if (!(keyResponseData instanceof ResponseData))
throw new MslInternalException("Key response data " + keyResponseData.getClass().getName() + " was not created by this factory.");
final ResponseData response = (ResponseData)keyResponseData;
// Verify response matches request.
final String requestParametersId = request.getParametersId();
final String responseParametersId = response.getParametersId();
if (!requestParametersId.equals(responseParametersId))
throw new MslKeyExchangeException(MslError.KEYX_RESPONSE_REQUEST_MISMATCH, "request " + requestParametersId + "; response " + responseParametersId).setMasterToken(masterToken);
// Reconstitute response public key.
final DHPrivateKey privateKey = request.getPrivateKey();
if (privateKey == null)
throw new MslKeyExchangeException(MslError.KEYX_PRIVATE_KEY_MISSING, "request Diffie-Hellman private key").setMasterToken(masterToken);
final DHParameterSpec params = privateKey.getParams();
final PublicKey publicKey;
try {
final KeyFactory factory = CryptoCache.getKeyFactory("DiffieHellman");
final BigInteger y = response.getPublicKey();
final DHPublicKeySpec publicKeySpec = new DHPublicKeySpec(y, params.getP(), params.getG());
publicKey = factory.generatePublic(publicKeySpec);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("DiffieHellman algorithm not found.", e);
} catch (final InvalidKeySpecException e) {
throw new MslKeyExchangeException(MslError.KEYX_INVALID_PUBLIC_KEY, "Diffie-Hellman public key specification rejected by Diffie-Hellman key factory.", e);
}
// Create crypto context.
final String identity = ctx.getEntityAuthenticationData(null).getIdentity();
final SessionKeys sessionKeys = deriveSessionKeys(publicKey, privateKey, params);
final MasterToken responseMasterToken = response.getMasterToken();
return new SessionCryptoContext(ctx, responseMasterToken, identity, sessionKeys.encryptionKey, sessionKeys.hmacKey);
}
/** Diffie-Hellman parameters. */
private final DiffieHellmanParameters params;
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 9,870 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/KeyRequestData.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.keyx;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.io.MslEncodable;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.util.MslContext;
/**
* <p>Key request data contains all the data needed to facilitate a exchange of
* session keys with the requesting entity.</p>
*
* <p>Specific key exchange mechanisms should define their own key request data
* types.</p>
*
* <p>Key request data is represented as
* {@code
* keyrequestdata = {
* "#mandatory" : [ "scheme", "keydata" ],
* "scheme" : "string",
* "keydata" : object
* }} where:
* <ul>
* <li>{@code scheme} is the key exchange scheme</li>
* <li>{@code keydata} is the scheme-specific key data</li>
* </ul></p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class KeyRequestData implements MslEncodable {
/** Key key exchange scheme. */
private static final String KEY_SCHEME = "scheme";
/** Key key request data. */
private static final String KEY_KEYDATA = "keydata";
/**
* Create a new key request data object with the specified key exchange
* scheme.
*
* @param scheme the key exchange scheme.
*/
protected KeyRequestData(final KeyExchangeScheme scheme) {
this.scheme = scheme;
}
/**
* Construct a new key request data instance of the correct type from the
* provided MSL object.
*
* @param ctx MSL context.
* @param keyRequestDataMo the MSL object.
* @return the key request data concrete instance.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException if there is an error verifying the key
* request data.
* @throws MslEntityAuthException if the entity authentication data could
* not be created.
* @throws MslKeyExchangeException if unable to create the key request
* data.
*/
public static KeyRequestData create(final MslContext ctx, final MslObject keyRequestDataMo) throws MslEncodingException, MslCryptoException, MslEntityAuthException, MslKeyExchangeException {
try {
// Pull the key data.
final String schemeName = keyRequestDataMo.getString(KEY_SCHEME);
final KeyExchangeScheme scheme = ctx.getKeyExchangeScheme(schemeName);
if (scheme == null)
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_SCHEME, schemeName);
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslObject keyData = keyRequestDataMo.getMslObject(KEY_KEYDATA, encoder);
// Construct an instance of the concrete subclass.
final KeyExchangeFactory keyFactory = ctx.getKeyExchangeFactory(scheme);
if (keyFactory == null)
throw new MslKeyExchangeException(MslError.KEYX_FACTORY_NOT_FOUND, scheme.name());
return keyFactory.createRequestData(ctx, keyData);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keyrequestdata " + keyRequestDataMo, e);
}
}
/**
* @return the key exchange scheme.
*/
public KeyExchangeScheme getKeyExchangeScheme() {
return scheme;
}
/**
* @param encoder MSL encoder factory.
* @param format MSL encoder format.
* @return the key data MSL representation.
* @throws MslEncoderException if there was an error constructing the MSL
* representation.
*/
protected abstract MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException;
/** Key exchange scheme. */
private final KeyExchangeScheme scheme;
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncodable#toMslEncoding(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public final byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_SCHEME, scheme.name());
mo.put(KEY_KEYDATA, getKeydata(encoder, format));
return encoder.encodeObject(mo, format);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof KeyRequestData)) return false;
final KeyRequestData that = (KeyRequestData)obj;
return scheme.equals(that.scheme);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return scheme.hashCode();
}
}
| 9,871 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/JsonWebEncryptionLadderExchange.java | /**
* Copyright (c) 2013-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.keyx;
import java.nio.charset.Charset;
import java.util.Arrays;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.AesKwCryptoContext;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.CekCryptoContext;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.Encryption;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.Format;
import com.netflix.msl.crypto.JsonWebKey;
import com.netflix.msl.crypto.JsonWebKey.Algorithm;
import com.netflix.msl.crypto.JsonWebKey.Usage;
import com.netflix.msl.crypto.SessionCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.entityauth.PresharedAuthenticationData;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>JSON Web Encryption ladder key exchange.</p>
*
* <p>The key ladder consists of a symmetric wrapping key used to protect the
* session keys. The wrapping key is only permitted to wrap and unwrap data. It
* cannot be used for encrypt/decrypt or sign/verify operations.</p>
*
* <p>The wrapping key is protected by wrapping it with a known common key
* (e.g. preshared keys) or the previously used wrapping key. The previous
* wrapping key must be provided by the requesting entity in the form found in
* the response data.</p>
*
* <p>The wrapping key is always an AES-128 key for AES key wrap/unwrap.</p>
*
* <p>This key exchange scheme does not provide perfect forward secrecy and
* should only be used if necessary to satisfy other security requirements.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class JsonWebEncryptionLadderExchange extends KeyExchangeFactory {
/** Encoding charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/** Wrapping key wrap mechanism. */
public enum Mechanism {
/** Wrapping key wrapped by PSK (AES-128 key wrap). */
PSK,
/** Wrapping key wrapped by previous wrapping key (AES-128 key wrap). */
WRAP,
}
/**
* <p>JSON Web Encryption ladder key request data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "mechanism" ],
* "mechanism" : "enum(PSK|MGK|WRAP)",
* "wrapdata" : "binary",
* }} where:
* <ul>
* <li>{@code mechanism} identifies the mechanism for wrapping and unwrapping the wrapping key</li>
* <li>{@code wrapdata} the wrapping data for the previous wrapping key</li>
* </ul></p>
*/
public static class RequestData extends KeyRequestData {
/** Key wrap key wrapping mechanism. */
private static final String KEY_MECHANISM = "mechanism";
/** Key wrap data. */
private static final String KEY_WRAPDATA = "wrapdata";
/**
* <p>Create a new JSON Web Encryption ladder key request data instance
* with the specified mechanism and wrapping key data.</p>
*
* <p>Arguments not applicable to the specified mechanism are
* ignored.</p>
*
* @param mechanism the wrap key wrapping mechanism.
* @param wrapdata the wrap data for reconstructing the previous
* wrapping key. May be null if the mechanism does not use the
* previous wrapping key.
* @throws MslInternalException if the mechanism requires wrap data and
* the required argument is null.
*/
public RequestData(final Mechanism mechanism, final byte[] wrapdata) {
super(KeyExchangeScheme.JWE_LADDER);
this.mechanism = mechanism;
switch (mechanism) {
case WRAP:
if (wrapdata == null)
throw new MslInternalException("Previous wrapping key based key exchange requires the previous wrapping key data and ID.");
this.wrapdata = wrapdata;
break;
default:
this.wrapdata = null;
break;
}
}
/**
* Create a new JSON Web Encryption ladder key request data instance
* from the provided MSL object.
*
* @param keyRequestMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException the wrapped key data cannot be verified
* or decrypted, or the specified mechanism is not supported.
* @throws MslKeyExchangeException if the specified mechanism is not
* recognized or the wrap data is missing or invalid.
*/
public RequestData(final MslObject keyRequestMo) throws MslCryptoException, MslKeyExchangeException, MslEncodingException {
super(KeyExchangeScheme.JWE_LADDER);
try {
final String mechanismName = keyRequestMo.getString(KEY_MECHANISM);
try {
mechanism = Mechanism.valueOf(mechanismName);
} catch (final IllegalArgumentException e) {
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_MECHANISM, mechanismName, e);
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyRequestMo, e);
}
try {
switch (mechanism) {
case PSK:
{
wrapdata = null;
break;
}
case WRAP:
{
wrapdata = keyRequestMo.getBytes(KEY_WRAPDATA);
if (wrapdata.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING, "keydata " + keyRequestMo);
break;
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyRequestMo, e);
}
}
/**
* @return the wrap key wrapping mechanism.
*/
public Mechanism getMechanism() {
return mechanism;
}
/**
* @return the previous wrapping key data or null if not applicable.
*/
public byte[] getWrapdata() {
return wrapdata;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_MECHANISM, mechanism.name());
if (wrapdata != null) mo.put(KEY_WRAPDATA, wrapdata);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof RequestData)) return false;
final RequestData that = (RequestData)obj;
final boolean wrapdataEqual = Arrays.equals(wrapdata, that.wrapdata);
return super.equals(obj) &&
mechanism.equals(that.mechanism) &&
wrapdataEqual;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#hashCode()
*/
@Override
public int hashCode() {
final int wrapdataHashCode = (wrapdata != null) ? Arrays.hashCode(wrapdata) : 0;
return super.hashCode() ^
mechanism.hashCode() ^
wrapdataHashCode;
}
/** Wrap key wrapping mechanism. */
private final Mechanism mechanism;
/** Wrap data. */
private final byte[] wrapdata;
}
/**
* <p>JSON Web Encryption ladder key response data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "wrapkey", "wrapdata", "encryptionkey", "hmackey" ],
* "wrapkey" : "binary",
* "wrapdata" : "binary",
* "encryptionkey" : "binary",
* "hmackey" : "binary",
* }} where:
* <ul>
* <li>{@code wrapkey} the new wrapping key in JWE format, wrapped by the wrapping key</li>
* <li>{@code wrapdata} the wrapping key data for use in subsequent key request data</li>
* <li>{@code encryptionkey} the session encryption key in JWE format, wrapped with the new wrapping key</li>
* <li>{@code hmackey} the session HMAC key in JWE format, wrapped with the new wrapping key</li>
* </ul></p>
*/
public static class ResponseData extends KeyResponseData {
/** Key wrapping key. */
private static final String KEY_WRAP_KEY = "wrapkey";
/** Key wrapping key data. */
private static final String KEY_WRAPDATA = "wrapdata";
/** Key encrypted encryption key. */
private static final String KEY_ENCRYPTION_KEY = "encryptionkey";
/** Key encrypted HMAC key. */
private static final String KEY_HMAC_KEY = "hmackey";
/**
* Create a new JSON Web Encryption ladder key response data instance
* with the provided master token and wrapped keys.
*
* @param masterToken the master token.
* @param wrapKey the wrapped wrap key.
* @param wrapdata the wrap data for reconstructing the wrap key.
* @param encryptionKey the wrap key wrapped encryption key.
* @param hmacKey the wrap key wrapped HMAC key.
*/
public ResponseData(final MasterToken masterToken, final byte[] wrapKey, final byte[] wrapdata, final byte[] encryptionKey, final byte[] hmacKey) {
super(masterToken, KeyExchangeScheme.JWE_LADDER);
this.wrapKey = wrapKey;
this.wrapdata = wrapdata;
this.encryptionKey = encryptionKey;
this.hmacKey = hmacKey;
}
/**
* Create a new JSON Web Encryption ladder key response data instance
* with the provided master token from the provided MSL object.
*
* @param masterToken the master token.
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the mechanism is not recognized,
* any of the keys are invalid, or if the wrap data is invalid.
*/
public ResponseData(final MasterToken masterToken, final MslObject keyDataMo) throws MslKeyExchangeException, MslEncodingException {
super(masterToken, KeyExchangeScheme.JWE_LADDER);
try {
wrapKey = keyDataMo.getBytes(KEY_WRAP_KEY);
wrapdata = keyDataMo.getBytes(KEY_WRAPDATA);
encryptionKey = keyDataMo.getBytes(KEY_ENCRYPTION_KEY);
hmacKey = keyDataMo.getBytes(KEY_HMAC_KEY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
}
}
/**
* @return the session key wrapping key.
*/
public byte[] getWrapKey() {
return wrapKey;
}
/**
* @return the session key wrapping key data.
*/
public byte[] getWrapdata() {
return wrapdata;
}
/**
* @return the wrapped session encryption key.
*/
public byte[] getEncryptionKey() {
return encryptionKey;
}
/**
* @return the wrapped session HMAC key.
*/
public byte[] getHmacKey() {
return hmacKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) {
final MslObject mo = encoder.createObject();
mo.put(KEY_WRAP_KEY, wrapKey);
mo.put(KEY_WRAPDATA, wrapdata);
mo.put(KEY_ENCRYPTION_KEY, encryptionKey);
mo.put(KEY_HMAC_KEY, hmacKey);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof ResponseData)) return false;
final ResponseData that = (ResponseData)obj;
return super.equals(obj) &&
Arrays.equals(wrapKey, that.wrapKey) &&
Arrays.equals(wrapdata, that.wrapdata) &&
Arrays.equals(encryptionKey, that.encryptionKey) &&
Arrays.equals(hmacKey, that.hmacKey);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^
Arrays.hashCode(wrapKey) ^
Arrays.hashCode(wrapdata) ^
Arrays.hashCode(encryptionKey) ^
Arrays.hashCode(hmacKey);
}
/** Wrapped wrap key. */
private final byte[] wrapKey;
/** Wrap data. */
private final byte[] wrapdata;
/** Wrapped encryption key. */
private final byte[] encryptionKey;
/** Wrapped HMAC key. */
private final byte[] hmacKey;
}
/**
* Create the crypto context identified by the mechanism.
*
* @param ctx MSL context.
* @param mechanism the wrap key wrapping mechanism.
* @param wrapdata the wrap key previous wrapping key data. May be null.
* @param identity the entity identity.
* @return the crypto context.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslKeyExchangeException if the mechanism is unsupported.
* @throws MslEntityAuthException if there is a problem with the entity
* identity.
*/
private static ICryptoContext createCryptoContext(final MslContext ctx, final Mechanism mechanism, final byte[] wrapdata, final String identity) throws MslKeyExchangeException, MslCryptoException, MslEntityAuthException {
switch (mechanism) {
case PSK:
{
final EntityAuthenticationData authdata = new PresharedAuthenticationData(identity);
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(EntityAuthenticationScheme.PSK);
if (factory == null)
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
final ICryptoContext cryptoContext = factory.getCryptoContext(ctx, authdata);
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(cryptoContext);
return new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
}
case WRAP:
{
final ICryptoContext cryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapBytes = cryptoContext.unwrap(wrapdata, encoder);
if (wrapBytes == null || wrapBytes.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(wrapKey);
return new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
}
default:
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
}
/**
* Create a new JSON Web Encryption ladder key exchange factory.
*
* @param repository the wrapping key crypto context repository.
* @param authutils authentication utilities.
*/
public JsonWebEncryptionLadderExchange(final WrapCryptoContextRepository repository, final AuthenticationUtils authutils) {
super(KeyExchangeScheme.JWE_LADDER);
this.repository = repository;
this.authutils = authutils;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createRequestData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslKeyExchangeException, MslCryptoException {
return new RequestData(keyRequestMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createResponseData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
return new ResponseData(masterToken, keyDataMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException, MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// If the master token was not issued by the local entity then we
// should not be generating a key response for it.
if (!masterToken.isVerified())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
// Verify the scheme is permitted.
final String identity = masterToken.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setMasterToken(masterToken);
// Create random AES-128 wrapping key with a random key ID.
final String wrapKeyId = String.valueOf(ctx.getRandom().nextLong());
final byte[] wrapBytes = new byte[16];
ctx.getRandom().nextBytes(wrapBytes);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
// Create the wrap data.
final ICryptoContext mslCryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapdata = mslCryptoContext.wrap(wrapBytes, encoder, format);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Grab the request data.
final Mechanism mechanism = request.getMechanism();
final byte[] prevWrapdata = request.getWrapdata();
// Wrap wrapping key using specified wrapping key.
final JsonWebKey wrapJwk = new JsonWebKey(Usage.wrap, Algorithm.A128KW, false, wrapKeyId, wrapKey);
final byte[] wrapJwkBytes = wrapJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final ICryptoContext wrapKeyCryptoContext = createCryptoContext(ctx, mechanism, prevWrapdata, identity);
final byte[] wrappedWrapJwk = wrapKeyCryptoContext.wrap(wrapJwkBytes, encoder, format);
// Wrap session keys inside JSON Web Key objects with the wrapping key.
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(wrapKey);
final ICryptoContext wrapCryptoContext = new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
final JsonWebKey encryptionJwk = new JsonWebKey(Usage.enc, Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(Usage.sig, Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] wrappedEncryptionJwk = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
final byte[] wrappedHmacJwk = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.renewMasterToken(ctx, masterToken, encryptionKey, hmacKey, null);
// Create session crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, wrappedWrapJwk, wrapdata, wrappedEncryptionJwk, wrappedHmacJwk);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData,final EntityAuthenticationData entityAuthData) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslEntityAuthException, MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = entityAuthData.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication Sscheme for entity not permitted " + identity + ":" + this.getScheme()).setEntityAuthenticationData(entityAuthData);
// Create random AES-128 wrapping key with a random key ID.
final String wrapKeyId = String.valueOf(ctx.getRandom().nextLong());
final byte[] wrapBytes = new byte[16];
ctx.getRandom().nextBytes(wrapBytes);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
// Create the wrap data.
final ICryptoContext mslCryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapdata = mslCryptoContext.wrap(wrapBytes, encoder, format);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Grab the request data.
final Mechanism mechanism = request.getMechanism();
final byte[] prevWrapdata = request.getWrapdata();
// Wrap wrapping key using specified wrapping key.
final JsonWebKey wrapJwk = new JsonWebKey(Usage.wrap, Algorithm.A128KW, false, wrapKeyId, wrapKey);
final byte[] wrapJwkBytes = wrapJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final ICryptoContext wrapKeyCryptoContext = createCryptoContext(ctx, mechanism, prevWrapdata, identity);
final byte[] wrappedWrapJwk = wrapKeyCryptoContext.wrap(wrapJwkBytes, encoder, format);
// Wrap session keys inside JSON Web Key objects with the wrapping key.
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(wrapKey);
final ICryptoContext wrapCryptoContext = new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
final JsonWebKey encryptionJwk = new JsonWebKey(Usage.enc, Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(Usage.sig, Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] wrappedEncryptionJwk = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
final byte[] wrappedHmacJwk = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.createMasterToken(ctx, entityAuthData, encryptionKey, hmacKey, null);
// Create session crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, wrappedWrapJwk, wrapdata, wrappedEncryptionJwk, wrappedHmacJwk);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.keyx.KeyResponseData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
if (!(keyResponseData instanceof ResponseData))
throw new MslInternalException("Key response data " + keyResponseData.getClass().getName() + " was not created by this factory.");
final ResponseData response = (ResponseData)keyResponseData;
// Unwrap new wrapping key.
final Mechanism mechanism = request.getMechanism();
final byte[] requestWrapdata = request.getWrapdata();
final EntityAuthenticationData entityAuthData = ctx.getEntityAuthenticationData(null);
final String identity = entityAuthData.getIdentity();
final ICryptoContext wrapKeyCryptoContext;
switch (mechanism) {
case PSK:
{
final EntityAuthenticationData authdata = new PresharedAuthenticationData(identity);
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(EntityAuthenticationScheme.PSK);
if (factory == null)
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name()).setEntityAuthenticationData(entityAuthData);
final ICryptoContext cryptoContext = factory.getCryptoContext(ctx, authdata);
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(cryptoContext);
wrapKeyCryptoContext = new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
break;
}
case WRAP:
{
wrapKeyCryptoContext = repository.getCryptoContext(requestWrapdata);
if (wrapKeyCryptoContext == null)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING, Base64.encode(requestWrapdata)).setEntityAuthenticationData(entityAuthData);
break;
}
default:
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name()).setEntityAuthenticationData(entityAuthData);
}
// Unwrap wrapping key.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] unwrappedWrapJwk = wrapKeyCryptoContext.unwrap(response.getWrapKey(), encoder);
final JsonWebKey wrapJwk;
try {
final MslObject wrapJwkMo = encoder.parseObject(unwrappedWrapJwk);
wrapJwk = new JsonWebKey(wrapJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedWrapJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
final SecretKey wrapKey = wrapJwk.getSecretKey();
// Unwrap session keys with wrapping key.
final CekCryptoContext cekCryptoContext = new AesKwCryptoContext(wrapKey);
final ICryptoContext unwrapCryptoContext = new JsonWebEncryptionCryptoContext(ctx, cekCryptoContext, Encryption.A128GCM, Format.JWE_JS);
final byte[] unwrappedEncryptionJwk = unwrapCryptoContext.unwrap(response.getEncryptionKey(), encoder);
final byte[] unwrappedHmacJwk = unwrapCryptoContext.unwrap(response.getHmacKey(), encoder);
final JsonWebKey encryptionJwk;
try {
final MslObject encryptionJwkMo = encoder.parseObject(unwrappedEncryptionJwk);
encryptionJwk = new JsonWebKey(encryptionJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedEncryptionJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
final JsonWebKey hmacJwk;
try {
final MslObject hmacJwkMo = encoder.parseObject(unwrappedHmacJwk);
hmacJwk = new JsonWebKey(hmacJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedHmacJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
// Deliver wrap data to wrap key repository.
final byte[] wrapdata = response.getWrapdata();
repository.addCryptoContext(wrapdata, unwrapCryptoContext);
if (requestWrapdata != null)
repository.removeCryptoContext(requestWrapdata);
// Create crypto context.
final MasterToken responseMasterToken = response.getMasterToken();
final SecretKey encryptionKey = encryptionJwk.getSecretKey();
final SecretKey hmacKey = hmacJwk.getSecretKey();
return new SessionCryptoContext(ctx, responseMasterToken, identity, encryptionKey, hmacKey);
}
/** Wrapping keys crypto context repository. */
private final WrapCryptoContextRepository repository;
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 9,872 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/JsonWebKeyLadderExchange.java | /**
* Copyright (c) 2013-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.keyx;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.CryptoCache;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.JsonWebKey;
import com.netflix.msl.crypto.JsonWebKey.Algorithm;
import com.netflix.msl.crypto.JsonWebKey.KeyOp;
import com.netflix.msl.crypto.SessionCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.entityauth.PresharedAuthenticationData;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* <p>JSON Web Key ladder key exchange.</p>
*
* <p>The key ladder consists of a symmetric wrapping key used to protect the
* session keys. The wrapping key is only permitted to wrap and unwrap data. It
* cannot be used for encrypt/decrypt or sign/verify operations.</p>
*
* <p>The wrapping key is protected by wrapping it with a known common key
* (e.g. preshared keys) or the previously used wrapping key. The previous
* wrapping key must be provided by the requesting entity in the form found in
* the response data.</p>
*
* <p>The wrapping key is always an AES-128 key for AES key wrap/unwrap.</p>
*
* <p>This key exchange scheme does not provide perfect forward secrecy and
* should only be used if necessary to satisfy other security requirements.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class JsonWebKeyLadderExchange extends KeyExchangeFactory {
/** Encoding charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/** Dummy wrapping key ID. */
private static final String WRAP_KEY_ID = "wrapKeyId";
/** Encrypt/decrypt key operations. */
private static final Set<KeyOp> ENCRYPT_DECRYPT = new HashSet<KeyOp>(Arrays.asList(KeyOp.encrypt, KeyOp.decrypt));
/** Wrap/unwrap key operations. */
private static final Set<KeyOp> WRAP_UNWRAP = new HashSet<KeyOp>(Arrays.asList(KeyOp.wrapKey, KeyOp.unwrapKey));
/** Sign/verify key operations. */
private static final Set<KeyOp> SIGN_VERIFY = new HashSet<KeyOp>(Arrays.asList(KeyOp.sign, KeyOp.verify));
/** Wrapping key wrap mechanism. */
public enum Mechanism {
/** Wrapping key wrapped by PSK (AES-128 key wrap). */
PSK,
/** Wrapping key wrapped by previous wrapping key (AES-128 key wrap). */
WRAP,
}
/**
* <p>JSON Web Key ladder key request data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "mechanism" ],
* "mechanism" : "enum(PSK|MGK|WRAP)",
* "wrapdata" : "binary",
* }} where:
* <ul>
* <li>{@code mechanism} identifies the mechanism for wrapping and unwrapping the wrapping key</li>
* <li>{@code wrapdata} the wrapping data for the previous wrapping key</li>
* </ul></p>
*/
public static class RequestData extends KeyRequestData {
/** Key wrap key wrapping mechanism. */
private static final String KEY_MECHANISM = "mechanism";
/** Key wrap data. */
private static final String KEY_WRAPDATA = "wrapdata";
/**
* <p>Create a new JSON Web Key ladder key request data instance
* with the specified mechanism and wrapping key data.</p>
*
* <p>Arguments not applicable to the specified mechanism are
* ignored.</p>
*
* @param mechanism the wrap key wrapping mechanism.
* @param wrapdata the wrap data for reconstructing the previous
* wrapping key. May be null if the mechanism does not use the
* previous wrapping key.
* @throws MslInternalException if the mechanism requires wrap data and
* the required argument is null.
*/
public RequestData(final Mechanism mechanism, final byte[] wrapdata) {
super(KeyExchangeScheme.JWK_LADDER);
this.mechanism = mechanism;
switch (mechanism) {
case WRAP:
if (wrapdata == null)
throw new MslInternalException("Previous wrapping key based key exchange requires the previous wrapping key data and ID.");
this.wrapdata = wrapdata;
break;
default:
this.wrapdata = null;
break;
}
}
/**
* Create a new JSON Web Key ladder key request data instance
* from the provided MSL object.
*
* @param keyRequestMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException the wrapped key data cannot be verified
* or decrypted, or the specified mechanism is not supported.
* @throws MslKeyExchangeException if the specified mechanism is not
* recognized or the wrap data is missing or invalid.
*/
public RequestData(final MslObject keyRequestMo) throws MslCryptoException, MslKeyExchangeException, MslEncodingException {
super(KeyExchangeScheme.JWK_LADDER);
try {
final String mechanismName = keyRequestMo.getString(KEY_MECHANISM);
try {
mechanism = Mechanism.valueOf(mechanismName);
} catch (final IllegalArgumentException e) {
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_MECHANISM, mechanismName, e);
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyRequestMo, e);
}
try {
switch (mechanism) {
case PSK:
{
wrapdata = null;
break;
}
case WRAP:
{
wrapdata = keyRequestMo.getBytes(KEY_WRAPDATA);
if (wrapdata.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING, "keydata " + keyRequestMo);
break;
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyRequestMo, e);
}
}
/**
* @return the wrap key wrapping mechanism.
*/
public Mechanism getMechanism() {
return mechanism;
}
/**
* @return the previous wrapping key data or null if not applicable.
*/
public byte[] getWrapdata() {
return wrapdata;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_MECHANISM, mechanism.name());
if (wrapdata != null) mo.put(KEY_WRAPDATA, wrapdata);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof RequestData)) return false;
final RequestData that = (RequestData)obj;
final boolean wrapdataEqual = Arrays.equals(wrapdata, that.wrapdata);
return super.equals(obj) &&
mechanism.equals(that.mechanism) &&
wrapdataEqual;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#hashCode()
*/
@Override
public int hashCode() {
final int wrapdataHashCode = (wrapdata != null) ? Arrays.hashCode(wrapdata) : 0;
return super.hashCode() ^
mechanism.hashCode() ^
wrapdataHashCode;
}
/** Wrap key wrapping mechanism. */
private final Mechanism mechanism;
/** Wrap data. */
private final byte[] wrapdata;
}
/**
* <p>JSON Web Key ladder key response data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "wrapkey", "wrapdata", "encryptionkey", "hmackey" ],
* "wrapkey" : "binary",
* "wrapdata" : "binary",
* "encryptionkey" : "binary",
* "hmackey" : "binary",
* }} where:
* <ul>
* <li>{@code wrapkey} the new wrapping key in JWK format, wrapped by the wrapping key</li>
* <li>{@code wrapdata} the wrapping key data for use in subsequent key request data</li>
* <li>{@code encryptionkey} the session encryption key in JWK format, wrapped with the new wrapping key</li>
* <li>{@code hmackey} the session HMAC key in JWK format, wrapped with the new wrapping key</li>
* </ul></p>
*/
public static class ResponseData extends KeyResponseData {
/** Key wrapping key. */
private static final String KEY_WRAP_KEY = "wrapkey";
/** Key wrapping key data. */
private static final String KEY_WRAPDATA = "wrapdata";
/** Key encrypted encryption key. */
private static final String KEY_ENCRYPTION_KEY = "encryptionkey";
/** Key encrypted HMAC key. */
private static final String KEY_HMAC_KEY = "hmackey";
/**
* Create a new JSON Web Key ladder key response data instance
* with the provided master token and wrapped keys.
*
* @param masterToken the master token.
* @param wrapKey the wrapped wrap key.
* @param wrapdata the wrap data for reconstructing the wrap key.
* @param encryptionKey the wrap key wrapped encryption key.
* @param hmacKey the wrap key wrapped HMAC key.
*/
public ResponseData(final MasterToken masterToken, final byte[] wrapKey, final byte[] wrapdata, final byte[] encryptionKey, final byte[] hmacKey) {
super(masterToken, KeyExchangeScheme.JWK_LADDER);
this.wrapKey = wrapKey;
this.wrapdata = wrapdata;
this.encryptionKey = encryptionKey;
this.hmacKey = hmacKey;
}
/**
* Create a new JSON Web Key ladder key response data instance
* with the provided master token from the provided MSL object.
*
* @param masterToken the master token.
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the mechanism is not recognized.
*/
public ResponseData(final MasterToken masterToken, final MslObject keyDataMo) throws MslKeyExchangeException, MslEncodingException {
super(masterToken, KeyExchangeScheme.JWK_LADDER);
try {
wrapKey = keyDataMo.getBytes(KEY_WRAP_KEY);
wrapdata = keyDataMo.getBytes(KEY_WRAPDATA);
encryptionKey = keyDataMo.getBytes(KEY_ENCRYPTION_KEY);
hmacKey = keyDataMo.getBytes(KEY_HMAC_KEY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
}
}
/**
* @return the session key wrapping key.
*/
public byte[] getWrapKey() {
return wrapKey;
}
/**
* @return the session key wrapping key data.
*/
public byte[] getWrapdata() {
return wrapdata;
}
/**
* @return the wrapped session encryption key.
*/
public byte[] getEncryptionKey() {
return encryptionKey;
}
/**
* @return the wrapped session HMAC key.
*/
public byte[] getHmacKey() {
return hmacKey;
}
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_WRAP_KEY, wrapKey);
mo.put(KEY_WRAPDATA, wrapdata);
mo.put(KEY_ENCRYPTION_KEY, encryptionKey);
mo.put(KEY_HMAC_KEY, hmacKey);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof ResponseData)) return false;
final ResponseData that = (ResponseData)obj;
return super.equals(obj) &&
Arrays.equals(wrapKey, that.wrapKey) &&
Arrays.equals(wrapdata, that.wrapdata) &&
Arrays.equals(encryptionKey, that.encryptionKey) &&
Arrays.equals(hmacKey, that.hmacKey);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^
Arrays.hashCode(wrapKey) ^
Arrays.hashCode(wrapdata) ^
Arrays.hashCode(encryptionKey) ^
Arrays.hashCode(hmacKey);
}
/** Wrapped wrap key. */
private final byte[] wrapKey;
/** Wrap data. */
private final byte[] wrapdata;
/** Wrapped encryption key. */
private final byte[] encryptionKey;
/** Wrapped HMAC key. */
private final byte[] hmacKey;
}
/**
* <p>A specialized crypto context for wrapping and unwrapping JSON web
* keys.</p>
*
* <p>Implementations of this class must add and remove padding to the JSON
* web key string representation's binary encoding for compatibility with
* the wrapping algorithm used.</p>
*/
public static abstract class JwkCryptoContext extends ICryptoContext {
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#encrypt(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] encrypt(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.ENCRYPT_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#decrypt(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] decrypt(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#sign(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] sign(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#verify(byte[], byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public boolean verify(final byte[] data, final byte[] signature, final MslEncoderFactory encoder) throws MslCryptoException {
throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED);
}
}
/**
* AES key wrap JSON web key crypto context.
*/
public static class AesKwJwkCryptoContext extends JwkCryptoContext {
/** AES key wrap cipher transform. */
private static final String A128_KW_TRANSFORM = "AESWrap";
/** AES key wrap block size in bytes. */
private static final int AES_KW_BLOCK_SIZE = 8;
/** Space character. */
private static final byte SPACE = (byte)' ';
/**
* Create an AES key wrap JSON web key crypto context. The provided
* crypto context must perform AES key wrap for its wrap and unwrap
* functions.
*
* @param cryptoContext the backing crypto context.
*/
public AesKwJwkCryptoContext(final ICryptoContext cryptoContext) {
this.key = null;
this.cryptoContext = cryptoContext;
}
/**
* Create an AES key wrap JSON web key crypto context with the provided
* key.
*
* @param key AES secret key.
*/
public AesKwJwkCryptoContext(final SecretKey key) {
if (!key.getAlgorithm().equals(JcaAlgorithm.AESKW))
throw new IllegalArgumentException("Secret key must be an " + JcaAlgorithm.AESKW + " key.");
this.key = key;
this.cryptoContext = null;
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
// Compute the number of bytes that are not aligned to the block
// size.
final int unalignedBytes = data.length % AES_KW_BLOCK_SIZE;
// If there are no unaligned bytes then we're good. Otherwise add
// spaces after the opening brace as padding. This assumes the data
// is actually the UTF-8 binary representation of a JSON web key.
final byte[] alignedJwk;
if (unalignedBytes == 0) {
alignedJwk = data;
} else {
final int paddingCount = AES_KW_BLOCK_SIZE - unalignedBytes;
alignedJwk = new byte[data.length + paddingCount];
alignedJwk[0] = '{';
final int dataOffset = 1 + paddingCount;
Arrays.fill(alignedJwk, 1, dataOffset, SPACE);
System.arraycopy(data, 1, alignedJwk, dataOffset, data.length - 1);
}
// If a secret key is provided use it.
if (key != null) {
try {
// Encrypt plaintext.
final Cipher cipher = CryptoCache.getCipher(A128_KW_TRANSFORM);
cipher.init(Cipher.WRAP_MODE, key);
// The wrap() function requires a key object, but the data
// we are trying to wrap is not necessarily a key. However
// it should be aligned to the AES key wrap block size so
// we can use the AES key wrap algorithm.
final Key secretKey = new SecretKeySpec(alignedJwk, JcaAlgorithm.AESKW);
return cipher.wrap(secretKey);
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Zero-length plaintext provided.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
} catch (final IllegalBlockSizeException e) {
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
}
}
// Otherwise use the backing crypto context.
return cryptoContext.wrap(alignedJwk, encoder, format);
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.ICryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
// If a secret key is provided use it.
if (key != null) {
try {
// Decrypt ciphertext.
final Cipher cipher = CryptoCache.getCipher(A128_KW_TRANSFORM);
cipher.init(Cipher.UNWRAP_MODE, key);
return cipher.unwrap(data, "AES", Cipher.SECRET_KEY).getEncoded();
} catch (final NoSuchPaddingException e) {
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
throw new MslCryptoException(MslError.INVALID_SYMMETRIC_KEY, e);
}
}
// Otherwise use the backing crypto context.
return cryptoContext.unwrap(data, encoder);
}
/** AES secret key. */
private final SecretKey key;
/** AES key wrap crypto context. */
private final ICryptoContext cryptoContext;
}
/**
* Create the JSON web key crypto context identified by the mechanism.
*
* @param ctx MSL context.
* @param mechanism the wrap key wrapping mechanism.
* @param wrapdata the wrap key previous wrapping key data. May be null.
* @param identity the entity identity.
* @return the JSON web key crypto context.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslKeyExchangeException if the mechanism is unsupported.
* @throws MslEntityAuthException if there is a problem with the entity
* identity.
*/
private static JwkCryptoContext createCryptoContext(final MslContext ctx, final Mechanism mechanism, final byte[] wrapdata, final String identity) throws MslKeyExchangeException, MslCryptoException, MslEntityAuthException {
switch (mechanism) {
case PSK:
{
final EntityAuthenticationData authdata = new PresharedAuthenticationData(identity);
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(EntityAuthenticationScheme.PSK);
if (factory == null)
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
final ICryptoContext aesKwCryptoContext = factory.getCryptoContext(ctx, authdata);
return new AesKwJwkCryptoContext(aesKwCryptoContext);
}
case WRAP:
{
final ICryptoContext cryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapBytes = cryptoContext.unwrap(wrapdata, encoder);
if (wrapBytes == null || wrapBytes.length == 0)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
return new AesKwJwkCryptoContext(wrapKey);
}
default:
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
}
/**
* Create a new JSON Web Key ladder key exchange factory.
*
* @param repository the wrapping key crypto context repository.
* @param authutils authentication utilities.
*/
public JsonWebKeyLadderExchange(final WrapCryptoContextRepository repository, final AuthenticationUtils authutils) {
super(KeyExchangeScheme.JWK_LADDER);
this.repository = repository;
this.authutils = authutils;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createRequestData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslKeyExchangeException, MslCryptoException {
return new RequestData(keyRequestMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createResponseData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyResponseMo) throws MslEncodingException, MslKeyExchangeException {
return new ResponseData(masterToken, keyResponseMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException, MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// If the master token was not issued by the local entity then we
// should not be generating a key response for it.
if (!masterToken.isVerified())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
// Grab the request data.
final Mechanism mechanism = request.getMechanism();
final byte[] prevWrapdata = request.getWrapdata();
final String identity = masterToken.getIdentity();
// Verify the scheme is permitted.
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setMasterToken(masterToken);
// Create random AES-128 wrapping key.
final byte[] wrapBytes = new byte[16];
ctx.getRandom().nextBytes(wrapBytes);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
// Create the wrap data.
final ICryptoContext mslCryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapdata = mslCryptoContext.wrap(wrapBytes, encoder, format);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Wrap wrapping key using specified wrapping key.
final JsonWebKey wrapJwk = new JsonWebKey(WRAP_UNWRAP, Algorithm.A128KW, false, WRAP_KEY_ID, wrapKey);
final byte[] wrapJwkBytes = wrapJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final ICryptoContext wrapKeyCryptoContext = createCryptoContext(ctx, mechanism, prevWrapdata, identity);
final byte[] wrappedWrapJwk = wrapKeyCryptoContext.wrap(wrapJwkBytes, encoder, format);
// Wrap session keys inside JSON Web Key objects with the wrapping key.
final ICryptoContext wrapCryptoContext = new AesKwJwkCryptoContext(wrapKey);
final JsonWebKey encryptionJwk = new JsonWebKey(ENCRYPT_DECRYPT, Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(SIGN_VERIFY, Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] wrappedEncryptionJwk = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
final byte[] wrappedHmacJwk = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.renewMasterToken(ctx, masterToken, encryptionKey, hmacKey, null);
// Create session crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, wrappedWrapJwk, wrapdata, wrappedEncryptionJwk, wrappedHmacJwk);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData,final EntityAuthenticationData entityAuthData) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslEntityAuthException, MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = entityAuthData.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setEntityAuthenticationData(entityAuthData);
// Create random AES-128 wrapping key.
final byte[] wrapBytes = new byte[16];
ctx.getRandom().nextBytes(wrapBytes);
final SecretKey wrapKey = new SecretKeySpec(wrapBytes, JcaAlgorithm.AESKW);
// Create the wrap data.
final ICryptoContext mslCryptoContext = ctx.getMslCryptoContext();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] wrapdata = mslCryptoContext.wrap(wrapBytes, encoder, format);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Grab the request data.
final Mechanism mechanism = request.getMechanism();
final byte[] prevWrapdata = request.getWrapdata();
// Wrap wrapping key using specified wrapping key.
final JsonWebKey wrapJwk = new JsonWebKey(WRAP_UNWRAP, Algorithm.A128KW, false, WRAP_KEY_ID, wrapKey);
final byte[] wrapJwkBytes = wrapJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final ICryptoContext wrapKeyCryptoContext = createCryptoContext(ctx, mechanism, prevWrapdata, identity);
final byte[] wrappedWrapJwk = wrapKeyCryptoContext.wrap(wrapJwkBytes, encoder, format);
// Wrap session keys inside JSON Web Key objects with the wrapping key.
final ICryptoContext wrapCryptoContext = new AesKwJwkCryptoContext(wrapKey);
final JsonWebKey encryptionJwk = new JsonWebKey(ENCRYPT_DECRYPT, Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(SIGN_VERIFY, Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] wrappedEncryptionJwk = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
final byte[] wrappedHmacJwk = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.createMasterToken(ctx, entityAuthData, encryptionKey, hmacKey, null);
// Create session crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, wrappedWrapJwk, wrapdata, wrappedEncryptionJwk, wrappedHmacJwk);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.keyx.KeyResponseData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
if (!(keyResponseData instanceof ResponseData))
throw new MslInternalException("Key response data " + keyResponseData.getClass().getName() + " was not created by this factory.");
final ResponseData response = (ResponseData)keyResponseData;
// Unwrap new wrapping key.
final Mechanism mechanism = request.getMechanism();
final byte[] requestWrapdata = request.getWrapdata();
final EntityAuthenticationData entityAuthData = ctx.getEntityAuthenticationData(null);
final String identity = entityAuthData.getIdentity();
final ICryptoContext wrapKeyCryptoContext;
switch (mechanism) {
case PSK:
{
final EntityAuthenticationData authdata = new PresharedAuthenticationData(identity);
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(EntityAuthenticationScheme.PSK);
if (factory == null)
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name()).setEntityAuthenticationData(entityAuthData);
final ICryptoContext cryptoContext = factory.getCryptoContext(ctx, authdata);
wrapKeyCryptoContext = new AesKwJwkCryptoContext(cryptoContext);
break;
}
case WRAP:
{
wrapKeyCryptoContext = repository.getCryptoContext(requestWrapdata);
if (wrapKeyCryptoContext == null)
throw new MslKeyExchangeException(MslError.KEYX_WRAPPING_KEY_MISSING, Base64.encode(requestWrapdata)).setEntityAuthenticationData(entityAuthData);
break;
}
default:
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name()).setEntityAuthenticationData(entityAuthData);
}
// Unwrap wrapping key.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final byte[] unwrappedWrapJwk = wrapKeyCryptoContext.unwrap(response.getWrapKey(), encoder);
final JsonWebKey wrapJwk;
try {
final MslObject wrapJwkMo = encoder.parseObject(unwrappedWrapJwk);
wrapJwk = new JsonWebKey(wrapJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedWrapJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
final SecretKey wrapKey = wrapJwk.getSecretKey();
// Unwrap session keys with wrapping key.
final ICryptoContext unwrapCryptoContext = new AesKwJwkCryptoContext(wrapKey);
final byte[] unwrappedEncryptionJwk = unwrapCryptoContext.unwrap(response.getEncryptionKey(), encoder);
final byte[] unwrappedHmacJwk = unwrapCryptoContext.unwrap(response.getHmacKey(), encoder);
final JsonWebKey encryptionJwk;
try {
final MslObject encryptionJwkMo = encoder.parseObject(unwrappedEncryptionJwk);
encryptionJwk = new JsonWebKey(encryptionJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedEncryptionJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
final JsonWebKey hmacJwk;
try {
final MslObject hmacJwkMo = encoder.parseObject(unwrappedHmacJwk);
hmacJwk = new JsonWebKey(hmacJwkMo);
} catch (final MslEncoderException e) {
throw new MslKeyExchangeException(MslError.INVALID_JWK, new String(unwrappedHmacJwk, UTF_8), e).setEntityAuthenticationData(entityAuthData);
}
// Deliver wrap data to wrap key repository.
final byte[] wrapdata = response.getWrapdata();
repository.addCryptoContext(wrapdata, unwrapCryptoContext);
if (requestWrapdata != null)
repository.removeCryptoContext(requestWrapdata);
// Create crypto context.
final MasterToken responseMasterToken = response.getMasterToken();
final SecretKey encryptionKey = encryptionJwk.getSecretKey();
final SecretKey hmacKey = hmacJwk.getSecretKey();
return new SessionCryptoContext(ctx, responseMasterToken, identity, encryptionKey, hmacKey);
}
/** Wrapping keys crypto context repository. */
private final WrapCryptoContextRepository repository;
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 9,873 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/AsymmetricWrappedExchange.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.keyx;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.AsymmetricCryptoContext;
import com.netflix.msl.crypto.CryptoCache;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.CekCryptoContext;
import com.netflix.msl.crypto.JsonWebEncryptionCryptoContext.Format;
import com.netflix.msl.crypto.JsonWebKey;
import com.netflix.msl.crypto.JsonWebKey.KeyOp;
import com.netflix.msl.crypto.JsonWebKey.Usage;
import com.netflix.msl.crypto.SessionCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>Asymmetric key wrapped key exchange.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class AsymmetricWrappedExchange extends KeyExchangeFactory {
/** Encrypt/decrypt key operations. */
private static final Set<KeyOp> ENCRYPT_DECRYPT = new HashSet<KeyOp>(Arrays.asList(KeyOp.encrypt, KeyOp.decrypt));
/** Sign/verify key operations. */
private static final Set<KeyOp> SIGN_VERIFY = new HashSet<KeyOp>(Arrays.asList(KeyOp.sign, KeyOp.verify));
/**
* <p>An RSA wrapping crypto context is unique in that it treats its wrap/
* unwrap operations as encrypt/decrypt respectively. This is compatible
* with the Web Crypto API.</p>
*/
private static class RsaWrappingCryptoContext extends AsymmetricCryptoContext {
/** JWK RSA crypto context mode. */
public static enum Mode {
/** RSA-OAEP wrap/unwrap */
WRAP_UNWRAP_OAEP,
/** RSA PKCS#1 wrap/unwrap */
WRAP_UNWRAP_PKCS1,
}
/**
* <p>Create a new RSA wrapping crypto context for the specified mode
* using the provided public and private keys. The mode identifies the
* operations to enable. All other operations are no-ops and return the
* data unmodified.</p>
*
* @param ctx MSL context.
* @param id key pair identity.
* @param privateKey the private key. May be null.
* @param publicKey the public key. May be null.
* @param mode crypto context mode.
*/
public RsaWrappingCryptoContext(final MslContext ctx, final String id, final PrivateKey privateKey, final PublicKey publicKey, final Mode mode) {
super(id, privateKey, publicKey, NULL_OP, null, NULL_OP);
switch (mode) {
case WRAP_UNWRAP_OAEP:
wrapTransform = "RSA/ECB/OAEPPadding";
wrapParams = OAEPParameterSpec.DEFAULT;
break;
case WRAP_UNWRAP_PKCS1:
wrapTransform = "RSA/ECB/PKCS1Padding";
wrapParams = null;
break;
default:
throw new MslInternalException("RSA wrapping crypto context mode " + mode + " not supported.");
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.AsymmetricCryptoContext#wrap(byte[], com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
public byte[] wrap(final byte[] data, final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslCryptoException {
if (NULL_OP.equals(wrapTransform))
return data;
if (publicKey == null)
throw new MslCryptoException(MslError.WRAP_NOT_SUPPORTED, "no public key");
Throwable reset = null;
try {
// Encrypt plaintext.
final Cipher cipher = CryptoCache.getCipher(wrapTransform);
cipher.init(Cipher.ENCRYPT_MODE, publicKey, wrapParams);
return cipher.doFinal(data);
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_ILLEGAL_BLOCK_SIZE, "not expected when padding is specified", e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.PLAINTEXT_BAD_PADDING, "not expected when encrypting", e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(wrapTransform);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.crypto.AsymmetricCryptoContext#unwrap(byte[], com.netflix.msl.io.MslEncoderFactory)
*/
@Override
public byte[] unwrap(final byte[] data, final MslEncoderFactory encoder) throws MslCryptoException {
if (NULL_OP.equals(wrapTransform))
return data;
if (privateKey == null)
throw new MslCryptoException(MslError.DECRYPT_NOT_SUPPORTED, "no private key");
Throwable reset = null;
try {
// Decrypt ciphertext.
final Cipher cipher = CryptoCache.getCipher(wrapTransform);
cipher.init(Cipher.DECRYPT_MODE, privateKey, wrapParams);
return cipher.doFinal(data);
} catch (final NoSuchPaddingException e) {
reset = e;
throw new MslInternalException("Unsupported padding exception.", e);
} catch (final NoSuchAlgorithmException e) {
reset = e;
throw new MslInternalException("Invalid cipher algorithm specified.", e);
} catch (final InvalidKeyException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_PRIVATE_KEY, e);
} catch (final IllegalBlockSizeException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_ILLEGAL_BLOCK_SIZE, e);
} catch (final BadPaddingException e) {
reset = e;
throw new MslCryptoException(MslError.CIPHERTEXT_BAD_PADDING, e);
} catch (final InvalidAlgorithmParameterException e) {
reset = e;
throw new MslCryptoException(MslError.INVALID_ALGORITHM_PARAMS, e);
} catch (final RuntimeException e) {
reset = e;
throw e;
} finally {
// FIXME Remove this once BouncyCastle Cipher is fixed in v1.48+
if (reset != null)
CryptoCache.resetCipher(wrapTransform);
}
}
/** Wrap/unwrap transform. */
private final String wrapTransform;
/** Wrap/unwrap algorithm parameters. */
private final AlgorithmParameterSpec wrapParams;
}
/**
* <p>Asymmetric key wrapped key request data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "keypairid", "mechanism", "publickey" ],
* "keypairid" : "string",
* "mechanism" : "string",
* "publickey" : "binary"
* }} where:
* <ul>
* <li>{@code keypairid} identifies the key pair for wrapping and unwrapping the session keys</li>
* <li>{@code mechanism} the public key cryptographic mechanism of the key pair</li>
* <li>{@code publickey} the public key used to wrap the session keys</li>
* </ul></p>
*/
public static class RequestData extends KeyRequestData {
public enum Mechanism {
/** RSA-OAEP encrypt/decrypt */
RSA,
/** ECIES */
ECC,
/** JSON Web Encryption with RSA-OAEP */
JWE_RSA,
/** JSON Web Encryption JSON Serialization with RSA-OAEP */
JWEJS_RSA,
/** JSON Web Key with RSA-OAEP */
JWK_RSA,
/** JSON Web Key with RSA-PKCS v1.5 */
JWK_RSAES,
}
/** Key key pair ID. */
private static final String KEY_KEY_PAIR_ID = "keypairid";
/** Key mechanism. */
private static final String KEY_MECHANISM = "mechanism";
/** Key public key. */
private static final String KEY_PUBLIC_KEY = "publickey";
/**
* Create a new asymmetric key wrapped key request data instance with
* the specified key pair ID and public key. The private key is also
* required but is not included in the request data.
*
* @param keyPairId the public/private key pair ID.
* @param mechanism the key exchange mechanism.
* @param publicKey the public key.
* @param privateKey the private key.
*/
public RequestData(final String keyPairId, final Mechanism mechanism, final PublicKey publicKey, final PrivateKey privateKey) {
super(KeyExchangeScheme.ASYMMETRIC_WRAPPED);
this.keyPairId = keyPairId;
this.mechanism = mechanism;
this.publicKey = publicKey;
this.privateKey = privateKey;
}
/**
* Create a new asymmetric key wrapped key request data instance from
* the provided MSL object. The private key will be unknown.
*
* @param keyRequestMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslCryptoException if the encoded key is invalid or the
* specified mechanism is not supported.
* @throws MslKeyExchangeException if the specified mechanism is not
* recognized.
*/
public RequestData(final MslObject keyRequestMo) throws MslEncodingException, MslCryptoException, MslKeyExchangeException {
super(KeyExchangeScheme.ASYMMETRIC_WRAPPED);
final byte[] encodedKey;
try {
keyPairId = keyRequestMo.getString(KEY_KEY_PAIR_ID);
final String mechanismName = keyRequestMo.getString(KEY_MECHANISM);
try {
mechanism = Mechanism.valueOf(mechanismName);
} catch (final IllegalArgumentException e) {
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_MECHANISM, mechanismName, e);
}
encodedKey = keyRequestMo.getBytes(KEY_PUBLIC_KEY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyRequestMo, e);
}
try {
switch (mechanism) {
case RSA:
case JWE_RSA:
case JWEJS_RSA:
case JWK_RSA:
case JWK_RSAES:
{
final KeyFactory factory = CryptoCache.getKeyFactory("RSA");
final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
publicKey = factory.generatePublic(keySpec);
break;
}
/* Does not currently work.
case ECC:
{
final KeyFactory factory = CryptoCache.getKeyFactory("ECDSA");
final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
publicKey = factory.generatePublic(keySpec);
break;
}
*/
default:
throw new MslCryptoException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
} catch (final NullPointerException e) {
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, "keydata " + keyRequestMo.toString(), e);
} catch (final NoSuchAlgorithmException e) {
throw new MslCryptoException(MslError.UNSUPPORTED_KEYX_MECHANISM, "keydata " + keyRequestMo.toString(), e);
} catch (final InvalidKeySpecException e) {
throw new MslCryptoException(MslError.INVALID_PUBLIC_KEY, "keydata " + keyRequestMo.toString(), e);
}
privateKey = null;
}
/**
* @return the key pair ID.
*/
public String getKeyPairId() {
return keyPairId;
}
/**
* @return the key mechanism.
*/
public Mechanism getMechanism() {
return mechanism;
}
/**
* @return the public key.
*/
public PublicKey getPublicKey() {
return publicKey;
}
/**
* @return the private key.
*/
public PrivateKey getPrivateKey() {
return privateKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) {
final MslObject mo = encoder.createObject();
mo.put(KEY_KEY_PAIR_ID, keyPairId);
mo.put(KEY_MECHANISM, mechanism.name());
mo.put(KEY_PUBLIC_KEY, publicKey.getEncoded());
return mo;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof RequestData)) return false;
final RequestData that = (RequestData)obj;
// Private keys are optional but must be considered.
final boolean privateKeysEqual =
privateKey == that.privateKey ||
(privateKey != null && that.privateKey != null &&
Arrays.equals(privateKey.getEncoded(), that.privateKey.getEncoded()));
return super.equals(obj) &&
keyPairId.equals(that.keyPairId) &&
mechanism.equals(that.mechanism) &&
Arrays.equals(publicKey.getEncoded(), that.publicKey.getEncoded()) &&
privateKeysEqual;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
// Private keys are optional but must be considered.
final int privateKeyHashCode = (privateKey != null)
? Arrays.hashCode(privateKey.getEncoded()) : 0;
return super.hashCode() ^
keyPairId.hashCode() ^
mechanism.hashCode() ^
Arrays.hashCode(publicKey.getEncoded()) ^
privateKeyHashCode;
}
/** Public/private key pair ID. */
private final String keyPairId;
/** Key mechanism. */
private final Mechanism mechanism;
/** Public key. */
private final PublicKey publicKey;
/** Private key. */
private final PrivateKey privateKey;
}
/**
* <p>Asymmetric key wrapped key response data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "keypairid", "encryptionkey", "hmackey" ],
* "keypairid" : "string",
* "encryptionkey" : "binary",
* "hmackey" : "binary"
* }} where:
* <ul>
* <li>{@code keypairid} identifies the key pair for wrapping and unwrapping the session keys</li>
* <li>{@code encryptionkey} the wrapped session encryption key</li>
* <li>{@code hmackey} the wrapped session HMAC key</li>
* </ul></p>
*/
public static class ResponseData extends KeyResponseData {
/** Key key pair ID. */
private static final String KEY_KEY_PAIR_ID = "keypairid";
/** Key encrypted encryption key. */
private static final String KEY_ENCRYPTION_KEY = "encryptionkey";
/** Key encrypted HMAC key. */
private static final String KEY_HMAC_KEY = "hmackey";
/**
* Create a new asymmetric key wrapped key response data instance with
* the provided master token, specified key pair ID, and public
* key-encrypted encryption and HMAC keys.
*
* @param masterToken the master token.
* @param keyPairId the public/private key pair ID.
* @param encryptionKey the public key-encrypted encryption key.
* @param hmacKey the public key-encrypted HMAC key.
*/
public ResponseData(final MasterToken masterToken, final String keyPairId, final byte[] encryptionKey, final byte[] hmacKey) {
super(masterToken, KeyExchangeScheme.ASYMMETRIC_WRAPPED);
this.keyPairId = keyPairId;
this.encryptionKey = encryptionKey;
this.hmacKey = hmacKey;
}
/**
* Create a new asymmetric key wrapped key response data instance with
* the provided master token from the provided MSL object.
*
* @param masterToken the master token.
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if a session key is invalid.
*/
public ResponseData(final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
super(masterToken, KeyExchangeScheme.ASYMMETRIC_WRAPPED);
try {
keyPairId = keyDataMo.getString(KEY_KEY_PAIR_ID);
encryptionKey = keyDataMo.getBytes(KEY_ENCRYPTION_KEY);
hmacKey = keyDataMo.getBytes(KEY_HMAC_KEY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
}
}
/**
* @return the key pair ID.
*/
public String getKeyPairId() {
return keyPairId;
}
/**
* @return the public key-encrypted encryption key.
*/
public byte[] getEncryptionKey() {
return encryptionKey;
}
/**
* @return the public key-encrypted HMAC key.
*/
public byte[] getHmacKey() {
return hmacKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_KEY_PAIR_ID, keyPairId);
mo.put(KEY_ENCRYPTION_KEY, encryptionKey);
mo.put(KEY_HMAC_KEY, hmacKey);
return mo;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof ResponseData)) return false;
final ResponseData that = (ResponseData)obj;
return super.equals(obj) &&
keyPairId.equals(that.keyPairId) &&
Arrays.equals(encryptionKey, that.encryptionKey)&&
Arrays.equals(hmacKey, that.hmacKey);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ keyPairId.hashCode() ^ Arrays.hashCode(encryptionKey) ^ Arrays.hashCode(hmacKey);
}
/** Public/private key pair ID. */
private final String keyPairId;
/** Public key-encrypted encryption key. */
private final byte[] encryptionKey;
/** Public key-encrypted HMAC key. */
private final byte[] hmacKey;
}
/**
* Create the crypto context identified by the key ID, mechanism, and
* provided keys.
*
* @param ctx MSL context.
* @param keyPairId the key pair ID.
* @param mechanism the key mechanism.
* @param privateKey the private key. May be null.
* @param publicKey the public key. May be null.
* @return the crypto context.
* @throws MslCryptoException if the key mechanism is unsupported.
*/
private static ICryptoContext createCryptoContext(final MslContext ctx, final String keyPairId, final RequestData.Mechanism mechanism, final PrivateKey privateKey, final PublicKey publicKey) throws MslCryptoException {
switch (mechanism) {
case JWE_RSA:
{
final CekCryptoContext cryptoContext = new JsonWebEncryptionCryptoContext.RsaOaepCryptoContext(privateKey, publicKey);
return new JsonWebEncryptionCryptoContext(ctx, cryptoContext, JsonWebEncryptionCryptoContext.Encryption.A128GCM, Format.JWE_CS);
}
case JWEJS_RSA:
{
final CekCryptoContext cryptoContext = new JsonWebEncryptionCryptoContext.RsaOaepCryptoContext(privateKey, publicKey);
return new JsonWebEncryptionCryptoContext(ctx, cryptoContext, JsonWebEncryptionCryptoContext.Encryption.A128GCM, Format.JWE_JS);
}
case RSA:
case JWK_RSA:
{
return new RsaWrappingCryptoContext(ctx, keyPairId, privateKey, publicKey, RsaWrappingCryptoContext.Mode.WRAP_UNWRAP_OAEP);
}
case JWK_RSAES:
{
return new RsaWrappingCryptoContext(ctx, keyPairId, privateKey, publicKey, RsaWrappingCryptoContext.Mode.WRAP_UNWRAP_PKCS1);
}
default:
throw new MslCryptoException(MslError.UNSUPPORTED_KEYX_MECHANISM, mechanism.name());
}
}
/**
* Create a new asymmetric wrapped key exchange factory.
*
* @param authutils authentication utilities.
*/
public AsymmetricWrappedExchange(final AuthenticationUtils authutils) {
super(KeyExchangeScheme.ASYMMETRIC_WRAPPED);
this.authutils = authutils;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createRequestData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslCryptoException, MslKeyExchangeException {
return new RequestData(keyRequestMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createResponseData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
return new ResponseData(masterToken, keyDataMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslMasterTokenException, MslEncodingException, MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// If the master token was not issued by the local entity then we
// should not be generating a key response for it.
if (!masterToken.isVerified())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
// Verify the scheme is permitted.
final String identity = masterToken.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setMasterToken(masterToken);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey, hmacKey;
try {
encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.SESSION_KEY_CREATION_FAILURE, e).setMasterToken(masterToken);
}
// Wrap session keys with public key.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final String keyPairId = request.getKeyPairId();
final RequestData.Mechanism mechanism = request.getMechanism();
final PublicKey publicKey = request.getPublicKey();
final ICryptoContext wrapCryptoContext = createCryptoContext(ctx, keyPairId, mechanism, null, publicKey);
final byte[] wrappedEncryptionKey, wrappedHmacKey;
switch (mechanism) {
case JWE_RSA:
case JWEJS_RSA:
{
final JsonWebKey encryptionJwk = new JsonWebKey(Usage.enc, JsonWebKey.Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(Usage.sig, JsonWebKey.Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
break;
}
case JWK_RSA:
case JWK_RSAES:
{
final JsonWebKey encryptionJwk = new JsonWebKey(ENCRYPT_DECRYPT, JsonWebKey.Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(SIGN_VERIFY, JsonWebKey.Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
break;
}
default:
{
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacBytes, encoder, format);
break;
}
}
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.renewMasterToken(ctx, masterToken, encryptionKey, hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, request.getKeyPairId(), wrappedEncryptionKey, wrappedHmacKey);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final EntityAuthenticationData entityAuthData) throws MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = entityAuthData.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication scheme for entity not permitted " + identity + ":" + this.getScheme()).setEntityAuthenticationData(entityAuthData);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Wrap session keys with public key.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final String keyPairId = request.getKeyPairId();
final RequestData.Mechanism mechanism = request.getMechanism();
final PublicKey publicKey = request.getPublicKey();
final ICryptoContext wrapCryptoContext = createCryptoContext(ctx, keyPairId, mechanism, null, publicKey);
final byte[] wrappedEncryptionKey, wrappedHmacKey;
switch (mechanism) {
case JWE_RSA:
case JWEJS_RSA:
{
final JsonWebKey encryptionJwk = new JsonWebKey(Usage.enc, JsonWebKey.Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(Usage.sig, JsonWebKey.Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
break;
}
case JWK_RSA:
case JWK_RSAES:
{
final JsonWebKey encryptionJwk = new JsonWebKey(ENCRYPT_DECRYPT, JsonWebKey.Algorithm.A128CBC, false, null, encryptionKey);
final JsonWebKey hmacJwk = new JsonWebKey(SIGN_VERIFY, JsonWebKey.Algorithm.HS256, false, null, hmacKey);
final byte[] encryptionJwkBytes = encryptionJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
final byte[] hmacJwkBytes = hmacJwk.toMslEncoding(encoder, MslEncoderFormat.JSON);
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionJwkBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacJwkBytes, encoder, format);
break;
}
default:
{
wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionBytes, encoder, format);
wrappedHmacKey = wrapCryptoContext.wrap(hmacBytes, encoder, format);
break;
}
}
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken masterToken = tokenFactory.createMasterToken(ctx, entityAuthData, encryptionKey, hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext;
try {
cryptoContext = new SessionCryptoContext(ctx, masterToken);
} catch (final MslMasterTokenException e) {
throw new MslInternalException("Master token constructed by token factory is not trusted.", e);
}
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(masterToken, request.getKeyPairId(), wrappedEncryptionKey, wrappedHmacKey);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.keyx.KeyResponseData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
if (!(keyResponseData instanceof ResponseData))
throw new MslInternalException("Key response data " + keyResponseData.getClass().getName() + " was not created by this factory.");
final ResponseData response = (ResponseData)keyResponseData;
// Verify response matches request.
final String requestKeyPairId = request.getKeyPairId();
final String responseKeyPairId = response.getKeyPairId();
if (!requestKeyPairId.equals(responseKeyPairId))
throw new MslKeyExchangeException(MslError.KEYX_RESPONSE_REQUEST_MISMATCH, "request " + requestKeyPairId + "; response " + responseKeyPairId);
// Unwrap session keys with identified key.
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final PrivateKey privateKey = request.getPrivateKey();
if (privateKey == null)
throw new MslKeyExchangeException(MslError.KEYX_PRIVATE_KEY_MISSING, "request Asymmetric private key");
final RequestData.Mechanism mechanism = request.getMechanism();
final ICryptoContext unwrapCryptoContext = createCryptoContext(ctx, requestKeyPairId, mechanism, privateKey, null);
final SecretKey encryptionKey, hmacKey;
switch (mechanism) {
case JWE_RSA:
case JWEJS_RSA:
case JWK_RSA:
case JWK_RSAES:
{
final byte[] encryptionJwkBytes = unwrapCryptoContext.unwrap(response.getEncryptionKey(), encoder);
final byte[] hmacJwkBytes = unwrapCryptoContext.unwrap(response.getHmacKey(), encoder);
final MslObject encryptionJwkMo, hmacJwkMo;
try {
encryptionJwkMo = encoder.parseObject(encryptionJwkBytes);
hmacJwkMo = encoder.parseObject(hmacJwkBytes);
} catch (final MslEncoderException e) {
throw new MslCryptoException(MslError.SESSION_KEY_CREATION_FAILURE, e).setMasterToken(masterToken);
}
encryptionKey = new JsonWebKey(encryptionJwkMo).getSecretKey();
hmacKey = new JsonWebKey(hmacJwkMo).getSecretKey();
break;
}
default:
{
final byte[] unwrappedEncryptionKey = unwrapCryptoContext.unwrap(response.getEncryptionKey(), encoder);
final byte[] unwrappedHmacKey = unwrapCryptoContext.unwrap(response.getHmacKey(), encoder);
try {
encryptionKey = new SecretKeySpec(unwrappedEncryptionKey, JcaAlgorithm.AES);
hmacKey = new SecretKeySpec(unwrappedHmacKey, JcaAlgorithm.HMAC_SHA256);
} catch (final IllegalArgumentException e) {
throw new MslCryptoException(MslError.SESSION_KEY_CREATION_FAILURE, e).setMasterToken(masterToken);
}
break;
}
}
// Create crypto context.
final String identity = ctx.getEntityAuthenticationData(null).getIdentity();
final MasterToken responseMasterToken = response.getMasterToken();
return new SessionCryptoContext(ctx, responseMasterToken, identity, encryptionKey, hmacKey);
}
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 9,874 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/DiffieHellmanParameters.java | /**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.keyx;
import java.util.Map;
import javax.crypto.spec.DHParameterSpec;
import com.netflix.msl.MslKeyExchangeException;
/**
* Diffie-Hellman parameters by parameter ID.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public interface DiffieHellmanParameters {
/**
* @return the map of Diffie-Hellman parameters by parameter ID.
* @throws MslKeyExchangeException if there is an error accessing the
* parameters.
*/
public Map<String,DHParameterSpec> getParameterSpecs() throws MslKeyExchangeException;
/**
* Returns the Diffie-Hellman parameter specification identified by the
* parameters ID.
*
* @param id the parameters ID.
* @return the parameter specification or null if the parameters ID is
* not recognized.
* @throws MslKeyExchangeException if there is an error accessing the
* parameter specification.
*/
public DHParameterSpec getParameterSpec(final String id) throws MslKeyExchangeException;
}
| 9,875 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/KeyExchangeFactory.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.keyx;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.util.MslContext;
/**
* A key exchange factory creates key request and response data instances for
* a specific key exchange scheme.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class KeyExchangeFactory {
/**
* The key exchange data struct contains key response data and a crypto
* context for the exchanged keys.
*/
public static class KeyExchangeData {
/**
* Create a new key key exhange data struct with the provided key
* response data, master token, and crypto context.
*
* @param keyResponseData the key response data.
* @param cryptoContext the crypto context.
*/
public KeyExchangeData(final KeyResponseData keyResponseData, final ICryptoContext cryptoContext) {
this.keyResponseData = keyResponseData;
this.cryptoContext = cryptoContext;
}
/** Key response data. */
public final KeyResponseData keyResponseData;
/** Crypto context for the exchanged keys. */
public final ICryptoContext cryptoContext;
}
/**
* Create a new key exchange factory for the specified scheme.
*
* @param scheme the key exchange scheme.
*/
protected KeyExchangeFactory(final KeyExchangeScheme scheme) {
this.scheme = scheme;
}
/**
* @return the key exchange scheme this factory is for.
*/
public KeyExchangeScheme getScheme() {
return scheme;
}
/**
* Construct a new key request data instance from the provided MSL object.
*
* @param ctx MSL context.
* @param keyRequestMo the MSL object.
* @return the key request data.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if there is an error creating the key
* request data.
* @throws MslCryptoException if the keying material cannot be created.
*/
protected abstract KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslKeyExchangeException, MslCryptoException;
/**
* Construct a new key response data instance from the provided MSL object.
*
* @param ctx MSL context.
* @param masterToken the master token for the new key response data.
* @param keyDataMo the MSL object.
* @return the key response data.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if there is an error creating the key
* response data.
*/
protected abstract KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException;
/**
* <p>Generate a new key response data instance and crypto context in
* response to the provided key request data. The key request data will be
* from the the remote entity.</p>
*
* <p>The provided master token should be renewed by incrementing its
* sequence number but maintaining its serial number by using the MSL
* context's token factory.</p>
*
* @param ctx MSL context.
* @param format MSL encoder format.
* @param keyRequestData the key request data.
* @param masterToken the master token to renew.
* @return the key response data and crypto context or {@code null} if the
* factory chooses not to perform key exchange.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslEncodingException if there is an error parsing or encoding
* the data.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be.
* @throws MslEntityAuthException if there is a problem with the master
* token identity.
* @throws MslException if there is an error renewing the master token.
*/
public abstract KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException, MslException;
/**
* <p>Generate a new key response data instance and crypto context in
* response to the provided key request data and entity authentication
* data. The key request data will be from the the remote entity.</p>
*
* @param ctx MSL context.
* @param format MSL encoder format.
* @param keyRequestData the key request data.
* @param entityAuthData the entity authentication data.
* @return the key response data and crypto context or {@code null} if the
* factory chooses not to perform key exchange.
* @throws MslKeyExchangeException if there is an error with the key
* request data or the key response data cannot be created.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslEncodingException if there is an error parsing or encoding
* the data.
* @throws MslEntityAuthException if there is a problem with the entity
* identity.
* @throws MslException if there is an error creating the master token.
*/
public abstract KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final EntityAuthenticationData entityAuthData) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslEntityAuthException, MslException;
/**
* Create a crypto context from the provided key request data and key
* response data. The key request data will be from the local entity and
* the key response data from the remote entity.
*
* @param ctx MSL context.
* @param keyRequestData the key request data.
* @param keyResponseData the key response data.
* @param masterToken the current master token (not the one inside the key
* response data). May be null.
* @return the crypto context.
* @throws MslKeyExchangeException if there is an error with the key
* request data or key response data.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslMasterTokenException if the master token is not trusted and
* needs to be.
* @throws MslEntityAuthException if there is a problem with the master
* token identity.
*/
public abstract ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException;
/** The factory's key exchange scheme. */
private final KeyExchangeScheme scheme;
} | 9,876 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/SymmetricWrappedExchange.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.keyx;
import java.util.Arrays;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslEntityAuthException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMasterTokenException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.crypto.JcaAlgorithm;
import com.netflix.msl.crypto.SessionCryptoContext;
import com.netflix.msl.entityauth.EntityAuthenticationData;
import com.netflix.msl.entityauth.EntityAuthenticationFactory;
import com.netflix.msl.entityauth.EntityAuthenticationScheme;
import com.netflix.msl.entityauth.PresharedAuthenticationData;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.TokenFactory;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* <p>Symmetric key wrapped key exchange.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class SymmetricWrappedExchange extends KeyExchangeFactory {
/** Key ID. */
public enum KeyId {
PSK,
SESSION,
}
/**
* <p>Symmetric key wrapped key request data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "keyid" ],
* "keyid" : "string",
* }} where:
* <ul>
* <li>{@code keyid} identifies the key that should be used to wrap the session keys</li>
* </ul></p>
*/
public static class RequestData extends KeyRequestData {
/** Key symmetric key ID. */
private static final String KEY_KEY_ID = "keyid";
/**
* Create a new symmetric key wrapped key request data instance with
* the specified key ID.
*
* @param keyId symmetric key identifier.
*/
public RequestData(final KeyId keyId) {
super(KeyExchangeScheme.SYMMETRIC_WRAPPED);
this.keyId = keyId;
}
/**
* Create a new symmetric key wrapped key request data instance from
* the provided MSL object.
*
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the key ID is not recognized.
*/
public RequestData(final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
super(KeyExchangeScheme.SYMMETRIC_WRAPPED);
try {
final String keyIdName = keyDataMo.getString(KEY_KEY_ID);
try {
keyId = KeyId.valueOf(keyIdName);
} catch (final IllegalArgumentException e) {
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_KEY_ID, keyIdName, e);
}
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
}
}
/**
* @return the wrapping key ID.
*/
public KeyId getKeyId() {
return keyId;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyRequestData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException {
final MslObject mo = encoder.createObject();
mo.put(KEY_KEY_ID, keyId.name());
return mo;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof RequestData)) return false;
final RequestData that = (RequestData)obj;
return super.equals(obj) && keyId.equals(that.keyId);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ keyId.hashCode();
}
/** Symmetric key ID. */
private final KeyId keyId;
}
/**
* <p>Symmetric key wrapped key response data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "keyid", "encryptionkey", "hmackey" ],
* "keyid" : "string",
* "encryptionkey" : "binary",
* "hmackey" : "binary"
* }} where:
* <ul>
* <li>{@code keyid} identifies the key that was used to wrap the session keys</li>
* <li>{@code encryptionkey} the wrapped session encryption key</li>
* <li>{@code hmackey} the wrapped session HMAC key</li>
* </ul></p>
*/
public static class ResponseData extends KeyResponseData {
/** Key symmetric key ID. */
private static final String KEY_KEY_ID = "keyid";
/** Key wrapped encryption key. */
private static final String KEY_ENCRYPTION_KEY = "encryptionkey";
/** Key wrapped HMAC key. */
private static final String KEY_HMAC_KEY = "hmackey";
/**
* Create a new symmetric key wrapped key response data instance with
* the provided master token, specified key ID and wrapped encryption
* and HMAC keys.
*
* @param masterToken the master token.
* @param keyId the wrapping key ID.
* @param encryptionKey the wrapped encryption key.
* @param hmacKey the wrapped HMAC key.
*/
public ResponseData(final MasterToken masterToken, final KeyId keyId, final byte[] encryptionKey, final byte[] hmacKey) {
super(masterToken, KeyExchangeScheme.SYMMETRIC_WRAPPED);
this.keyId = keyId;
this.encryptionKey = encryptionKey;
this.hmacKey = hmacKey;
}
/**
* Create a new symmetric key wrapped key response data instance with
* the provided master token from the provided MSL object.
*
* @param masterToken the master token.
* @param keyDataMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
* @throws MslKeyExchangeException if the key ID is not recognized or
* a session key is invalid.
*/
public ResponseData(final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
super(masterToken, KeyExchangeScheme.SYMMETRIC_WRAPPED);
try {
final String keyIdName = keyDataMo.getString(KEY_KEY_ID);
try {
keyId = KeyId.valueOf(keyIdName);
} catch (final IllegalArgumentException e) {
throw new MslKeyExchangeException(MslError.UNIDENTIFIED_KEYX_KEY_ID, keyIdName, e);
}
encryptionKey = keyDataMo.getBytes(KEY_ENCRYPTION_KEY);
hmacKey = keyDataMo.getBytes(KEY_HMAC_KEY);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "keydata " + keyDataMo, e);
}
}
/**
* @return the wrapping key ID.
*/
public KeyId getKeyId() {
return keyId;
}
/**
* @return the wrapped encryption key.
*/
public byte[] getEncryptionKey() {
return encryptionKey;
}
/**
* @return the wrapped HMAC key.
*/
public byte[] getHmacKey() {
return hmacKey;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyResponseData#getKeydata(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)
*/
@Override
protected MslObject getKeydata(final MslEncoderFactory encoder, final MslEncoderFormat format) {
final MslObject mo = encoder.createObject();
mo.put(KEY_KEY_ID, keyId.name());
mo.put(KEY_ENCRYPTION_KEY, encryptionKey);
mo.put(KEY_HMAC_KEY, hmacKey);
return mo;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof ResponseData)) return false;
final ResponseData that = (ResponseData)obj;
return super.equals(obj) &&
keyId.equals(that.keyId) &&
Arrays.equals(encryptionKey, that.encryptionKey) &&
Arrays.equals(hmacKey, that.hmacKey);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^
keyId.hashCode() ^
Arrays.hashCode(encryptionKey) ^
Arrays.hashCode(hmacKey);
}
/** Symmetric key ID. */
private final KeyId keyId;
/** Wrapped encryption key. */
private final byte[] encryptionKey;
/** Wrapped HMAC key. */
private final byte[] hmacKey;
}
/**
* Create the crypto context identified by the key ID.
*
* @param ctx MSL context.
* @param keyId the key ID.
* @param masterToken the existing master token. May be null.
* @param identity the entity identity.
* @return the crypto context.
* @throws MslCryptoException if the crypto context cannot be created.
* @throws MslMasterTokenException if the master token is not trusted.
* @throws MslKeyExchangeException if the key ID is unsupported.
* @throws MslEntityAuthException if there is an problem with the entity
* identity.
*/
private static ICryptoContext createCryptoContext(final MslContext ctx, final KeyId keyId, final MasterToken masterToken, final String identity) throws MslCryptoException, MslKeyExchangeException, MslEntityAuthException, MslMasterTokenException {
switch (keyId) {
case SESSION:
{
// If the master token is null session wrapped is unsupported.
if (masterToken == null)
throw new MslKeyExchangeException(MslError.KEYX_MASTER_TOKEN_MISSING, keyId.name());
// Use a stored master token crypto context if we have one.
final ICryptoContext cachedCryptoContext = ctx.getMslStore().getCryptoContext(masterToken);
if (cachedCryptoContext != null)
return cachedCryptoContext;
// If there was no stored crypto context try making one from
// the master token. We can only do this if we can open up the
// master token.
if (!masterToken.isDecrypted())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken);
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, masterToken);
return cryptoContext;
}
case PSK:
{
final EntityAuthenticationData authdata = new PresharedAuthenticationData(identity);
final EntityAuthenticationFactory factory = ctx.getEntityAuthenticationFactory(EntityAuthenticationScheme.PSK);
if (factory == null)
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_KEY_ID, keyId.name());
return factory.getCryptoContext(ctx, authdata);
}
default:
throw new MslKeyExchangeException(MslError.UNSUPPORTED_KEYX_KEY_ID, keyId.name());
}
}
/**
* Create a new symmetric wrapped key exchange factory.
*
* @param authutils authentication utiliites.
*/
public SymmetricWrappedExchange(final AuthenticationUtils authutils) {
super(KeyExchangeScheme.SYMMETRIC_WRAPPED);
this.authutils = authutils;
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createRequestData(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyRequestData createRequestData(final MslContext ctx, final MslObject keyRequestMo) throws MslEncodingException, MslKeyExchangeException {
return new RequestData(keyRequestMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#createResponseData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject)
*/
@Override
protected KeyResponseData createResponseData(final MslContext ctx, final MasterToken masterToken, final MslObject keyDataMo) throws MslEncodingException, MslKeyExchangeException {
return new ResponseData(masterToken, keyDataMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final MasterToken masterToken) throws MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = masterToken.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication Scheme for Device Type Not Supported " + identity + ":" + this.getScheme()).setMasterToken(masterToken);
// If the master token was not issued by the local entity then we
// should not be generating a key response for it.
if (!masterToken.isVerified())
throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken).setMasterToken(masterToken);
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Wrap session keys with identified key...
final KeyId keyId = request.getKeyId();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final ICryptoContext wrapCryptoContext = createCryptoContext(ctx, keyId, masterToken, masterToken.getIdentity());
final byte[] wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionBytes, encoder, format);
final byte[] wrappedHmacKey = wrapCryptoContext.wrap(hmacBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken newMasterToken = tokenFactory.renewMasterToken(ctx, masterToken, encryptionKey, hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext = new SessionCryptoContext(ctx, newMasterToken);
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(newMasterToken, keyId, wrappedEncryptionKey, wrappedHmacKey);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#generateResponse(com.netflix.msl.util.MslContext, com.netflix.msl.io.MslEncoderFormat, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.entityauth.EntityAuthenticationData)
*/
@Override
public KeyExchangeData generateResponse(final MslContext ctx, final MslEncoderFormat format, final KeyRequestData keyRequestData, final EntityAuthenticationData entityAuthData) throws MslException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
// Verify the scheme is permitted.
final String identity = entityAuthData.getIdentity();
if (!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslKeyExchangeException(MslError.KEYX_INCORRECT_DATA, "Authentication Scheme for Device Type Not Supported " + identity + ":" + this.getScheme());
// Create random AES-128 encryption and SHA-256 HMAC keys.
final byte[] encryptionBytes = new byte[16];
final byte[] hmacBytes = new byte[32];
ctx.getRandom().nextBytes(encryptionBytes);
ctx.getRandom().nextBytes(hmacBytes);
final SecretKey encryptionKey = new SecretKeySpec(encryptionBytes, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(hmacBytes, JcaAlgorithm.HMAC_SHA256);
// Wrap session keys with identified key.
final KeyId keyId = request.getKeyId();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final ICryptoContext wrapCryptoContext;
try {
wrapCryptoContext = createCryptoContext(ctx, keyId, null, identity);
} catch (final MslMasterTokenException e) {
throw new MslInternalException("Master token exception thrown when the master token is null.", e);
}
final byte[] wrappedEncryptionKey = wrapCryptoContext.wrap(encryptionBytes, encoder, format);
final byte[] wrappedHmacKey = wrapCryptoContext.wrap(hmacBytes, encoder, format);
// Create the master token.
final TokenFactory tokenFactory = ctx.getTokenFactory();
final MasterToken masterToken = tokenFactory.createMasterToken(ctx, entityAuthData, encryptionKey, hmacKey, null);
// Create crypto context.
final ICryptoContext cryptoContext;
try {
cryptoContext = new SessionCryptoContext(ctx, masterToken);
} catch (final MslMasterTokenException e) {
throw new MslInternalException("Master token constructed by token factory is not trusted.", e);
}
// Return the key exchange data.
final KeyResponseData keyResponseData = new ResponseData(masterToken, keyId, wrappedEncryptionKey, wrappedHmacKey);
return new KeyExchangeData(keyResponseData, cryptoContext);
}
/* (non-Javadoc)
* @see com.netflix.msl.keyx.KeyExchangeFactory#getCryptoContext(com.netflix.msl.util.MslContext, com.netflix.msl.keyx.KeyRequestData, com.netflix.msl.keyx.KeyResponseData, com.netflix.msl.tokens.MasterToken)
*/
@Override
public ICryptoContext getCryptoContext(final MslContext ctx, final KeyRequestData keyRequestData, final KeyResponseData keyResponseData, final MasterToken masterToken) throws MslKeyExchangeException, MslCryptoException, MslEncodingException, MslMasterTokenException, MslEntityAuthException {
if (!(keyRequestData instanceof RequestData))
throw new MslInternalException("Key request data " + keyRequestData.getClass().getName() + " was not created by this factory.");
final RequestData request = (RequestData)keyRequestData;
if (!(keyResponseData instanceof ResponseData))
throw new MslInternalException("Key response data " + keyResponseData.getClass().getName() + " was not created by this factory.");
final ResponseData response = (ResponseData)keyResponseData;
// Verify response matches request.
final KeyId requestKeyId = request.getKeyId();
final KeyId responseKeyId = response.getKeyId();
if (!requestKeyId.equals(responseKeyId))
throw new MslKeyExchangeException(MslError.KEYX_RESPONSE_REQUEST_MISMATCH, "request " + requestKeyId + "; response " + responseKeyId).setMasterToken(masterToken);
// Unwrap session keys with identified key.
final EntityAuthenticationData entityAuthData = ctx.getEntityAuthenticationData(null);
final String identity = entityAuthData.getIdentity();
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final ICryptoContext unwrapCryptoContext = createCryptoContext(ctx, responseKeyId, masterToken, identity);
final byte[] unwrappedEncryptionKey = unwrapCryptoContext.unwrap(response.getEncryptionKey(), encoder);
final byte[] unwrappedHmacKey = unwrapCryptoContext.unwrap(response.getHmacKey(), encoder);
// Create crypto context.
final SecretKey encryptionKey = new SecretKeySpec(unwrappedEncryptionKey, JcaAlgorithm.AES);
final SecretKey hmacKey = new SecretKeySpec(unwrappedHmacKey, JcaAlgorithm.HMAC_SHA256);
final MasterToken responseMasterToken = response.getMasterToken();
return new SessionCryptoContext(ctx, responseMasterToken, identity, encryptionKey, hmacKey);
}
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 9,877 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/keyx/WrapCryptoContextRepository.java | /**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.keyx;
import com.netflix.msl.crypto.ICryptoContext;
/**
* <p>The wrap crypto context repository provides access to wrapping key crypto
* contexts and is used by key exchange factories that make use of intermediate
* wrapping keys to deliver new wrapping key data to the application. The
* wrapping key data and its corresponding crypto context can then be used in
* future key request data.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public interface WrapCryptoContextRepository {
/**
* Add a new wrapping key crypto context and wrap data. The wrap data
* should be used in key request data to request a new wrapping key
* wrapped with this wrapping key.
*
* @param wrapdata wrapping key wrap data.
* @param cryptoContext wrapping key crypto context.
*/
public void addCryptoContext(final byte[] wrapdata, final ICryptoContext cryptoContext);
/**
* Return the wrapping key crypto context identified by the specified
* wrap data.
*
* @param wrapdata wrapping key wrap data.
* @return the wrapping key crypto context or null if none exists.
*/
public ICryptoContext getCryptoContext(final byte[] wrapdata);
/**
* Remove the wrapping key crypto context identified by the specified
* key wrap data. This is called after calling
* {@link #addCryptoContext(byte[], ICryptoContext)} to
* indicate the old wrapping crypto context should no longer be
* necessary.
*
* @param wrapdata wrapping key wrap data.
*/
public void removeCryptoContext(final byte[] wrapdata);
}
| 9,878 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslEncoderException.java | /**
* Copyright (c) 2015-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
/**
* <p>A MSL encoder exception is thrown by the MSL encoding abstraction classes
* when there is a problem.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslEncoderException extends Exception {
private static final long serialVersionUID = -6338714624096298489L;
/**
* <p>Construct a new MSL encoder exception with the provided message.</p>
*
* @param message the detail message.
*/
public MslEncoderException(final String message) {
super(message);
}
/**
* <p>Construct a new MSL encoder exception with the provided cause.</p>
*
* @param cause the cause of the exception.
*/
public MslEncoderException(final Throwable cause) {
super(cause);
}
/**
* <p>Construct a new MSL encoder exception with the provided message and
* cause.</p>
*
* @param message the detail message.
* @param cause the cause of the exception.
*/
public MslEncoderException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 9,879 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslEncoderFactory.java | /**
* Copyright (c) 2015-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.util.Base64;
/**
* <p>An abstract factory class for producing {@link MslTokenizer},
* {@link MslObject}, and {@link MslArray} instances of various encoder
* formats.</p>
*
* <p>A concrete implementations must identify its supported and preferred
* encoder formats and provide implementations for encoding and decoding those
* formats.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class MslEncoderFactory {
/**
* <p>Escape and quote a string for print purposes.</p>
*
* <p>This is based on the org.json {@code MslObject.quote()} code.</p>
*
* @param string the string to quote. May be {@code null}.
* @return the quoted string.
*/
static String quote(final String string) {
final StringBuilder sb = new StringBuilder();
// Return "" for null or zero-length string.
if (string == null || string.length() == 0) {
sb.append("\"\"");
return sb.toString();
}
char c = 0;
final int len = string.length();
sb.append('"');
for (int i = 0; i < len; i += 1) {
final char b = c;
c = string.charAt(i);
switch (c) {
case '\\':
case '"':
sb.append('\\');
sb.append(c);
break;
case '/':
if (b == '<') {
sb.append('\\');
}
sb.append(c);
break;
case '\b':
sb.append("\\b");
break;
case '\t':
sb.append("\\t");
break;
case '\n':
sb.append("\\n");
break;
case '\f':
sb.append("\\f");
break;
case '\r':
sb.append("\\r");
break;
default:
if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
|| (c >= '\u2000' && c < '\u2100'))
{
sb.append("\\u");
final String hhhh = Integer.toHexString(c);
sb.append("0000", 0, 4 - hhhh.length());
sb.append(hhhh);
} else {
sb.append(c);
}
}
}
sb.append('"');
return sb.toString();
}
/**
* <p>Convert a value to a string for print purposes.</p>
*
* <p>This is based on the org.json {@code MslObject.writeValue()} code.</p>
*
* @param value the value to convert to a string. May be {@code null}.
* @return the string.
*/
@SuppressWarnings("unchecked")
static String stringify(final Object value) {
if (value == null || value.equals(null)) {
return "null";
} else if (value instanceof MslObject || value instanceof MslArray) {
return value.toString();
} else if (value instanceof Map) {
return new MslObject((Map<?,?>)value).toString();
} else if (value instanceof Collection) {
return new MslArray((Collection<Object>)value).toString();
} else if (value instanceof Object[]) {
return new MslArray((Object[])value).toString();
} else if (value instanceof Number || value instanceof Boolean) {
return value.toString();
} else if (value instanceof byte[]) {
return Base64.encode((byte[])value);
} else {
return quote(value.toString());
}
}
/**
* Returns the most preferred encoder format from the provided set of
* formats.
*
* @param formats the set of formats to choose from. May be {@code null} or
* empty.
* @return the preferred format from the provided set or the default format
* if format set is {@code null} or empty.
*/
public abstract MslEncoderFormat getPreferredFormat(final Set<MslEncoderFormat> formats);
/**
* Create a new {@link MslTokenizer}. The encoder format will be
* determined by inspecting the byte stream identifier located in the first
* byte.
*
* @param source the binary data to tokenize.
* @return the {@link MslTokenizer}.
* @throws IOException if there is a problem reading the byte stream
* identifier.
* @throws MslEncoderException if the encoder format is not recognized or
* is not supported.
*/
public MslTokenizer createTokenizer(final InputStream source) throws IOException, MslEncoderException {
// Read the byte stream identifier (and only the identifier).
final InputStream bufferedSource = source.markSupported() ? source : new UnsynchronizedBufferedInputStream(source);
bufferedSource.mark(1);
final byte id = (byte)bufferedSource.read();
if (id == -1)
throw new MslEncoderException("End of stream reached when attempting to read the byte stream identifier.");
// Identify the encoder format.
final MslEncoderFormat format = MslEncoderFormat.getFormat(id);
if (format == null)
throw new MslEncoderException("Unidentified encoder format ID: (byte)" + id + ".");
// Reset the input stream and return the tokenizer.
bufferedSource.reset();
return generateTokenizer(bufferedSource, format);
}
/**
* Create a new {@link MslTokenizer} of the specified encoder format.
*
* @param source the binary data to tokenize.
* @param format the encoder format.
* @return the {@link MslTokenizer}.
* @throws MslEncoderException if the encoder format is not supported.
*/
protected abstract MslTokenizer generateTokenizer(final InputStream source, final MslEncoderFormat format) throws MslEncoderException;
/**
* Create a new {@link MslObject}.
*
* @return the {@link MslObject}.
*/
public MslObject createObject() {
return createObject(null);
}
/**
* Create a new {@link MslObject} populated with the provided map.
*
* @param map the map of name/value pairs. This must be a map of
* {@code String}s onto {@code Object}s. May be {@code null}.
* @return the {@link MslObject}.
* @throws IllegalArgumentException if one of the values is of an
* unsupported type.
*/
public MslObject createObject(final Map<String,Object> map) {
return new MslObject(map);
}
/**
* Identify the encoder format of the {@link MslObject} of the encoded
* data. The format will be identified by inspecting the byte stream
* identifier located in the first byte.
*
* @param encoding the encoded data.
* @return the encoder format.
* @throws MslEncoderException if the encoder format cannot be identified
* or there is an error parsing the encoder format ID.
*/
public MslEncoderFormat parseFormat(final byte[] encoding) throws MslEncoderException {
// Fail if the encoding is too short.
if (encoding.length < 1)
throw new MslEncoderException("No encoding identifier found.");
// Identify the encoder format.
final byte id = encoding[0];
final MslEncoderFormat format = MslEncoderFormat.getFormat(id);
if (format == null)
throw new MslEncoderException("Unidentified encoder format ID: (byte)" + id + ".");
return format;
}
/**
* Parse a {@link MslObject} from encoded data. The encoder format will be
* determined by inspecting the byte stream identifier located in the first
* byte.
*
* @param encoding the encoded data to parse.
* @return the {@link MslObject}.
* @throws MslEncoderException if the encoder format is not supported or
* there is an error parsing the encoded data.
*/
public abstract MslObject parseObject(final byte[] encoding) throws MslEncoderException;
/**
* Encode a {@link MslObject} into the specified encoder format.
*
* @param object the {@link MslObject} to encode.
* @param format the encoder format.
* @return the encoded data.
* @throws MslEncoderException if the encoder format is not supported or
* there is an error encoding the object.
*/
public abstract byte[] encodeObject(final MslObject object, final MslEncoderFormat format) throws MslEncoderException;
/**
* Create a new {@link MslArray}.
*
* @return the {@link MslArray}.
*/
public MslArray createArray() {
return createArray(null);
}
/**
* Create a new {@link MslArray} populated with the provided values.
*
* @param collection the collection of values. May be {@code null}.
* @return the {@link MslArray}.
* @throws IllegalArgumentException if one of the values is of an
* unsupported type.
*/
public MslArray createArray(final Collection<?> collection) {
return new MslArray(collection);
}
}
| 9,880 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/JsonMslObject.java | /**
* Copyright (c) 2015-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.nio.charset.Charset;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.util.Base64;
/**
* <p>A {@code MslObject} that encodes its data as UTF-8 JSON.</p>
*
* <p>This implementation is backed by {@code org.json}.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class JsonMslObject extends MslObject implements JSONString {
/** UTF-8 charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/**
* Returns a JSON MSL encoding of provided MSL object.
*
* @param encoder the encoder factory.
* @param object the MSL object.
* @return the encoded data.
* @throws MslEncoderException if there is an error encoding the data.
*/
public static byte[] getEncoded(final MslEncoderFactory encoder, final MslObject object) throws MslEncoderException {
if (object instanceof JsonMslObject)
return ((JsonMslObject)object).toJSONString().getBytes(UTF_8);
final JsonMslObject jsonObject = new JsonMslObject(encoder, object);
return jsonObject.toJSONString().getBytes(UTF_8);
}
/**
* Create a new {@code JsonMslObject} from the given {@code MslObject}.
*
* @param encoder the encoder factory.
* @param o the {@code MslObject}.
* @throws MslEncoderException if the MSL object contains an unsupported
* type.
*/
public JsonMslObject(final MslEncoderFactory encoder, final MslObject o) throws MslEncoderException {
this.encoder = encoder;
try {
for (final String key : o.getKeys())
put(key, o.opt(key));
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL object encoding.", e);
}
}
/**
* Create a new {@code JsonMslObject} from the given {@code JSONObject}.
*
* @param encoder the encoder factory.
* @param jo the {@code JSONObject}.
* @throws MslEncoderException if the JSON object contains an unsupported
* type.
*/
public JsonMslObject(final MslEncoderFactory encoder, final JSONObject jo) throws MslEncoderException {
this.encoder = encoder;
try {
for (final Object key : jo.keySet()) {
if (!(key instanceof String))
throw new MslEncoderException("Invalid JSON object encoding.");
put((String)key, jo.opt((String)key));
}
} catch (final JSONException e) {
throw new MslEncoderException("Invalid JSON object encoding.", e);
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL object encoding.", e);
}
}
/**
* Create a new {@code JsonMslObject} from its encoded representation.
*
* @param encoder the encoder factory.
* @param encoding the encoded data.
* @throws MslEncoderException if the data is malformed or invalid.
*/
public JsonMslObject(final MslEncoderFactory encoder, final byte[] encoding) throws MslEncoderException {
this.encoder = encoder;
try {
final String json = new String(encoding, UTF_8);
final JSONObject jo = new JSONObject(json);
for (final Object key : jo.keySet()) {
if (!(key instanceof String))
throw new MslEncoderException("Invalid JSON object encoding.");
put((String)key, jo.opt((String)key));
}
} catch (final JSONException e) {
throw new MslEncoderException("Invalid JSON object encoding.", e);
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL object encoding.", e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslObject#put(java.lang.String, java.lang.Object)
*/
@Override
public MslObject put(final String key, final Object value) {
final Object o;
try {
// Convert JSONObject to MslObject.
if (value instanceof JSONObject)
o = new JsonMslObject(encoder, (JSONObject)value);
// Convert JSONArray to a MslArray.
else if (value instanceof JSONArray)
o = new JsonMslArray(encoder, (JSONArray)value);
// All other types are OK as-is.
else
o = value;
} catch (final MslEncoderException e) {
throw new IllegalArgumentException("Unsupported JSON object or array representation.", e);
}
return super.put(key, o);
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslObject#getBytes(java.lang.String)
*/
@Override
public byte[] getBytes(final String key) throws MslEncoderException {
// When a JsonMslObject is decoded, there's no way for us to know if a
// value is supposed to be a String to byte[]. Therefore interpret
// Strings as Base64-encoded data consistent with the toJSONString()
// and getEncoded().
final Object value = get(key);
if (value instanceof byte[])
return (byte[])value;
if (value instanceof String) {
try {
return Base64.decode((String)value);
} catch (final IllegalArgumentException e) {
// Fall through.
}
}
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not binary data.");
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslObject#optBytes(java.lang.String)
*/
@Override
public byte[] optBytes(final String key) {
return optBytes(key, new byte[0]);
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslObject#optBytes(java.lang.String, byte[])
*/
@Override
public byte[] optBytes(final String key, final byte[] defaultValue) {
// When a JsonMslObject is decoded, there's no way for us to know if a
// value is supposed to be a String to byte[]. Therefore interpret
// Strings as Base64-encoded data consistent with the toJSONString()
// and getEncoded().
final Object value = opt(key);
if (value instanceof byte[])
return (byte[])value;
if (value instanceof String) {
try {
return Base64.decode((String)value);
} catch (final IllegalArgumentException e) {
// Fall through.
}
}
return defaultValue;
}
/* (non-Javadoc)
* @see org.json.JSONString#toJSONString()
*/
@Override
public String toJSONString() {
try {
final JSONObject jo = new JSONObject();
final Set<String> keys = getKeys();
for (final String key : keys) {
final Object value = opt(key);
if (value instanceof byte[]) {
jo.put(key, Base64.encode((byte[])value));
} else if (value instanceof JsonMslObject || value instanceof JsonMslArray) {
jo.put(key, value);
} else if (value instanceof MslObject) {
final JsonMslObject jsonValue = new JsonMslObject(encoder, (MslObject)value);
jo.put(key, jsonValue);
} else if (value instanceof MslArray) {
final JsonMslArray jsonValue = new JsonMslArray(encoder, (MslArray)value);
jo.put(key, jsonValue);
} else if (value instanceof MslEncodable) {
final byte[] json = ((MslEncodable)value).toMslEncoding(encoder, MslEncoderFormat.JSON);
final JsonMslObject jsonValue = new JsonMslObject(encoder, json);
jo.put(key, jsonValue);
} else {
jo.put(key, value);
}
}
return jo.toString();
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
} catch (final MslEncoderException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
} catch (final JSONException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslObject#toString()
*/
@Override
public String toString() {
return toJSONString();
}
/** MSL encoder factory. */
private final MslEncoderFactory encoder;
}
| 9,881 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/ThriftyUtf8Reader.java | /**
* Copyright (c) 2017-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
/**
* <p>A specialized UTF-8 reader that only reads exactly the number of bytes
* necessary to decode the character, and does not close the underlying input
* stream. This ensures any unneeded bytes remain on the input stream, which
* can then be reused.</p>
*
* <p>Based on Andy Clark's
* {@code com.sun.org.apache.xerces.internal.impl.io.UTF8Reader}.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class ThriftyUtf8Reader extends Reader {
/** Default byte buffer size (8192). */
public static final int DEFAULT_BUFFER_SIZE = 16384;
/** Malformed replacement character. */
public static final char MALFORMED_CHAR = 0xFFFD;
/** Input stream. */
private final InputStream fInputStream;
/** Byte buffer. */
private final byte[] fBuffer = new byte[DEFAULT_BUFFER_SIZE];
/** Current buffer read position. */
private int fIndex = 0;
/** Number of valid bytes in the buffer. */
private int fOffset = 0;
/** Pending character. */
private int fPending = -1;
/** Surrogate character. */
private int fSurrogate = -1;
/**
* Create a new thrifty UTF-8 reader that will read data off the provided
* input stream.
*
* @param inputStream the underlying input stream.
*/
public ThriftyUtf8Reader(final InputStream inputStream) {
fInputStream = inputStream;
}
@Override
public int read() throws IOException {
// Return any surrogate.
if (fSurrogate != -1) {
final int c = fSurrogate;
fSurrogate = -1;
return c;
}
// Read the first byte or use the pending character.
final int b0;
if (fPending != -1) {
b0 = fPending;
fPending = -1;
} else {
b0 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b0 == -1)
return -1;
}
// UTF-8: [0xxx xxxx]
// Unicode: [0000 0000] [0xxx xxxx]
if (b0 < 0x80)
return (char)b0;
// UTF-8: [110y yyyy] [10xx xxxx]
// Unicode: [0000 0yyy] [yyxx xxxx]
if ((b0 & 0xE0) == 0xC0) {
final int b1 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b1 == -1)
return MALFORMED_CHAR;
if ((b1 & 0xC0) != 0x80) {
fPending = b1;
return MALFORMED_CHAR;
}
// Make sure the decoded value is not below the first code point of
// a 2-byte sequence.
if ((b0 & 0x1E) == 0)
return MALFORMED_CHAR;
return ((b0 << 6) & 0x07C0) | (b1 & 0x003F);
}
// UTF-8: [1110 zzzz] [10yy yyyy] [10xx xxxx]
// Unicode: [zzzz yyyy] [yyxx xxxx]
if ((b0 & 0xF0) == 0xE0) {
final int b1 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b1 == -1)
return MALFORMED_CHAR;
if ((b1 & 0xC0) != 0x80) {
fPending = b1;
return MALFORMED_CHAR;
}
final int b2 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b2 == -1)
return MALFORMED_CHAR;
if ((b2 & 0xC0) != 0x80) {
fPending = b2;
return MALFORMED_CHAR;
}
// Make sure the decoded value is not:
//
// 1. A surrogate character (0xD800 - 0xDFFF).
// 2. Below the first code point of a 3-byte sequence.
// 3. Equal to 0xFFFE or 0xFFFF.
if ((b0 == 0xED && b1 >= 0xA0)
|| ((b0 & 0x0F) == 0 && (b1 & 0x20) == 0)
|| (b0 == 0xEF && (b1 & 0x3F) == 0x3F && (b2 & 0x3E) == 0x3E))
{
return MALFORMED_CHAR;
}
return ((b0 << 12) & 0xF000) | ((b1 << 6) & 0x0FC0) | (b2 & 0x003F);
}
// UTF-8: [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]*
// Unicode: [1101 10ww] [wwzz zzyy] (high surrogate)
// [1101 11yy] [yyxx xxxx] (low surrogate)
// * uuuuu = wwww + 1
if ((b0 & 0xF8) == 0xF0) {
final int b1 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b1 == -1)
return MALFORMED_CHAR;
if ((b1 & 0xC0) != 0x80) {
fPending = b1;
return MALFORMED_CHAR;
}
final int b2 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b2 == -1)
return MALFORMED_CHAR;
if ((b2 & 0xC0) != 0x80) {
fPending = b2;
return MALFORMED_CHAR;
}
final int b3 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b3 == -1)
return MALFORMED_CHAR;
if ((b3 & 0xC0) != 0x80) {
fPending = b3;
return MALFORMED_CHAR;
}
// Make sure the decoded value is not below the first code point of
// a 4-byte sequence.
if ((b0 & 0x07) == 0 && (b1 & 0x30) == 0)
return MALFORMED_CHAR;
final int uuuuu = ((b0 << 2) & 0x001C) | ((b1 >> 4) & 0x0003);
// Make sure the decoded value is not above the Unicode plane 0x10.
if (uuuuu > 0x10)
return MALFORMED_CHAR;
final int wwww = uuuuu - 1;
final int hs = 0xD800 |
((wwww << 6) & 0x03C0) | ((b1 << 2) & 0x003C) |
((b2 >> 4) & 0x0003);
final int ls = 0xDC00 | ((b2 << 6) & 0x03C0) | (b3 & 0x003F);
fSurrogate = ls;
return hs;
}
// UTF-8: [1111 10uu] [10uu zzzz] [10yy yyyy] [10xx xxxx] [10ww wwww]
// Unicode: invalid
if ((b0 & 0xFC) == 0xF8) {
final int b1 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b1 == -1)
return MALFORMED_CHAR;
if ((b1 & 0xC0) != 0x80) {
fPending = b1;
return MALFORMED_CHAR;
}
final int b2 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b2 == -1)
return MALFORMED_CHAR;
if ((b2 & 0xC0) != 0x80) {
fPending = b2;
return MALFORMED_CHAR;
}
final int b3 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b3 == -1)
return MALFORMED_CHAR;
if ((b3 & 0xC0) != 0x80) {
fPending = b3;
return MALFORMED_CHAR;
}
final int b4 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b4 == -1)
return MALFORMED_CHAR;
if ((b4 & 0xC0) != 0x80) {
fPending = b4;
return MALFORMED_CHAR;
}
return MALFORMED_CHAR;
}
// UTF-8: [1111 110u] [10uu zzzz] [10yy yyyy] [10xx xxxx] [10ww wwww] [10vv vvvv]
// Unicode: invalid
if ((b0 & 0xFE) == 0xFC) {
final int b1 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b1 == -1)
return MALFORMED_CHAR;
if ((b1 & 0xC0) != 0x80) {
fPending = b1;
return MALFORMED_CHAR;
}
final int b2 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b2 == -1)
return MALFORMED_CHAR;
if ((b2 & 0xC0) != 0x80) {
fPending = b2;
return MALFORMED_CHAR;
}
final int b3 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b3 == -1)
return MALFORMED_CHAR;
if ((b3 & 0xC0) != 0x80) {
fPending = b3;
return MALFORMED_CHAR;
}
final int b4 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b4 == -1)
return MALFORMED_CHAR;
if ((b4 & 0xC0) != 0x80) {
fPending = b4;
return MALFORMED_CHAR;
}
final int b5 = (fIndex == fOffset) ? fInputStream.read() : fBuffer[fIndex++] & 0x00FF;
if (b5 == -1)
return MALFORMED_CHAR;
if ((b5 & 0xC0) != 0x80) {
fPending = b5;
return MALFORMED_CHAR;
}
return MALFORMED_CHAR;
}
// Error.
return MALFORMED_CHAR;
}
@Override
public int read(final char ch[], int offset, int length) throws IOException {
int numRead = 0;
// Start with any surrogate.
if (fSurrogate != -1) {
ch[offset++] = (char)fSurrogate;
fSurrogate = -1;
--length;
++numRead;
}
// If there are no available bytes in the buffer...
if (fIndex >= fOffset) {
// Read at most buffer size bytes.
if (length > fBuffer.length)
length = fBuffer.length;
final int count = fInputStream.read(fBuffer, 0, length);
// If we could not read anymore, return the number of characters
// read so far or end-of-stream.
if (count == -1)
return (numRead > 0) ? numRead : -1;
// Start reading from the beginning of the buffer, up to the number
// of valid bytes.
fIndex = 0;
fOffset = count;
}
// Read bytes (out of the buffer) until the buffer is empty or we have
// all of the characters requested.
while (fIndex < fOffset && numRead < length) {
final int c = read();
// If we could not read anymore, return the number of characters
// read so far or end-of-stream.
if (c == -1)
return (numRead > 0) ? numRead : -1;
// Populate the character array.
ch[offset++] = (char)c;
++numRead;
}
// To avoid recursing forever or from blocking too long, return with
// what we have so far.
return numRead;
}
@Override
public long skip(final long n) throws IOException {
// Don't pass skip down to the backing input stream since we're being
// asked to skip characters and not bytes.
long remaining = n;
final char[] ch = new char[fBuffer.length];
do {
final int length = ch.length < remaining ? ch.length : (int)remaining;
final int count = read(ch, 0, length);
if (count > 0)
remaining -= count;
else
break;
} while (remaining > 0);
final long skipped = n - remaining;
return skipped;
}
/**
* Tell whether this stream supports the mark() operation.
*/
@Override
public boolean markSupported() {
return fInputStream.markSupported();
}
@Override
public void mark(final int readLimit) throws IOException {
// This is complicated because the read limit is in characters but the
// backing input stream is in bytes. If we really want to be safe then
// we need to multiply by the maximum number of bytes per character.
// Account for overflow.
final long byteLimit = 6 * readLimit;
final int safeLimit = (byteLimit < 0 || byteLimit > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int)byteLimit;
fInputStream.mark(safeLimit);
}
@Override
public void reset() throws IOException {
fOffset = 0;
fSurrogate = -1;
fInputStream.reset();
}
@Override
public void close() {
// Explicitly do not close the backing input stream for our use case.
// This is because we are using ThriftyUtf8Reader inside a stream
// parser.
}
}
| 9,882 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/Url.java | /**
* Copyright (c) 2012-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The URL interface provides access to an input stream and output stream tied
* to a specific URL.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public interface Url {
/**
* The Connection interface represents a communication link between the
* application and a URL.
*/
public static interface Connection {
/**
* <p>Returns an input stream that reads from this connection.</p>
*
* <p>Asking for the input stream must not prevent use of the output
* stream, but reading from the input stream may prevent further
* writing to the output stream.</p>
*
* <p>The returned input stream must support
* {@link InputStream#mark(int)}, {@link InputStream#reset()}, and
* {@link InputStream#skip(long)} if you wish to use it for more than
* one MSL message.</p>
*
* @return an input stream that reads from this connection.
* @throws IOException if an I/O error occurs while creating the input
* stream.
*/
public InputStream getInputStream() throws IOException;
/**
* <p>Returns an output stream that writes to this connection.</p>
*
* <p>Asking for the output stream must not prevent use of the input
* stream, but writing to the output stream may prevent further reading
* from the input stream.</p>
*
* @return an output stream that writes to this connection.
* @throws IOException if an I/O error occurs while creating the output
* stream.
*/
public OutputStream getOutputStream() throws IOException;
}
/**
* Set the timeout.
*
* @param timeout connect/read/write timeout in milliseconds.
*/
public void setTimeout(final int timeout);
/**
* Open a new connection to the target location.
*
* @return a {@link Connection} linking to the URL.
* @throws IOException if an I/O exception occurs.
*/
public Connection openConnection() throws IOException;
}
| 9,883 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/LZWInputStream.java | /**
* Copyright (c) 2013-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* <p>This class implements a stream filter for reading compressed data in the
* LZW format.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class LZWInputStream extends InputStream {
/** Maximum number of values represented by a byte. */
private static final int BYTE_RANGE = 256;
/** The initial dictionary. */
private static final Map<Integer,byte[]> INITIAL_DICTIONARY = new HashMap<Integer,byte[]>(BYTE_RANGE);
static {
for (int i = 0; i < BYTE_RANGE; ++i) {
byte[] data = { (byte)i };
INITIAL_DICTIONARY.put(i, data);
}
}
/**
* Creates a new input stream.
*
* @param in the input stream.
*/
public LZWInputStream(final InputStream in) {
this.in = in;
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
/* (non-Javadoc)
* @see java.io.InputStream#close()
*/
@Override
public void close() throws IOException {
if (!closed) {
closed = true;
in.close();
}
}
/* (non-Javadoc)
* @see java.io.InputStream#read()
*/
@Override
public int read() throws IOException {
if (closed)
throw new IOException("Input stream is closed.");
// Grab another byte if we need one. Check for end of stream.
if (buffer.size() == 0) {
final byte[] b = new byte[1];
int available = decompress(b, 0, 1);
if (available == -1)
return -1;
return b[0];
}
// Return the next byte.
return buffer.remove();
}
/* (non-Javadoc)
* @see java.io.InputStream#read(byte[], int, int)
*/
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
if (closed)
throw new IOException("Input stream is closed.");
if (off > 0)
throw new IndexOutOfBoundsException("Specified offset cannot be negative.");
if (len < 0)
throw new IndexOutOfBoundsException("Specified length cannot be negative.");
if (len > b.length - off)
throw new IndexOutOfBoundsException("Requested length exceeds buffer size at offset.");
// Copy as many bytes as we have buffered.
int offset = off;
int needed = len;
while (needed > 0 && buffer.size() > 0) {
b[offset++] = buffer.remove();
--needed;
}
// If we don't need any more then we're done.
if (needed == 0)
return len;
// Grab any more bytes that we need. Check for end of stream.
int read = decompress(b, offset, needed);
if (read == -1) {
if (needed == len)
return -1;
return len - needed;
}
needed -= read;
// Return the number of bytes we read.
return len - needed;
}
/**
* Reads compressed data from the underlying input stream and decompresses
* the codes to the original data.
*
* @param b the buffer into which the data is read.
* @param off the start offset in array b at which the data is written.
* @param len the maximum number of bytes to read.
* @return the number of bytes decoded into the buffer.
* @throws IOException if there is an error reading from the code stream.
*/
private int decompress(final byte[] b, final int off, final int len) throws IOException {
int totalRead = 0;
while (totalRead < len) {
// The number of bytes we need is equal to the number of bits we
// need rounded up to the next full byte.
final int bitsAvailable = codes.size() * Byte.SIZE - codeOffset;
final int bitsNeeded = bits - bitsAvailable;
final int bytesNeeded = (bitsNeeded / Byte.SIZE) + (bitsNeeded % 8 != 0 ? 1 : 0);
// Read bytes until we have enough for a code value. If we aren't
// able to read enough then we've hit end of stream.
final byte[] codeBytes = new byte[bytesNeeded];
int bytesRead = 0;
while (bytesRead < bytesNeeded) {
int read = in.read(codeBytes, bytesRead, codeBytes.length - bytesRead);
if (read == -1) {
// If we haven't buffered anything then return end of
// stream.
if (totalRead == 0) return -1;
return totalRead;
}
bytesRead += read;
}
// Append read bytes to the buffered code bytes.
for (final byte codeByte : codeBytes)
codes.add(codeByte);
// Now decode the next code.
int value = 0;
int bitsDecoded = 0;
while (bitsDecoded < bits) {
// Read the next batch of bits.
final int bitlen = Math.min(bits - bitsDecoded, Byte.SIZE - codeOffset);
int msbits = codes.peek();
// First shift left to erase the most significant bits then
// shift right to get the correct number of bits.
msbits <<= codeOffset;
msbits &= 0xff;
msbits >>>= Byte.SIZE - bitlen;
// If we read to the end of this byte then zero the code bit
// offset and remove the byte.
bitsDecoded += bitlen;
codeOffset += bitlen;
if (codeOffset == Byte.SIZE) {
codeOffset = 0;
codes.remove();
}
// Shift left by the number of bits remaining to decode and add
// the current bits to the value.
value |= (msbits & 0xff) << (bits - bitsDecoded);
}
// Grab the bytes for this code.
byte[] data = dictionary.get(value);
// This is the first iteration. The next code will have a larger
// bit length.
if (prevdata.size() == 0) {
++bits;
}
// If there is previous data then add the previous data plus this
// data's first character to the dictionary.
else {
// If the code was not in the dictionary then we have
// encountered the code that we are going to enter into the
// dictionary right now.
//
// This is the odd case where the decoder is one code behind
// the encoder in populating the dictionary and the byte that
// will be added to create the sequence is equal to the first
// byte of the previous sequence.
if (data == null) {
final byte[] prevbytes = prevdata.toByteArray();
prevdata.write(prevbytes[0]);
} else {
prevdata.write(data[0]);
}
// Add the dictionary entry.
dictionary.put(dictionary.size(), prevdata.toByteArray());
prevdata.reset();
// If we just generated the code for 2^p - 1 then increment the
// code bit length.
if (dictionary.size() == (1 << bits))
++bits;
// If the code was not in the dictionary before, it should be
// now. Grab the data.
if (data == null)
data = dictionary.get(value);
}
// Append the decoded bytes to the provided buffer or the internal
// buffer.
for (final byte d : data) {
if (totalRead < len)
b[off + totalRead++] = d;
else
buffer.add(d);
}
// Save this data for the next iteration.
prevdata.write(data);
}
// Return the number of bytes decoded.
return totalRead;
}
/** Input stream. */
private final InputStream in;
/** The dictionary of bytes keyed off codes. */
private final Map<Integer,byte[]> dictionary = new HashMap<Integer,byte[]>(INITIAL_DICTIONARY);
/** Buffered code bytes. */
private final LinkedList<Byte> codes = new LinkedList<Byte>();
/** Current codebyte bit offset. */
private int codeOffset = 0;
/** Current bit length. */
private int bits = Byte.SIZE;
/** Buffered bytes pending read. */
private final LinkedList<Byte> buffer = new LinkedList<Byte>();
/** Previously buffered bytes. */
private final ByteArrayOutputStream prevdata = new ByteArrayOutputStream();
/** Stream closed. */
private boolean closed = false;
}
| 9,884 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslObject.java | /**
* Copyright (c) 2015-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* <p>A {@code MslObject} is an unordered collection of name/value pairs. It is
* functionally equivalent to a JSON object, in that it encodes the pair data
* without imposing any specific order and may contain more or less pairs than
* explicitly defined.</p>
*
* <p>The values can be any of these types: <code>Boolean</code>,
* <code>Byte[]</code> <code>MslArray</code>, <code>MslObject</code>,
* <code>Number</code>, or <code>String</code>. <code>Enum</code> is also
* accepted and will be converted to a <code>String</code> using its
* {@code name()} method.</p>
*
* <p>The generic <code>get()</code> and <code>opt()</code> methods return
* an object, which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and type
* coercion for you. The opt methods differ from the get methods in that they
* do not throw. Instead, they return a specified value, such as null.</p>
*
* <p>The <code>put</code> methods add or replace values in an object.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslObject {
/**
* Create a new empty {@code MslObject}.
*/
public MslObject() {
}
/**
* Create a new {@code MslObject} from the given map.
*
* @param map the map of name/value pairs. This must be a map of
* {@code String}s onto values. May be {@code null}.
* @throws IllegalArgumentException if one of the values is of an
* unsupported type.
*/
public MslObject(final Map<?,?> map) {
if (map != null) {
for (final Map.Entry<?, ?> entry : map.entrySet()) {
final Object key = entry.getKey();
if (!(key instanceof String))
throw new IllegalArgumentException("Map key is not a string.");
final Object value = entry.getValue();
put((String)key, value);
}
}
}
/** Object map. */
private final Map<String,Object> map = new HashMap<String,Object>();
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of a proper
* type or the value is {@code null}.
*/
@SuppressWarnings("unchecked")
public Object get(final String key) throws MslEncoderException {
if (key == null)
throw new IllegalArgumentException("Null key.");
final Object o = map.get(key);
if (o == null)
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] not found.");
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
return o;
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public boolean getBoolean(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof Boolean)
return (Boolean)o;
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a boolean.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public byte[] getBytes(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof byte[])
return (byte[])o;
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not binary data.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public double getDouble(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof Number)
return ((Number)o).doubleValue();
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a number.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public int getInt(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof Number)
return ((Number)o).intValue();
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a number.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public MslArray getMslArray(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof MslArray)
return (MslArray)o;
if (o instanceof Object[])
return new MslArray((Object[])o);
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a MslArray.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @param encoder the MSL encoder factory.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public MslObject getMslObject(final String key, final MslEncoderFactory encoder) throws MslEncoderException {
final Object o = get(key);
if (o instanceof MslObject)
return (MslObject)o;
/* FIXME: How should we handle MslEncodable?
if (o instanceof MslEncodable)
return ((MslEncodable)o).toMslObject(encoder);
*/
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof byte[]) {
try {
return encoder.parseObject((byte[])o);
} catch (final MslEncoderException e) {
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a MslObject.");
}
}
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a MslObject.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public long getLong(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof Number)
return ((Number)o).longValue();
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a number.");
}
/**
* Return the value associated with the specified key.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
* @throws MslEncoderException if there is no associated value of the
* proper type or the value is {@code null}.
*/
public String getString(final String key) throws MslEncoderException {
final Object o = get(key);
if (o instanceof String)
return (String)o;
throw new MslEncoderException("MslObject[" + MslEncoderFactory.quote(key) + "] is not a string.");
}
/**
* Return true if the specified key exists. The value may be {@code null}.
*
* @param key the key.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public boolean has(final String key) {
if (key == null)
throw new IllegalArgumentException("Null key.");
return map.containsKey(key);
}
/**
* Return the value associated with the specified key or {@code null} if
* the key is unknown or the value is an unsupported type.
*
* @param key the key.
* @return the value. May be {@code null}.
* @throws IllegalArgumentException if the key is {@code null}.
*/
@SuppressWarnings("unchecked")
public Object opt(final String key) {
if (key == null)
throw new IllegalArgumentException("Null key.");
final Object o = map.get(key);
try {
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
} catch (final IllegalArgumentException e) {
return null;
}
return o;
}
/**
* Return the value associated with the specified key or {@code false} if
* the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public boolean optBoolean(final String key) {
return optBoolean(key, false);
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public boolean optBoolean(final String key, final boolean defaultValue) {
final Object o = opt(key);
if (o instanceof Boolean)
return (Boolean)o;
return defaultValue;
}
/**
* Return the value associated with the specified key or an empty byte
* array if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public byte[] optBytes(final String key) {
return optBytes(key, new byte[0]);
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public byte[] optBytes(final String key, final byte[] defaultValue) {
final Object o = opt(key);
if (o instanceof byte[])
return (byte[])o;
return defaultValue;
}
/**
* Return the value associated with the specified key or {@code NaN} if
* the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public double optDouble(final String key) {
return optDouble(key, Double.NaN);
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public double optDouble(final String key, final double defaultValue) {
final Object o = opt(key);
if (o instanceof Number)
return ((Number)o).doubleValue();
return defaultValue;
}
/**
* Return the value associated with the specified key or zero if
* the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public int optInt(final String key) {
return optInt(key, 0);
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public int optInt(final String key, final int defaultValue) {
final Object o = opt(key);
if (o instanceof Number)
return ((Number)o).intValue();
return defaultValue;
}
/**
* Return the {@code MslArray} associated with the specified key or
* {@code null} if the key is unknown or the value is not of the correct
* type.
*
* @param key the key.
* @return the {@code MslArray} or {@code null}.
* @throws IllegalArgumentException if the key is {@code null}.
*/
@SuppressWarnings("unchecked")
public MslArray optMslArray(final String key) {
final Object o = opt(key);
if (o instanceof MslArray)
return (MslArray)o;
try {
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
} catch (final IllegalArgumentException e) {
return null;
}
return null;
}
/**
* Return the {@code MslObject} associated with the specified key or
* {@code null} if the key unknown or the value is not of the correct type.
*
* @param key the key.
* @param encoder the MSL encoder factory.
* @return the {@code MslObject} or {@code null}.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject optMslObject(final String key, final MslEncoderFactory encoder) {
final Object o = opt(key);
if (o instanceof MslObject)
return (MslObject)o;
/* FIXME: How should we handle MslEncodable?
if (o instanceof MslEncodable) {
try {
return ((MslEncodable)o).toMslObject(encoder);
} catch (final MslEncoderException e) {
// Drop through.
}
}
*/
if (o instanceof Map) {
try {
return new MslObject((Map<?,?>)o);
} catch (final IllegalArgumentException e) {
return null;
}
}
if (o instanceof byte[]) {
try {
return encoder.parseObject((byte[])o);
} catch (final MslEncoderException e) {
return null;
}
}
return null;
}
/**
* Return the value associated with the specified key or zero if
* the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public long optLong(final String key) {
return optLong(key, 0);
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public long optLong(final String key, final long defaultValue) {
final Object o = opt(key);
if (o instanceof Number)
return ((Number)o).longValue();
return defaultValue;
}
/**
* Return the value associated with the specified key or the empty string
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public String optString(final String key) {
return optString(key, "");
}
/**
* Return the value associated with the specified key or the default value
* if the key is unknown or the value is not of the correct type.
*
* @param key the key.
* @param defaultValue the default value.
* @return the value.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public String optString(final String key, final String defaultValue) {
final Object o = opt(key);
if (o instanceof String)
return (String)o;
return defaultValue;
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null} or the
* value is of an unsupported type.
*/
@SuppressWarnings("unchecked")
public MslObject put(final String key, final Object value) {
if (key == null)
throw new IllegalArgumentException("Null key.");
// Remove if requested.
if (value == null) {
map.remove(key);
return this;
}
// Otherwise set.
if (value instanceof Boolean ||
value instanceof byte[] ||
value instanceof Number ||
value instanceof MslObject ||
value instanceof MslArray ||
value instanceof String ||
value instanceof MslEncodable)
{
map.put(key, value);
}
else if (value instanceof Map)
map.put(key, new MslObject((Map<?,?>)value));
else if (value instanceof Collection)
map.put(key, new MslArray((Collection<Object>)value));
else if (value instanceof Object[])
map.put(key, new MslArray((Object[])value));
else if (value instanceof Enum)
map.put(key, ((Enum<?>)value).name());
else
throw new IllegalArgumentException("Value [" + value.getClass() + "] is an unsupported type.");
return this;
}
/**
* <p><p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putBoolean(final String key, final Boolean value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putBytes(final String key, final byte[] value) {
return put(key, value);
}
/**
* Put a key/value pair into the {@code MslObject}. The collection of
* elements will be transformed into a {@code MslArray}. If the value is
* {@code null} the key will be removed.
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null} or the value
* contains an unsupported type.
*/
public MslObject putCollection(final String key, final Collection<Object> value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putDouble(final String key, final Double value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putInt(final String key, final Integer value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putLong(final String key, final Long value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. The map of strings
* onto objects will be transformed into a {@code MslObject}. If the value
* is {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null} or one of
* the values in the map is an unsupported type.
*/
public MslObject putMap(final String key, final Map<String,Object> value) {
return put(key, value);
}
/**
* <p>Put a key/value pair into the {@code MslObject}. If the value is
* {@code null} the key will be removed.</p>
*
* <p>This method will call {@link #put(String, Object)}.</p>
*
* @param key the key.
* @param value the value. May be {@code null}.
* @return this.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public MslObject putString(final String key, final String value) {
return put(key, value);
}
/**
* Remove a key and its associated value from the {@code MslObject}.
*
* @param key the key.
* @return the removed value. May be {@code null}.
* @throws IllegalArgumentException if the key is {@code null}.
*/
public Object remove(final String key) {
if (key == null)
throw new IllegalArgumentException("Null key.");
final Object value = opt(key);
map.remove(key);
return value;
}
/**
* Return an unmodifiable set of the {@code MslObject} keys.
*
* @return the unmodifiable set of the {@code MslObject} keys.
*/
public Set<String> getKeys() {
return Collections.unmodifiableSet(map.keySet());
}
/**
* Return an unmodifiable map of the {@code MslObject} contents.
*
* @return the unmodifiable map of {@code MslObject} contents.
*/
public Map<String,Object> getMap() {
return Collections.unmodifiableMap(map);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (!(obj instanceof MslObject)) return false;
final MslObject that = (MslObject)obj;
try {
return MslEncoderUtils.equalObjects(this, that);
} catch (final MslEncoderException e) {
return false;
}
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return MslEncoderUtils.hashObject(this);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// This is based on the org.json {@code MslObject.write()} code.
final StringBuilder sb = new StringBuilder();
boolean commanate = false;
final int length = map.size();
final Iterator<String> keys = map.keySet().iterator();
sb.append('{');
if (length == 1) {
final String key = keys.next();
sb.append(MslEncoderFactory.quote(key));
sb.append(':');
sb.append(MslEncoderFactory.stringify(this.map.get(key)));
} else if (length != 0) {
while (keys.hasNext()) {
final String key = keys.next();
if (commanate) {
sb.append(',');
}
sb.append(MslEncoderFactory.quote(key));
sb.append(':');
sb.append(MslEncoderFactory.stringify(this.map.get(key)));
commanate = true;
}
}
sb.append('}');
return sb.toString();
}
}
| 9,885 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslTokenizer.java | /**
* Copyright (c) 2015-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
/**
* <p>A {@code MslTokenizer} takes in a binary source and parses out
* {@link MslObject} and {@link MslArray} instances.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public abstract class MslTokenizer {
/**
* <p>Closes the tokenizer, cleaning up any resources and preventing future
* use.</p>
*
* @throws MslEncoderException if there is an error closing the tokenizer.
*/
public void close() throws MslEncoderException {
closed = true;
}
/**
* <p>Aborts future reading off the tokenizer.</p>
*/
public void abort() {
aborted = true;
}
/**
* <p>Returns true if more objects can be read from the data source. This
* method determines that by actually trying to read the next object.</p>
*
* @param timeout read timeout in milliseconds or -1 for no timeout.
* @return true if more objects are available from the data source, false
* if the tokenizer has been aborted or closed.
* @throws MslEncoderException if the next object cannot be read or the
* source data at the current position is invalid.
*/
public boolean more(final int timeout) throws MslEncoderException {
if (aborted || closed) return false;
if (next != null) return true;
next = nextObject(timeout);
return (next != null);
}
/**
* <p>Return the next object (should be an instance of {@link MslObject} or
* {@link MslArray}) from the source data.</p>
*
* <p>If the source data's current position cannot be parsed as an object,
* an exception is thrown and the source data position's new position is
* undefined. Subsequent calls to this function should not re-throw the
* exception and instead should look for the next object. The algorithm
* used to search for the next object, and how the position should be set
* to do so, is up to the implementer and may depend upon the encoding.</p>
*
* @param timeout read timeout in milliseconds or -1 for no timeout.
* @return the next object or {@code null} if there are no more.
* @throws MslEncoderException if the next object cannot be read or the
* source data at the current position is invalid.
*/
protected abstract MslObject next(final int timeout) throws MslEncoderException;
/**
* <p>Return the next object.</p>
*
* @param timeout read timeout in milliseconds or -1 for no timeout.
* @return the next object or {@code null} if there are no more or the
* tokenizer has been aborted or closed.
* @throws MslEncoderException if the next object cannot be read or the
* source data at the current position is invalid.
*/
public MslObject nextObject(final int timeout) throws MslEncoderException {
if (aborted || closed) return null;
if (next != null) {
final MslObject mo = next;
next = null;
return mo;
}
return next(timeout);
}
/** Closed. */
private boolean closed = false;
/** Aborted. */
private boolean aborted = false;
/** Cached next object. */
private MslObject next = null;
}
| 9,886 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslEncodable.java | /**
* Copyright (c) 2015-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
/**
* <p>This interface allows a class to override the default behavior when being
* encoded into a {@link MslObject} or {@link MslArray}.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public interface MslEncodable {
/**
* Returns the requested encoding of a MSL object representing the
* implementing class.
*
* @param encoder the encoder factory.
* @param format the encoder format.
* @return a MSL encoding of the MSL object.
* @throws MslEncoderException if the encoder format is not supported or
* there is an error encoding the data.
*/
public byte[] toMslEncoding(final MslEncoderFactory encoder, final MslEncoderFormat format) throws MslEncoderException;
}
| 9,887 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/JsonMslArray.java | /**
* Copyright (c) 2015-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.nio.charset.Charset;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.util.Base64;
/**
* <p>A {@code MslArray} that encodes its data as UTF-8 JSON.</p>
*
* <p>This implementation is backed by {@code org.json}.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class JsonMslArray extends MslArray implements JSONString {
/** UTF-8 charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/**
* Create a new {@code JsonMslArray} from the given {@code MslArray}.
*
* @param encoder the encoder factory.
* @param a the {@code MslArray}.
* @throws MslEncoderException if the MSL array contains an unsupported
* type.
*/
public JsonMslArray(final MslEncoderFactory encoder, final MslArray a) throws MslEncoderException {
this.encoder = encoder;
try {
for (int i = 0; i < a.size(); ++i)
put(i, a.opt(i));
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL array encoding.", e);
}
}
/**
* Create a new {@code JsonMslArray} from the given {@code JSONArray}.
*
* @param encoder the encoder factory.
* @param ja the {@code JSONArray}.
* @throws MslEncoderException if the JSON array contains an unsupported
* type.
*/
public JsonMslArray(final MslEncoderFactory encoder, final JSONArray ja) throws MslEncoderException {
this.encoder = encoder;
try {
for (int i = 0; i < ja.length(); ++i)
put(-1, ja.opt(i));
} catch (final JSONException e) {
throw new MslEncoderException("Invalid JSON array encoding.", e);
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL array encoding.", e);
}
}
/**
* Create a new {@code JsonMslArray} from its encoded representation.
*
* @param encoder the encoder factory.
* @param encoding the encoded data.
* @throws MslEncoderException if the data is malformed or invalid.
*/
public JsonMslArray(final MslEncoderFactory encoder, final byte[] encoding) throws MslEncoderException {
this.encoder = encoder;
try {
final String json = new String(encoding, UTF_8);
final JSONArray ja = new JSONArray(json);
for (int i = 0; i < ja.length(); ++i)
put(-1, ja.opt(i));
} catch (final JSONException e) {
throw new MslEncoderException("Invalid JSON array encoding.", e);
} catch (final IllegalArgumentException e) {
throw new MslEncoderException("Invalid MSL array encoding.", e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslArray#put(int, java.lang.Object)
*/
@Override
public MslArray put(final int index, final Object value) {
final Object o;
try {
// Convert JSONObject to MslObject.
if (value instanceof JSONObject)
o = new JsonMslObject(encoder, (JSONObject)value);
// Convert JSONarray to a MslArray.
else if (value instanceof JSONArray)
o = new JsonMslArray(encoder, (JSONArray)value);
// All other types are OK as-is.
else
o = value;
} catch (final MslEncoderException e) {
throw new IllegalArgumentException("Unsupported JSON object or array representation.", e);
}
return super.put(index, o);
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslArray#getBytes(int)
*/
@Override
public byte[] getBytes(final int index) throws MslEncoderException {
// When a JsonMslArray is decoded, there's no way for us to know if a
// value is supposed to be a String to byte[]. Therefore interpret
// Strings as Base64-encoded data consistent with the toJSONString()
// and getEncoded().
final Object value = get(index);
if (value instanceof byte[])
return (byte[])value;
if (value instanceof String) {
try {
return Base64.decode((String)value);
} catch (final IllegalArgumentException e) {
// Fall through.
}
}
throw new MslEncoderException("MslArray[" + index + "] is not binary data.");
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslArray#optBytes(int)
*/
@Override
public byte[] optBytes(final int index) {
return optBytes(index, new byte[0]);
}
public byte[] optBytes(final int index, final byte[] defaultValue) {
// When a JsonMslArray is decoded, there's no way for us to know if a
// value is supposed to be a String to byte[]. Therefore interpret
// Strings as Base64-encoded data consistent with the toJSONString()
// and getEncoded().
final Object value = opt(index);
if (value instanceof byte[])
return (byte[])value;
if (value instanceof String) {
try {
return Base64.decode((String)value);
} catch (final IllegalArgumentException e) {
// Fall through.
}
}
return defaultValue;
}
/* (non-Javadoc)
* @see org.json.JSONString#toJSONString()
*/
@Override
public String toJSONString() {
try {
final JSONArray ja = new JSONArray();
final int size = size();
for (int i = 0; i < size; ++i) {
final Object value = opt(i);
if (value instanceof byte[]) {
ja.put(i, Base64.encode((byte[])value));
} else if (value instanceof JsonMslObject || value instanceof JsonMslArray) {
ja.put(i, value);
} else if (value instanceof MslObject) {
final JsonMslObject jsonValue = new JsonMslObject(encoder, (MslObject)value);
ja.put(i, jsonValue);
} else if (value instanceof MslArray) {
final JsonMslArray jsonValue = new JsonMslArray(encoder, (MslArray)value);
ja.put(i, jsonValue);
} else if (value instanceof MslEncodable) {
final byte[] json = ((MslEncodable)value).toMslEncoding(encoder, MslEncoderFormat.JSON);
final JsonMslObject jsonValue = new JsonMslObject(encoder, json);
ja.put(i, jsonValue);
} else {
ja.put(i, value);
}
}
return ja.toString();
} catch (final IllegalArgumentException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
} catch (final MslEncoderException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
} catch (final JSONException e) {
throw new MslInternalException("Error encoding MSL object as JSON.", e);
}
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslArray#toString()
*/
@Override
public String toString() {
return toJSONString();
}
/** MSL encoder factory. */
private final MslEncoderFactory encoder;
}
| 9,888 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslEncoderFormat.java | /**
* Copyright (c) 2015-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* <p>MSL encoder formats.</p>
*
* <p>The format name is used to uniquely identify encoder formats.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslEncoderFormat {
/** Map of names onto formats. */
private static Map<String,MslEncoderFormat> formatsByName = new HashMap<String,MslEncoderFormat>();
/** Map of identifiers onto formats. */
private static Map<Byte,MslEncoderFormat> formatsById = new HashMap<Byte,MslEncoderFormat>();
/** UTF-8 JSON. */
public static final MslEncoderFormat JSON = new MslEncoderFormat("JSON", (byte)'{');
/**
* Define an encoder format with the specified name and byte stream
* identifier.
*
* @param name the encoder format name.
* @param identifier the byte stream identifier.
*/
protected MslEncoderFormat(final String name, final byte identifier) {
this.name = name;
this.identifier = identifier;
// Add this format to the map.
synchronized (formatsByName) {
formatsByName.put(name, this);
}
synchronized (formatsById) {
formatsById.put(Byte.valueOf(identifier), this);
}
}
/**
* @param name the encoder format name.
* @return the encoder format identified by the specified name or
* {@code null} if there is none.
*/
public static MslEncoderFormat getFormat(final String name) {
return formatsByName.get(name);
}
/**
* @param identifier the encoder format identifier.
* @return the encoder format identified by the specified identifier or
* {@code null} if there is none.
*/
public static MslEncoderFormat getFormat(final byte identifier) {
return formatsById.get(Byte.valueOf(identifier));
}
/**
* @return all known encoder formats.
*/
public static Collection<MslEncoderFormat> values() {
return formatsByName.values();
}
/**
* @return the format identifier.
*/
public String name() {
return name;
}
/**
* @return the byte stream identifier.
*/
public byte identifier() {
return identifier;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return name();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return name.hashCode() ^ Byte.valueOf(identifier).hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof MslEncoderFormat)) return false;
final MslEncoderFormat that = (MslEncoderFormat)obj;
return this.name.equals(that.name) && this.identifier == that.identifier;
}
/** Name. */
private final String name;
/** Byte stream identifier. */
private final byte identifier;
}
| 9,889 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslEncoderUtils.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.util.Base64;
import com.netflix.msl.util.MslContext;
/**
* MSL encoder utility functions.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslEncoderUtils {
/** Encoding charset. */
private static final Charset UTF_8 = Charset.forName("UTF-8");
/** Base64 characters. */
private static final char CHAR_PLUS = '+';
private static final char CHAR_MINUS = '-';
private static final char CHAR_SLASH = '/';
private static final char CHAR_UNDERSCORE = '_';
private static final char CHAR_EQUALS = '=';
/**
* URL-safe Base64 encode data as UTF-8 without padding characters.
*
* @param s the value to Base64 encode.
* @return the Base64 encoded data.
*/
public static String b64urlEncode(final String s) {
final byte[] data = s.getBytes(UTF_8);
return MslEncoderUtils.b64urlEncode(data);
}
/**
* URL-safe Base64 encode data without padding characters.
*
* @param data the value to Base64 encode.
* @return the Base64 encoded data.
*/
public static String b64urlEncode(final byte[] data) {
// Perform a standard Base64 encode.
final String padded = Base64.encode(data);
// Replace standard characters with URL-safe characters.
final String modified = padded.replace(CHAR_PLUS, CHAR_MINUS).replace(CHAR_SLASH, CHAR_UNDERSCORE);
// Remove padding.
final int padIndex = modified.indexOf(CHAR_EQUALS);
return (padIndex != -1) ? modified.substring(0, padIndex) : modified;
}
/**
* URL-safe Base64 decode data that has no padding characters.
*
* @param data the Base64 encoded data.
* @return the decoded data or {@code null} if there is an error decoding.
*/
public static byte[] b64urlDecode(final String data) {
// Replace URL-safe characters with standard characters.
final String modified = data.replace(CHAR_MINUS, CHAR_PLUS).replace(CHAR_UNDERSCORE, CHAR_SLASH);
// Pad if necessary, then decode.
try {
final int toPad = 4 - (modified.length() % 4);
if (toPad == 0 || toPad == 4)
return Base64.decode(modified);
final StringBuilder padded = new StringBuilder(modified);
for (int i = 0; i < toPad; ++i)
padded.append(CHAR_EQUALS);
return Base64.decode(padded.toString());
} catch (final IllegalArgumentException e) {
return null;
}
}
/**
* Create a MSL array from a collection of objects that are either one of
* the accepted types: <code>Boolean</code>, <code>Byte[]</code>,
* <code>MslArray</code>, <code>MslObject</code>, <code>Number</code>,
* <code>String</code>, <code>null</code>, or turn any
* <code>MslEncodable</code> into a <code>MslObject</code>.
*
* @param ctx MSL context.
* @param format MSL encoder format.
* @param c a collection of MSL encoding-compatible objects.
* @return the constructed MSL array.
* @throws MslEncoderException if a <code>MslEncodable</code> cannot be
* encoded properly or an unsupported object is encountered.
*/
public static MslArray createArray(final MslContext ctx, final MslEncoderFormat format, final Collection<?> c) throws MslEncoderException {
final MslEncoderFactory encoder = ctx.getMslEncoderFactory();
final MslArray array = encoder.createArray();
for (final Object o : c) {
if (o instanceof byte[] ||
o instanceof Boolean ||
o instanceof MslArray ||
o instanceof MslObject ||
o instanceof Number ||
o instanceof String ||
o instanceof Map ||
o instanceof Collection ||
o instanceof Object[] ||
o instanceof Enum ||
o == null)
{
array.put(-1, o);
} else if (o instanceof MslEncodable) {
final MslEncodable me = (MslEncodable)o;
final byte[] encode = me.toMslEncoding(encoder, format);
final MslObject mo = encoder.parseObject(encode);
array.put(-1, mo);
} else {
throw new MslEncoderException("Class " + o.getClass().getName() + " is not MSL encoding-compatible.");
}
}
return array;
}
/**
* Performs a deep comparison of two MSL objects for equivalence. MSL
* objects are equivalent if they have the same name/value pairs. Also, two
* MSL object references are considered equal if both are null.
*
* @param mo1 first MSL object. May be null.
* @param mo2 second MSL object. May be null.
* @return true if the MSL objects are equivalent.
* @throws MslEncoderException if there is an error parsing the data.
*/
public static boolean equalObjects(final MslObject mo1, final MslObject mo2) throws MslEncoderException {
// Equal if both null or the same object.
if (mo1 == mo2)
return true;
// Not equal if only one of them is null.
if (mo1 == null || mo2 == null)
return false;
// Check the children names. If there are no names, the MSL object is
// empty.
final Set<String> names1 = mo1.getKeys();
final Set<String> names2 = mo2.getKeys();
// Continue if the same object.
if (names1 != names2) {
// Not equal if only one of them is null or of different length.
if (names1 == null || names2 == null || names1.size() != names2.size())
return false;
// Not equal if the sets are not equal.
if (!names1.equals(names2))
return false;
}
// Bail on the first child element whose values are not equal.
for (final String name : names1) {
final Object o1 = mo1.opt(name);
final Object o2 = mo2.opt(name);
// Equal if both null or the same object.
if (o1 == o2) continue;
// Not equal if only one of them is null.
if (o1 == null || o2 == null)
return false;
// byte[] may be represented differently, so we have to compare by
// accessing directly. This isn't perfect but works for now.
if (o1 instanceof byte[] || o2 instanceof byte[]) {
final byte[] b1 = mo1.getBytes(name);
final byte[] b2 = mo2.getBytes(name);
if (!Arrays.equals(b1, b2))
return false;
} else if (o1 instanceof MslObject && o2 instanceof MslObject) {
if (!MslEncoderUtils.equalObjects((MslObject)o1, (MslObject)o2))
return false;
} else if (o1 instanceof MslArray && o2 instanceof MslArray) {
if (!MslEncoderUtils.equalArrays((MslArray)o1, (MslArray)o2))
return false;
} else {
if (o1.getClass() != o2.getClass())
return false;
if (!o1.equals(o2))
return false;
}
}
// All name/value pairs are equal.
return true;
}
/**
* Computes the hash code of a MSL object in a manner that is consistent
* with MSL object equality.
*
* @param mo MSL object. May be {@code null}.
* @return the hash code.
*/
public static int hashObject(final MslObject mo) {
if (mo == null) return -1;
int hashcode = 0;
final Set<String> names = mo.getKeys();
for (final String name : names) {
final int valuehash;
// byte[] may be represented differently, so try accessing directly
// first.
final byte[] b = mo.optBytes(name, null);
if (b != null) {
valuehash = Arrays.hashCode(b);
}
// Otherwise process normally.
else {
final Object o = mo.opt(name);
if (o instanceof MslObject) {
valuehash = hashObject((MslObject)o);
} else if (o instanceof MslArray) {
valuehash = hashArray((MslArray)o);
} else if (o != null) {
valuehash = o.hashCode();
} else {
valuehash = 1;
}
}
// Modify the hash code. The name/value association matters.
hashcode ^= (name.hashCode() + valuehash);
}
return hashcode;
}
/**
* Performs a deep comparison of two MSL arrays for equality. Two MSL
* arrays are considered equal if both arrays contain the same number of
* elements, and all corresponding pairs of elements in the two arrays are
* equal. In other words, two MSL arrays are equal if they contain the
* same elements in the same order. Also, two MSL array references are
* considered equal if both are null.
*
* @param ma1 first MSL array. May be null.
* @param ma2 second MSL array. May be null.
* @return true if the MSL arrays are equal.
* @throws MslEncoderException if there is an error parsing the data.
*/
public static boolean equalArrays(final MslArray ma1, final MslArray ma2) throws MslEncoderException {
// Equal if both null or the same object.
if (ma1 == ma2)
return true;
// Not equal if only one of them is null or of different length.
if (ma1 == null || ma2 == null || ma1.size() != ma2.size())
return false;
// Bail on the first elements whose values are not equal.
for (int i = 0; i < ma1.size(); ++i) {
final Object o1 = ma1.opt(i);
final Object o2 = ma2.opt(i);
// Equal if both null or the same object.
if (o1 == o2) continue;
// Not equal if only one of them is null.
if (o1 == null || o2 == null)
return false;
// byte[] may be represented differently, so we have to compare by
// accessing directly. This isn't perfect but works for now.
if (o1 instanceof byte[] || o2 instanceof byte[]) {
final byte[] b1 = ma1.getBytes(i);
final byte[] b2 = ma2.getBytes(i);
if (!Arrays.equals(b1, b2))
return false;
} else if (o1 instanceof MslObject && o2 instanceof MslObject) {
if (!MslEncoderUtils.equalObjects((MslObject)o1, (MslObject)o2))
return false;
} else if (o1 instanceof MslArray && o2 instanceof MslArray) {
if (!MslEncoderUtils.equalArrays((MslArray)o1, (MslArray)o2))
return false;
} else {
if (o1.getClass() != o2.getClass())
return false;
if (!o1.equals(o2))
return false;
}
}
// All values are equal.
return true;
}
/**
* Computes the hash code of a MSL array in a manner that is consistent
* with MSL array equality.
*
* @param ma MSL array. May be {@code null}.
* @return the hash code.
*/
public static int hashArray(final MslArray ma) {
if (ma == null) return -1;
int hashcode = 0;
for (int i = 0; i < ma.size(); ++i) {
// byte[] may be represented differently, so try accessing directly
// first.
final byte[] b = ma.optBytes(i, null);
if (b != null) {
hashcode = 37 * hashcode + Arrays.hashCode(b);
continue;
}
// Otherwise process normally.
final Object o = ma.opt(i);
if (o instanceof MslObject) {
hashcode = 37 * hashcode + hashObject((MslObject)o);
} else if (o instanceof MslArray) {
hashcode = 37 * hashcode + hashArray((MslArray)o);
} else if (o != null) {
hashcode = 37 * hashcode + o.hashCode();
} else {
hashcode = 37 * hashcode + 1;
}
}
return hashcode;
}
/**
* Performs a shallow comparison of two MSL arrays for set equality. Two
* MSL arrays are considered set-equal if both arrays contain the same
* number of elements and all elements found in one array are also found in
* the other. In other words, two MSL arrays are set-equal if they contain
* the same elements in the any order. Also, two MSL array references are
* considered set-equal if both are null.
*
* @param ma1 first MSL array. May be {@code null}.
* @param ma2 second MSL array. May be {@code null}.
* @return true if the MSL arrays are set-equal.
* @throws MslEncoderException if there is an error parsing the data.
*/
public static boolean equalSets(final MslArray ma1, final MslArray ma2) throws MslEncoderException {
// Equal if both null or the same object.
if (ma1 == ma2)
return true;
// Not equal if only one of them is null or of different length.
if (ma1 == null || ma2 == null || ma1.size() != ma2.size())
return false;
// Compare as sets.
final Set<Object> s1 = new HashSet<Object>();
final Set<Object> s2 = new HashSet<Object>();
for (int i = 0; i < ma1.size(); ++i) {
s1.add(ma1.opt(i));
s2.add(ma2.opt(i));
}
return s1.equals(s2);
}
/**
* Merge two MSL objects into a single MSL object. If the same key is
* found in both objects, the second object's value is used. The values are
* copied by reference so this is a shallow copy.
*
* @param mo1 first MSL object. May be null.
* @param mo2 second MSL object. May be null.
* @return the merged MSL object or null if both arguments are null.
* @throws MslEncoderException if a value in one of the arguments is
* invalid—this should not happen.
*/
public static MslObject merge(final MslObject mo1, final MslObject mo2) throws MslEncoderException {
// Return null if both objects are null.
if (mo1 == null && mo2 == null)
return null;
// Make a copy of the first object, or create an empty object.
final MslObject mo = (mo1 != null)
? new MslObject(mo1.getMap())
: new MslObject();
// If the second object is null, we're done and just return the copy.
if (mo2 == null)
return mo;
// Copy the contents of the second object into the final object.
for (final String key : mo2.getKeys())
mo.put(key, mo2.get(key));
return mo;
}
}
| 9,890 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/DefaultMslEncoderFactory.java | /**
* Copyright (c) 2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.io.InputStream;
import java.util.Set;
/**
* <p>Default {@link MslEncoderFactory} implementation that supports the
* following encoder formats:
* <ul>
* <li>JSON: backed by {@code org.json}.</li>
* </ul>
* </p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class DefaultMslEncoderFactory extends MslEncoderFactory {
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncoderFactory#getPreferredFormat(java.util.Set)
*/
public MslEncoderFormat getPreferredFormat(final Set<MslEncoderFormat> formats) {
// We don't know about any other formats right now.
return MslEncoderFormat.JSON;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncoderFactory#generateTokenizer(java.io.InputStream, com.netflix.msl.io.MslEncoderFormat)
*/
protected MslTokenizer generateTokenizer(final InputStream source, final MslEncoderFormat format) throws MslEncoderException {
// JSON.
if (MslEncoderFormat.JSON.equals(format))
return new JsonMslTokenizer(this, source);
// Unsupported encoder format.
throw new MslEncoderException("Unsupported encoder format: " + format + ".");
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncoderFactory#parseObject(byte[])
*/
public MslObject parseObject(final byte[] encoding) throws MslEncoderException {
// Identify the encoder format.
final MslEncoderFormat format = parseFormat(encoding);
// JSON.
if (MslEncoderFormat.JSON.equals(format))
return new JsonMslObject(this, encoding);
// Unsupported encoder format.
throw new MslEncoderException("Unsupported encoder format: " + format + ".");
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslEncoderFactory#encodeObject(com.netflix.msl.io.MslObject, com.netflix.msl.io.MslEncoderFormat)
*/
public byte[] encodeObject(final MslObject object, final MslEncoderFormat format) throws MslEncoderException {
// JSON.
if (MslEncoderFormat.JSON.equals(format))
return JsonMslObject.getEncoded(this, object);
// Unsupported encoder format.
throw new MslEncoderException("Unsupported encoder format: " + format + ".");
}
}
| 9,891 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/UnsynchronizedBufferedInputStream.java | /**
* Copyright (c) 2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* <p>A {@code UnsynchronizedBufferedInputStream} adds support for the
* {@code mark()} and {@code reset()} functions.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class UnsynchronizedBufferedInputStream extends FilterInputStream {
/**
* Buffer of data read since the last call to mark(). Null if
* mark() has not been called or if the read limit has been
* exceeded.
*/
protected byte buf[] = null;
/** Number of valid bytes in the buffer. */
protected int bufcount;
/** Current buffer read position. */
protected int bufpos;
/**
* Creates a new <code>UnsynchronizedBufferedInputStream</code> without any
* mark position set.
*
* @param in the backing input stream.
*/
public UnsynchronizedBufferedInputStream(final InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
if (in == null)
throw new IOException("Stream is closed");
// If we have any data in the buffer, read it first.
if (bufpos < bufcount)
return buf[bufpos++];
// Otherwise read from the backing stream...
final int c = in.read();
if (c == -1) return -1;
// If we are buffering data...
if (buf != null) {
// Store the data if there is space.
if (bufcount < buf.length) {
buf[bufcount++] = (byte)c;
bufpos++;
}
// Otherwise we have exceeded the read limit. Stop buffering and
// invalidate the mark.
else {
buf = null;
bufcount = 0;
bufpos = 0;
}
}
// Return the read data.
return c;
}
@Override
public int read(final byte b[], final int off, final int len) throws IOException {
if (in == null)
throw new IOException("Stream is closed");
// Copy in any buffered data.
final int copied;
if (bufcount > bufpos) {
copied = Math.min(bufcount - bufpos, len);
System.arraycopy(buf, bufpos, b, off, copied);
bufpos += copied;
} else {
copied = 0;
}
// Read any remaining data requested.
final int remaining = len - copied;
final int numread = in.read(b, off + copied, remaining);
// If we were unable to read, return the number of bytes copied or -1
// to indicate end-of-stream if we also didn't copy any bytes.
if (numread == -1)
return (copied > 0) ? copied : -1;
// If we are buffering data...
if (buf != null) {
// Store the data if there is space.
if (bufcount + numread <= buf.length) {
System.arraycopy(b, copied, buf, bufpos, numread);
bufcount += numread;
bufpos += numread;
}
// Otherwise we have exceeded the read limit. Stop buffering and
// invalidate the mark.
else {
buf = null;
bufcount = 0;
bufpos = 0;
}
}
// Return number of bytes read.
return copied + numread;
}
@Override
public long skip(final long n) throws IOException {
if (in == null)
throw new IOException("Stream is closed");
// If we have enough buffered characters, skip over them.
final long buffered = bufcount - bufpos;
if (buffered >= n) {
bufpos += n;
return n;
}
// Otherwise skip over the buffered characters and read the rest.
bufpos += buffered;
long remaining = n - buffered;
while (remaining > 0) {
final byte[] buf = new byte[(int)remaining];
final int read = read(buf, 0, buf.length);
if (read == -1) break;
remaining -= read;
}
// Return the number of characters skipped.
return n - remaining;
}
@Override
public int available() throws IOException {
if (in == null)
throw new IOException("Stream is closed");
final int available = in.available();
return (bufcount + available < 0) ? Integer.MAX_VALUE : bufcount + available;
}
@Override
public void mark(final int readlimit) {
// Create the new buffer of the requested size.
final byte[] newbuf = new byte[readlimit];
// Copy any unread data that is currently buffered into the new buffer.
final int tocopy = (buf != null) ? bufcount - bufpos : 0;
if (tocopy > 0)
System.arraycopy(buf, bufpos, newbuf, 0, tocopy);
// Set the buffer.
buf = newbuf;
bufpos = 0;
bufcount = tocopy;
}
@Override
public void reset() throws IOException {
if (in == null)
throw new IOException("Stream is closed");
bufpos = 0;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void close() throws IOException {
if (in != null) {
in.close();
in = null;
}
}
} | 9,892 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/JavaUrl.java | /**
* Copyright (c) 2012-2016 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.io.BufferedInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* An implementation of the {@link Url} interface based on the built-in Java
* {@link URL} class.
*/
public class JavaUrl implements Url {
/**
* <p>A delayed input stream does not open the real input stream until one
* of its methods is called. This class may be useful in situations where
* the connection will not permit use of its output stream after the input
* stream is requested.</p>
*
* <p>The input stream itself will be a {@link BufferedInputStream} which
* will read ahead for improved performance, and support the
* {@link #mark(int)}, {@link #reset()}, and {@link #skip(long)}
* methods. This is necessary to facilitate stream reuse across multiple
* MSL messages.</p>
*/
public static class DelayedInputStream extends FilterInputStream {
/**
* Create a new delayed input stream that will not attempt to
* construct the input stream from the URL connection until it is
* actually needed (i.e. read from).
*
* @param conn backing URL connection.
*/
public DelayedInputStream(final URLConnection conn) {
super(null);
this.conn = conn;
}
/**
* <p>If the connection input stream has not already been opened, open
* it and wrap it inside a {@link BufferedInputStream}, then assign it
* to the parent member variable {@link FilterInputStream#in}.</p>
*
* <p>If mark was called and delayed, also mark the input stream.</p>
*
* @throws IOException any exception thrown by
* {@link URLConnection#getInputStream()}.
*/
private void openOnce() throws IOException {
// Return immediately if already open.
if (in != null) return;
// Open and wrap the input stream.
final InputStream source = conn.getInputStream();
in = new BufferedInputStream(source);
// If mark had been called earlier, mark the input stream now.
if (readlimit != -1)
in.mark(readlimit);
}
@Override
public int available() throws IOException {
openOnce();
return super.available();
}
@Override
public void close() throws IOException {
openOnce();
super.close();
}
@Override
public synchronized void mark(final int readlimit) {
// Mark the BufferedInputStream if it is already open.
if (in != null)
super.mark(readlimit);
// Otherwise remember that mark was called so it can be called on
// the BufferedInputStream once opened.
else
this.readlimit = readlimit;
}
@Override
public boolean markSupported() {
// BufferedInputStream supports mark.
return true;
}
@Override
public int read() throws IOException {
openOnce();
return super.read();
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
openOnce();
return super.read(b, off, len);
}
@Override
public int read(final byte[] b) throws IOException {
openOnce();
return super.read(b);
}
@Override
public synchronized void reset() throws IOException {
openOnce();
super.reset();
}
@Override
public long skip(final long n) throws IOException {
openOnce();
return super.skip(n);
}
/** Connection providing the input stream. */
private final URLConnection conn;
/** Mark read limit. -1 if no mark is set. */
private int readlimit = -1;
}
/**
* An implementation of the {@link Connection} interface backed by the
* built-in Java {@link URLConnection} class.
*/
private static class JavaConnection implements Connection {
/**
* Create a new Java connection with the backing URL connection.
*
* @param conn the backing URL connection.
*/
public JavaConnection(final URLConnection conn) {
this.conn = conn;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.Url.Connection#getInputStream()
*/
@Override
public InputStream getInputStream() throws IOException {
// Asking for the URL connection's input stream prevents further
// writing to the output stream, so return a delayed input stream.
return new DelayedInputStream(conn);
}
/* (non-Javadoc)
* @see com.netflix.msl.io.Url.Connection#getOutputStream()
*/
@Override
public OutputStream getOutputStream() throws IOException {
return conn.getOutputStream();
}
/** URL connection. */
private final URLConnection conn;
}
/**
* @param url the target location.
*/
public JavaUrl(final URL url) {
this.url = url;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.Url#setTimeout(int)
*/
@Override
public void setTimeout(final int timeout) {
this.timeout = timeout;
}
/* (non-Javadoc)
* @see com.netflix.msl.io.Url#openConnection()
*/
@Override
public Connection openConnection() throws IOException {
final URLConnection connection = url.openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
return new JavaConnection(connection);
}
/** URL. */
private final URL url;
/** Connection timeout. */
private int timeout = 0;
}
| 9,893 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/LZWOutputStream.java | /**
* Copyright (c) 2013-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* <p>This class implements a stream filter for writing compressed data in the
* LZW format.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class LZWOutputStream extends OutputStream {
/** Maximum number of codes to buffer before flushing. */
private static final int MAX_BUFFER_SIZE = 100;
/** A byte array for use as map keys. */
private static class Key {
/**
* Create a new key with the following byte array value. This does not
* make a copy of the byte array.
*
* @param bytes the byte array to serve as the key value.
*/
public Key(final byte[] bytes) {
this.bytes = bytes;
this.hashCode = Arrays.hashCode(bytes);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof Key)) return false;
return Arrays.equals(bytes, ((Key)o).bytes);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return hashCode;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return Arrays.toString(bytes);
}
/** The byte array value. */
private final byte[] bytes;
/** The hash code value. */
private final int hashCode;
}
/** A code is a numeric value represented by a specific number of bits. */
private static class Code {
/**
* Create a new code with the specified value and bit length.
*
* @param value the value.
* @param bits the number of bits used to encode the value.
*/
public Code(int value, int bits) {
this.value = value;
this.bits = bits;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return Integer.toHexString(value) + " (" + bits + "b)";
}
/** Numeric value. */
public final int value;
/** Bit length. */
public final int bits;
}
/** Maximum number of values represented by a byte. */
private static final int BYTE_RANGE = 256;
/** The initial dictionary. */
private static final Map<Key,Integer> INITIAL_DICTIONARY = new HashMap<Key,Integer>(BYTE_RANGE);
static {
for (int i = 0; i < BYTE_RANGE; ++i) {
final byte[] keybytes = { (byte)i };
final Key key = new Key(keybytes);
INITIAL_DICTIONARY.put(key, i);
}
}
/**
* Creates a new output stream.
*
* @param out the output stream.
*/
public LZWOutputStream(final OutputStream out) {
this.out = out;
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
/* (non-Javadoc)
* @see java.io.OutputStream#close()
*/
@Override
public void close() throws IOException {
if (!closed) {
finish();
out.close();
closed = true;
}
}
/**
* Finishes writing compressed data to the output stream without closing
* the underlying stream. Use this method when applying multiple filters in
* succession to the same output stream.
*
* @throws IOException if an I/O error has occurred.
*/
public void finish() throws IOException {
if (!finish) {
finish = true;
// If there are any symbols left we have to emit those codes now.
if (symbols.size() > 0) {
final byte[] keybytes = symbols.toByteArray();
final Key key = new Key(keybytes);
final Integer value = dictionary.get(key);
buffer.add(new Code(value, bits));
flush();
}
}
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(int)
*/
@Override
public void write(int b) throws IOException {
final byte[] buf = new byte[1];
buf[0] = (byte)(b & 0xff);
write(buf, 0, 1);
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(byte[], int, int)
*/
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (closed)
throw new IOException("Output stream is closed.");
if (off < 0)
throw new IndexOutOfBoundsException("Offset cannot be negative.");
if (len < 0)
throw new IndexOutOfBoundsException("Length cannot be negative.");
if (off + len > b.length)
throw new IndexOutOfBoundsException("Offset plus length cannot be greater than the array length.");
for (int i = off; i < off + len; ++i) {
// Add a byte to the input.
final byte c = b[i];
symbols.write(c);
// Check if the input is in the dictionary.
final byte[] keybytes = symbols.toByteArray();
final Key key = new Key(keybytes);
final Integer value = dictionary.get(key);
// If the input is not in the dictionary, then...
if (value == null) {
// emit the previous input's code...
final byte[] prevkeybytes = Arrays.copyOf(keybytes, keybytes.length - 1);
final Key prevkey = new Key(prevkeybytes);
final Integer prevvalue = dictionary.get(prevkey);
buffer.add(new Code(prevvalue, bits));
// and add the new input to the dictionary.
//
// The bit width increases from p to p + 1 when the new code is
// the first code requiring p + 1 bits.
final int newvalue = dictionary.size();
if (newvalue >> bits != 0)
++bits;
dictionary.put(key, newvalue);
// Remove the emitted symbol from the current input.
symbols.reset();
symbols.write(c);
// If the buffer is too big, flush to avoid blowing the heap.
if (buffer.size() > MAX_BUFFER_SIZE)
flush();
}
}
}
/* (non-Javadoc)
* @see java.io.OutputStream#flush()
*/
public void flush() throws IOException {
// Do nothing if the code buffer is empty.
if (buffer.isEmpty()) return;
// Use MSB-First packing order.
//
// Collect codes until aligned on a byte boundary.
int codebits = 0;
final LinkedList<Code> codes = new LinkedList<Code>();
while (buffer.size() > 0) {
final Code c = buffer.remove();
codes.add(c);
codebits += c.bits;
// If aligned on a byte boundary output the collected codes and
// remove them from the codes buffer.
if (codebits % 8 == 0) {
out.write(codesToBytes(codes));
codes.clear();
codebits = 0;
}
}
// If the stream is closed then output the remaining codes.
if (finish)
out.write(codesToBytes(codes));
// Otherwise stick them back onto the code buffer for next time.
else
buffer.addAll(codes);
}
/**
* Convert an ordered list of codes (which may or may not be byte-aligned)
* into their MSB-first byte representation.
*
* @param codes an ordered list of codes.
* @return the MSB-first byte representation of the codes.
*/
private static byte[] codesToBytes(final LinkedList<Code> codes) {
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
byte b = 0;
int available = Byte.SIZE;
while (codes.size() > 0) {
// Write the current code bits MSB-first.
final Code code = codes.remove();
int bits = code.bits;
while (bits > 0) {
// If the code has more bits than available, shift right to get
// the most significant bits. This finishes off the current
// byte.
if (bits > available) {
int msbits = code.value;
msbits >>>= bits - available;
b |= (msbits & 0xff);
// The current byte is finished so write it out.
bytes.write(b);
// We've written 'available' bits of the current code. The
// next byte is completely available so reset the values.
bits -= available;
available = Byte.SIZE;
b = 0;
}
// If the code has less then or equal bits available, shift
// left to pack against the previous bits.
else if (bits <= available) {
// First shift left to erase the most significant bits then
// shift right to start at the correct offset.
int msbits = code.value;
msbits <<= available - bits;
msbits &= 0xff;
msbits >>>= Byte.SIZE - available;
b |= (msbits & 0xff);
// We've written 'bits' bits into the current byte. There
// are no more bits to write for the current code.
available -= bits;
bits = 0;
// If this finished the current byte then write it and
// reset the values.
if (available == 0) {
bytes.write(b);
available = Byte.SIZE;
b = 0;
}
}
}
}
// If the number of bits available in the current byte is less than the
// size of a byte then the current byte still needs to be written.
if (available < Byte.SIZE)
bytes.write(b);
return bytes.toByteArray();
}
/** Output stream. */
private final OutputStream out;
/** The dictionary of codes keyed off bytes. */
private final Map<Key,Integer> dictionary = new HashMap<Key,Integer>(INITIAL_DICTIONARY);
/** Working symbols. */
private final ByteArrayOutputStream symbols = new ByteArrayOutputStream();
/** Current bit length. */
private int bits = Byte.SIZE;
/** Buffered codes pending write. */
private final LinkedList<Code> buffer = new LinkedList<Code>();
/** Finish called. */
private boolean finish = false;
/** Stream closed. */
private boolean closed = false;
}
| 9,894 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/JsonMslTokenizer.java | /**
* Copyright (c) 2015-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslInternalException;
/**
* <p>Create a new {@link MslTokenizer} that parses JSON-encoded MSL
* messages.</p>
*
* <p>This implementation is backed by {@code org.json}.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class JsonMslTokenizer extends MslTokenizer {
/**
* <p>Create a new JSON MSL tokenzier that will read data off the provided
* input stream.</p>
*
* @param encoder MSL encoder factory.
* @param source JSON input stream.
*/
public JsonMslTokenizer(final MslEncoderFactory encoder, final InputStream source) {
this.encoder = encoder;
// We cannot use the standard {@code InputStreamReader} to support
// UTF-8 decoding because it makes use of {@code StreamDecoder} which
// will read {@code StreamDecoder.DEFAULT_BYTE_BUFFER_SIZE} bytes by
// default, and enforces a minimum of
// {@code StreamDecoder.MIN_BYTE_BUFFER_SIZE}. This will consume extra
// bytes and prevent the input stream from being used for future MSL
// messages.
//
// {@code JSONTokener} will consume one character at a time, but will
// default to a {@code BufferedReader} with the default buffer size if
// an {@code InputStream} or {@code Reader} is provided that does not
// support mark, which will also consume extra bytes and prevent reuse
// of the input stream.
//
// Ensure none of that occurs and that only the minimum number of bytes
// are consumed by explicitly using the {@code ThriftyUtf8Reader} which
// reads characters one at a time and also supports mark.
//
// Make sure we're trying to parse UTF-8 data.
if (StandardCharsets.UTF_8 != MslConstants.DEFAULT_CHARSET)
throw new MslInternalException("Charset " + MslConstants.DEFAULT_CHARSET + " unsupported.");
final Reader reader = new ThriftyUtf8Reader(source);
this.tokenizer = new JSONTokener(reader);
}
/* (non-Javadoc)
* @see com.netflix.msl.io.MslTokenizer#next(int)
*/
@Override
protected MslObject next(final int timeout) throws MslEncoderException {
try {
if (!tokenizer.more())
return null;
final Object o = tokenizer.nextValue();
if (o instanceof JSONObject)
return new JsonMslObject(encoder, (JSONObject)o);
throw new MslEncoderException("JSON value is not a JSON object.");
} catch (final JSONException e) {
throw new MslEncoderException("JSON syntax error.", e);
}
}
/** MSL encoder factory. */
private final MslEncoderFactory encoder;
/** JSON tokenizer. */
private final JSONTokener tokenizer;
}
| 9,895 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/io/MslArray.java | /**
* Copyright (c) 2015-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.io;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* <p>A {@code MslArray} is an ordered sequence of values.</p>
*
* <p>The values can be any of these types: <code>Boolean</code>,
* <code>Byte[]</code> <code>MslArray</code>, <code>MslObject</code>,
* <code>Number</code>, or <code>String</code>. <code>Enum</code> is also
* accepted and will be converted to a <code>String</code> using its
* {@code name()} method.</p>
*
* <p>The generic <code>get()</code> and <code>opt()</code> methods return an
* object, which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and type
* coercion for you. The opt methods differ from the get methods in that they
* do not throw. Instead, they return a specified value, such as null.</p>
*
* <p>The <code>put</code> methods add or replace values in an object.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class MslArray {
/**
* Create a new empty {@code MslArray}.
*/
public MslArray() {
}
/**
* Create a new {@code MslArray} from the given object array.
*
* @param array the array of values. May be {@code null}.
* @throws IllegalArgumentException if one of the values is of an
* unsupported type.
*/
public MslArray(final Object[] array) {
if (array != null) {
for (final Object o : array)
put(-1, o);
}
}
/**
* Create a new {@code MslArray} from the given collection.
*
* @param collection the collection of values. May be {@code null}.
* @throws IllegalArgumentException if one of the values is of an
* unsupported type.
*/
public MslArray(final Collection<?> collection) {
if (collection != null) {
for (final Object o : collection)
put(-1, o);
}
}
/** Object list. */
private final List<Object> list = new ArrayList<Object>();
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
@SuppressWarnings("unchecked")
public Object get(final int index) throws MslEncoderException {
if (index < 0 || index >= list.size())
throw new ArrayIndexOutOfBoundsException("MslArray[" + index + "] is negative or exceeds array length.");
final Object o = list.get(index);
if (o == null)
throw new MslEncoderException("MslArray[" + index + "] is null.");
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
return o;
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public boolean getBoolean(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof Boolean)
return (Boolean)o;
throw new MslEncoderException("MslArray[" + index + "] is not a boolean.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public byte[] getBytes(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof byte[])
return (byte[])o;
throw new MslEncoderException("MslArray[" + index + "] is not binary data.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public double getDouble(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof Number)
return ((Number)o).doubleValue();
throw new MslEncoderException("MslArray[" + index + "] is not a number.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public int getInt(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof Number)
return ((Number)o).intValue();
throw new MslEncoderException("MslArray[" + index + "] is not a number.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
@SuppressWarnings("unchecked")
public MslArray getMslArray(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof MslArray)
return (MslArray)o;
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
throw new MslEncoderException("MslArray[" + index + "] is not a MslArray.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @param encoder the MSL encoder factory.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public MslObject getMslObject(final int index, final MslEncoderFactory encoder) throws MslEncoderException {
final Object o = get(index);
if (o instanceof MslObject)
return (MslObject)o;
/* FIXME: How should we handle MslEncodable?
if (o instanceof MslEncodable)
return ((MslEncodable)o).toMslObject(encoder);
*/
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof byte[]) {
try {
return encoder.parseObject((byte[])o);
} catch (final MslEncoderException e) {
throw new MslEncoderException("MslObject[" + index + "] is not a MslObject.", e);
}
}
throw new MslEncoderException("MslArray[" + index + "] is not a MslObject.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public long getLong(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof Number)
return ((Number)o).longValue();
throw new MslEncoderException("MslArray[" + index + "] is not a number.");
}
/**
* Return the value associated with an index.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
* @throws MslEncoderException if the value is {@code null} or of the wrong
* type.
*/
public String getString(final int index) throws MslEncoderException {
final Object o = get(index);
if (o instanceof String)
return (String)o;
throw new MslEncoderException("MslArray[" + index + "] is not a string.");
}
/**
* Return true if the value at the index is {@code null}.
*
* @param index the index.
* @return true if the value is null.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public boolean isNull(final int index) {
if (index < 0 || index >= list.size())
throw new ArrayIndexOutOfBoundsException("MslArray[" + index + "] is negative or exceeds array length.");
return list.get(index) == null;
}
/**
* Return the number of elements in the array, including {@code null}
* values.
*
* @return the array size.
*/
public int size() {
return list.size();
}
/**
* Return the value at the index, which may be {@code null}. {@code null}
* will also be returned if the value is an unsupported type.
*
* @param index the index.
* @return the value. May be {@code null}.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
@SuppressWarnings("unchecked")
public Object opt(final int index) {
if (index < 0 || index >= list.size())
throw new ArrayIndexOutOfBoundsException("MslArray[" + index + "] is negative or exceeds array length.");
final Object o = list.get(index);
try {
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
} catch (final IllegalArgumentException e) {
return null;
}
return o;
}
/**
* Return the value at the index or {@code false} if the value is not of
* the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public boolean optBoolean(final int index) {
return optBoolean(index, false);
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public boolean optBoolean(final int index, final boolean defaultValue) {
final Object o = opt(index);
if (o instanceof Boolean)
return (Boolean)o;
return defaultValue;
}
/**
* Return the value at the index or an empty byte array if the value is not
* of the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public byte[] optBytes(final int index) {
return optBytes(index, new byte[0]);
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public byte[] optBytes(final int index, final byte[] defaultValue) {
final Object o = opt(index);
if (o instanceof byte[])
return (byte[])o;
return defaultValue;
}
/**
* Return the value at the index or {@code NaN} if the value is not of
* the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public double optDouble(final int index) {
return optDouble(index, Double.NaN);
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public double optDouble(final int index, final double defaultValue) {
final Object o = opt(index);
if (o instanceof Number)
return ((Number)o).doubleValue();
return defaultValue;
}
/**
* Return the value at the index or zero if the value is not of
* the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public int optInt(final int index) {
return optInt(index, 0);
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public int optInt(final int index, final int defaultValue) {
final Object o = opt(index);
if (o instanceof Number)
return ((Number)o).intValue();
return defaultValue;
}
/**
* Return the {@code MslArray} at the index or {@code null} if the value
* is not of the correct type.
*
* @param index the index.
* @return the {@code MslArray} or {@code null}.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
@SuppressWarnings("unchecked")
public MslArray optMslArray(final int index) {
final Object o = opt(index);
if (o instanceof MslArray)
return (MslArray)o;
if (o instanceof Collection)
return new MslArray((Collection<Object>)o);
if (o instanceof Object[])
return new MslArray((Object[])o);
return null;
}
/**
* Return the {@code MslObject} at the index or {@code null} if the value
* is not of the correct type.
*
* @param index the index.
* @param encoder the MSL encoder factory.
* @return the {@code MslObject} or {@code null}.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public MslObject optMslObject(final int index, final MslEncoderFactory encoder) {
final Object o = opt(index);
if (o instanceof MslObject)
return (MslObject)o;
/* FIXME: How should we handle MslEncodable?
if (o instanceof MslEncodable) {
try {
return ((MslEncodable)o).toMslObject(encoder);
} catch (final MslEncoderException e) {
// Drop through.
}
}
*/
try {
if (o instanceof Map)
return new MslObject((Map<?,?>)o);
} catch (final IllegalArgumentException e) {
return null;
}
if (o instanceof byte[]) {
try {
return encoder.parseObject((byte[])o);
} catch (final MslEncoderException e) {
return null;
}
}
return null;
}
/**
* Return the value at the index or zero if the value is not of
* the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public long optLong(final int index) {
return optLong(index, 0);
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public long optLong(final int index, final long defaultValue) {
final Object o = opt(index);
if (o instanceof Number)
return ((Number)o).longValue();
return defaultValue;
}
/**
* Return the value at the index or the empty string if the value is not
* of the correct type.
*
* @param index the index.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public String optString(final int index) {
return optString(index, "");
}
/**
* Return the value at the index or the default value if the value is not
* of the correct type.
*
* @param index the index.
* @param defaultValue the default value.
* @return the value.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public String optString(final int index, final String defaultValue) {
final Object o = opt(index);
if (o instanceof String)
return (String)o;
return defaultValue;
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
* @throws IllegalArgumentException if the value is of an unsupported type.
*/
@SuppressWarnings("unchecked")
public MslArray put(final int index, final Object value) {
if (index < -1)
throw new ArrayIndexOutOfBoundsException("MslArray[" + index + "] is negative.");
// Convert appropriate values to MSL objects or MSL arrays.
final Object element;
if (value instanceof Boolean ||
value instanceof byte[] ||
value instanceof Number ||
value instanceof MslObject ||
value instanceof MslArray ||
value instanceof String ||
value instanceof MslEncodable)
{
element = value;
}
else if (value instanceof Map) {
element = new MslObject((Map<?,?>)value);
} else if (value instanceof Collection) {
element = new MslArray((Collection<Object>)value);
} else if (value instanceof Object[]) {
element = new MslArray((Object[])value);
} else if (value instanceof Enum) {
element = ((Enum<?>)value).name();
} else if (value == null) {
element = null;
} else {
throw new IllegalArgumentException("Value [" + value.getClass() + "] is an unsupported type.");
}
// Fill with null elements as necessary.
for (int i = list.size(); i < index; ++i)
list.add(null);
// Append if requested.
if (index == -1 || index == list.size()) {
list.add(element);
return this;
}
// Otherwise replace.
list.set(index, element);
return this;
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putBoolean(final int index, final Boolean value) {
return put(index, value);
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putBytes(final int index, final byte[] value) {
return put(index, value);
}
/**
* Put or replace a value in the {@code MslArray} at the index. The
* collection of elements will be transformed into a {@code MslArray}. If
* the index exceeds the length, null elements will be added as necessary.
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
* @throws IllegalArgumentException if the value contains an unsupported
* type.
*/
public MslArray putCollection(final int index, final Collection<Object> value) {
return put(index, value);
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putDouble(final int index, final Double value) {
return put(index, value);
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putInt(final int index, final Integer value) {
return put(index, value);
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putLong(final int index, final Long value) {
return put(index, value);
}
/**
* Put or replace a value in the {@code MslArray} at the index. The map of
* strings onto objects will be transformed into a {@code MslObject}. If
* the index exceeds the length, null elements will be added as necessary.
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
* @throws IllegalArgumentException if one of the values is an unsupported
* type.
*/
public MslArray putMap(final int index, final Map<String,Object> value) {
return put(index, new MslObject(value));
}
/**
* <p>Put or replace a value in the {@code MslArray} at the index. If the
* index exceeds the length, null elements will be added as necessary.</p>
*
* <p>This method will call {@link #put(int, Object)}.</p>
*
* @param index the index. -1 for the end of the array.
* @param value the value. May be {@code null}.
* @return this.
* @throws ArrayIndexOutOfBoundsException if the index is less than -1.
*/
public MslArray putString(final int index, final String value) {
return put(index, value);
}
/**
* Remove an element at the index. This decreases the length by one.
*
* @param index the index. -1 for the end of the array.
* @return the removed value. May be {@code null}.
* @throws ArrayIndexOutOfBoundsException if the index is negative or
* exceeds the number of elements in the array.
*/
public Object remove(final int index) {
if (index < -1 || index >= list.size())
throw new ArrayIndexOutOfBoundsException("MslArray[" + index + "] is negative or exceeds array length.");
final int i = (index == -1) ? list.size() - 1 : index;
final Object value = opt(i);
list.remove(i);
return value;
}
/**
* Return an unmodifiable collection of the {@code MslArray} contents.
*
* @return the unmodifiable collection of {@code MslArray} contents.
*/
public Collection<Object> getCollection() {
return Collections.unmodifiableList(list);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (!(obj instanceof MslArray)) return false;
final MslArray that = (MslArray)obj;
try {
return MslEncoderUtils.equalArrays(this, that);
} catch (final MslEncoderException e) {
return false;
}
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return MslEncoderUtils.hashArray(this);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// This is based on the org.json {@code JSONArray.write()} code.
final StringBuilder sb = new StringBuilder();
boolean commanate = false;
final int length = list.size();
sb.append('[');
if (length == 1) {
sb.append(MslEncoderFactory.stringify(this.list.get(0)));
} else if (length != 0) {
for (int i = 0; i < length; i += 1) {
if (commanate) {
sb.append(',');
}
sb.append(MslEncoderFactory.stringify(list.get(i)));
commanate = true;
}
}
sb.append(']');
return sb.toString();
}
}
| 9,896 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/userauth/UserAuthenticationScheme.java | /**
* Copyright (c) 2012-2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.userauth;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* <p>User authentication schemes.</p>
*
* <p>The scheme name is used to uniquely identify user authentication
* schemes.</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class UserAuthenticationScheme {
/** Map of names onto schemes. */
private static Map<String,UserAuthenticationScheme> schemes = new HashMap<String,UserAuthenticationScheme>();
/** Email/password. */
public static final UserAuthenticationScheme EMAIL_PASSWORD = new UserAuthenticationScheme("EMAIL_PASSWORD");
/** User ID token. */
public static final UserAuthenticationScheme USER_ID_TOKEN = new UserAuthenticationScheme("USER_ID_TOKEN");
/**
* Define a user authentication scheme with the specified name.
*
* @param name the user authentication scheme name.
*/
protected UserAuthenticationScheme(final String name) {
this.name = name;
// Add this scheme to the map.
synchronized (schemes) {
schemes.put(name, this);
}
}
/**
* @param name the entity authentication scheme name.
* @return the scheme identified by the specified name or {@code null} if
* there is none.
*/
public static UserAuthenticationScheme getScheme(final String name) {
return schemes.get(name);
}
/**
* @return all known user authentication schemes.
*/
public static Collection<UserAuthenticationScheme> values() {
return schemes.values();
}
/**
* @return the scheme identifier.
*/
public String name() {
return name;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return name();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return name.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof UserAuthenticationScheme)) return false;
final UserAuthenticationScheme that = (UserAuthenticationScheme)obj;
return this.name.equals(that.name);
}
/** Scheme name. */
private final String name;
}
| 9,897 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/userauth/EmailPasswordAuthenticationFactory.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.userauth;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.MslInternalException;
import com.netflix.msl.MslUserAuthException;
import com.netflix.msl.io.MslObject;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.util.AuthenticationUtils;
import com.netflix.msl.util.MslContext;
/**
* Email/password-based user authentication factory.
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class EmailPasswordAuthenticationFactory extends UserAuthenticationFactory {
/**
* Construct a new email/password-based user authentication factory.
*
* @param store email/password store.
* @param authutils authentication utilities.
*/
public EmailPasswordAuthenticationFactory(final EmailPasswordStore store, final AuthenticationUtils authutils) {
super(UserAuthenticationScheme.EMAIL_PASSWORD);
this.store = store;
this.authutils = authutils;
}
/* (non-Javadoc)
* @see com.netflix.msl.userauth.UserAuthenticationFactory#createData(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.io.MslObject)
*/
@Override
public UserAuthenticationData createData(final MslContext ctx, final MasterToken masterToken, final MslObject userAuthMo) throws MslEncodingException {
return new EmailPasswordAuthenticationData(userAuthMo);
}
/* (non-Javadoc)
* @see com.netflix.msl.userauth.UserAuthenticationFactory#authenticate(com.netflix.msl.util.MslContext, java.lang.String, com.netflix.msl.userauth.UserAuthenticationData, com.netflix.msl.tokens.UserIdToken)
*/
@Override
public MslUser authenticate(final MslContext ctx, final String identity, final UserAuthenticationData data, final UserIdToken userIdToken) throws MslUserAuthException {
// Make sure we have the right kind of user authentication data.
if (!(data instanceof EmailPasswordAuthenticationData))
throw new MslInternalException("Incorrect authentication data type " + data.getClass().getName() + ".");
final EmailPasswordAuthenticationData epad = (EmailPasswordAuthenticationData)data;
// Verify the scheme is permitted.
if(!authutils.isSchemePermitted(identity, this.getScheme()))
throw new MslUserAuthException(MslError.USERAUTH_ENTITY_INCORRECT_DATA, "Authentication scheme " + this.getScheme() + " not permitted for entity " + identity + ".").setUserAuthenticationData(data);
// Extract and check email and password values.
final String epadEmail = epad.getEmail();
final String epadPassword = epad.getPassword();
if (epadEmail == null || epadPassword == null)
throw new MslUserAuthException(MslError.EMAILPASSWORD_BLANK).setUserAuthenticationData(epad);
final String email = epadEmail.trim();
final String password = epadPassword.trim();
if (email.isEmpty() || password.isEmpty())
throw new MslUserAuthException(MslError.EMAILPASSWORD_BLANK).setUserAuthenticationData(epad);
// Authenticate the user.
final MslUser user = store.isUser(email, password);
if (user == null)
throw new MslUserAuthException(MslError.EMAILPASSWORD_INCORRECT).setUserAuthenticationData(epad);
// Verify the scheme is still permitted.
if (!authutils.isSchemePermitted(identity, user, this.getScheme()))
throw new MslUserAuthException(MslError.USERAUTH_ENTITYUSER_INCORRECT_DATA, "Authentication scheme " + this.getScheme() + " not permitted for entity " + identity + ".").setUserAuthenticationData(epad);
// If a user ID token was provided validate the user identities.
if (userIdToken != null) {
final MslUser uitUser = userIdToken.getUser();
if (!user.equals(uitUser))
throw new MslUserAuthException(MslError.USERIDTOKEN_USERAUTH_DATA_MISMATCH, "uad user " + user + "; uit user " + uitUser).setUserAuthenticationData(epad);
}
// Return the user.
return user;
}
/** Email/password store. */
private final EmailPasswordStore store;
/** Authentication utilities. */
private final AuthenticationUtils authutils;
}
| 9,898 |
0 | Create_ds/msl/core/src/main/java/com/netflix/msl | Create_ds/msl/core/src/main/java/com/netflix/msl/userauth/EmailPasswordAuthenticationData.java | /**
* Copyright (c) 2012-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.userauth;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslError;
import com.netflix.msl.io.MslEncoderException;
import com.netflix.msl.io.MslEncoderFactory;
import com.netflix.msl.io.MslEncoderFormat;
import com.netflix.msl.io.MslObject;
/**
* <p>Email/password-based user authentication data.</p>
*
* <p>
* {@code {
* "#mandatory" : [ "email", "password" ],
* "email" : "string",
* "password" : "string"
* }} where:
* <ul>
* <li>{@code email} is the user email address</li>
* <li>{@code password} is the user password</li>
* </ul></p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public class EmailPasswordAuthenticationData extends UserAuthenticationData {
/** Key email. */
private static final String KEY_EMAIL = "email";
/** Key password. */
private static final String KEY_PASSWORD = "password";
/**
* Construct a new email/password authentication data instance from the
* specified email and password.
*
* @param email the email address.
* @param password the password.
*/
public EmailPasswordAuthenticationData(final String email, final String password) {
super(UserAuthenticationScheme.EMAIL_PASSWORD);
this.email = email;
this.password = password;
}
/**
* Construct a new email/password authentication data instance from the
* provided MSL object.
*
* @param emailPasswordAuthMo the MSL object.
* @throws MslEncodingException if there is an error parsing the data.
*/
public EmailPasswordAuthenticationData(final MslObject emailPasswordAuthMo) throws MslEncodingException {
super(UserAuthenticationScheme.EMAIL_PASSWORD);
try {
email = emailPasswordAuthMo.getString(KEY_EMAIL);
password = emailPasswordAuthMo.getString(KEY_PASSWORD);
} catch (final MslEncoderException e) {
throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "email/password authdata " + emailPasswordAuthMo, e);
}
}
/**
* @return the email address.
*/
public String getEmail() {
return email;
}
/**
* @return the password.
*/
public String getPassword() {
return password;
}
@Override
public MslObject getAuthData(final MslEncoderFactory encoder, final MslEncoderFormat format) {
final MslObject mo = encoder.createObject();
mo.put(KEY_EMAIL, email);
mo.put(KEY_PASSWORD, password);
return mo;
}
/* (non-Javadoc)
* @see com.netflix.msl.userauth.UserAuthenticationData#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof EmailPasswordAuthenticationData)) return false;
final EmailPasswordAuthenticationData that = (EmailPasswordAuthenticationData)obj;
return super.equals(obj) && email.equals(that.email) && password.equals(that.password);
}
/* (non-Javadoc)
* @see com.netflix.msl.userauth.UserAuthenticationData#hashCode()
*/
@Override
public int hashCode() {
return super.hashCode() ^ email.hashCode() ^ password.hashCode();
}
/** Email. */
private final String email;
/** Password. */
private final String password;
}
| 9,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.