--- a/security/nss/.gitignore
+++ b/security/nss/.gitignore
@@ -12,9 +12,8 @@ out/*
GPATH
GRTAGS
GTAGS
#*
.#*
.ycm_extra_conf.py*
fuzz/libFuzzer/*
fuzz/corpus
-fuzz/out
--- a/security/nss/Makefile
+++ b/security/nss/Makefile
@@ -91,16 +91,25 @@ endif
ifdef CCC
NSPR_CONFIGURE_ENV += CXX=$(CCC)
endif
# Remove -arch definitions. NSPR can't handle that.
NSPR_CONFIGURE_ENV := $(filter-out -arch x86_64,$(NSPR_CONFIGURE_ENV))
NSPR_CONFIGURE_ENV := $(filter-out -arch i386,$(NSPR_CONFIGURE_ENV))
NSPR_CONFIGURE_ENV := $(filter-out -arch ppc,$(NSPR_CONFIGURE_ENV))
+ifdef SANITIZER_CFLAGS
+ifdef BUILD_OPT
+NSPR_CONFIGURE_OPTS += --enable-debug-symbols
+endif
+NSPR_CONFIGURE_ENV += CFLAGS='$(SANITIZER_CFLAGS)' \
+ CXXFLAGS='$(SANITIZER_CFLAGS)' \
+ LDFLAGS='$(SANITIZER_LDFLAGS)'
+endif
+
#
# Some pwd commands on Windows (for example, the pwd
# command in Cygwin) return a pathname that begins
# with a (forward) slash. When such a pathname is
# passed to Windows build tools (for example, cl), it
# is mistaken as a command-line option. If that is the case,
# we use a relative pathname as NSPR's prefix on Windows.
#
--- a/security/nss/TAG-INFO
+++ b/security/nss/TAG-INFO
@@ -1,1 +1,1 @@
-0750d7a0402b
+NSS_3_28_2_RTM
--- a/security/nss/automation/buildbot-slave/build.sh
+++ b/security/nss/automation/buildbot-slave/build.sh
@@ -238,63 +238,29 @@ test_jss()
grep FAIL ${LOG_TMP}
[ $? -eq 1 ] || RET=1
print_result "JSS - tests - ${BITS} bits - ${OPT}" ${RET} 0
return ${RET}
}
-create_objdir_dist_link()
-{
- # compute relevant 'dist' OBJDIR_NAME subdirectory names for JSS and NSS
- OS_TARGET=`uname -s`
- OS_RELEASE=`uname -r | sed 's/-.*//' | sed 's/-.*//' | cut -d . -f1,2`
- CPU_TAG=_`uname -m`
- # OBJDIR_NAME_COMPILER appears to be defined for NSS but not JSS
- OBJDIR_NAME_COMPILER=_cc
- LIBC_TAG=_glibc
- IMPL_STRATEGY=_PTH
- if [ "${RUN_BITS}" = "64" ]; then
- OBJDIR_TAG=_${RUN_BITS}_${RUN_OPT}.OBJ
- else
- OBJDIR_TAG=_${RUN_OPT}.OBJ
- fi
-
- # define NSS_OBJDIR_NAME
- NSS_OBJDIR_NAME=${OS_TARGET}${OS_RELEASE}${CPU_TAG}${OBJDIR_NAME_COMPILER}
- NSS_OBJDIR_NAME=${NSS_OBJDIR_NAME}${LIBC_TAG}${IMPL_STRATEGY}${OBJDIR_TAG}
- print_log "create_objdir_dist_link(): NSS_OBJDIR_NAME='${NSS_OBJDIR_NAME}'"
-
- # define JSS_OBJDIR_NAME
- JSS_OBJDIR_NAME=${OS_TARGET}${OS_RELEASE}${CPU_TAG}
- JSS_OBJDIR_NAME=${JSS_OBJDIR_NAME}${LIBC_TAG}${IMPL_STRATEGY}${OBJDIR_TAG}
- print_log "create_objdir_dist_link(): JSS_OBJDIR_NAME='${JSS_OBJDIR_NAME}'"
-
- if [ -e "${HGDIR}/dist/${NSS_OBJDIR_NAME}" ]; then
- SOURCE=${HGDIR}/dist/${NSS_OBJDIR_NAME}
- TARGET=${HGDIR}/dist/${JSS_OBJDIR_NAME}
- ln -s ${SOURCE} ${TARGET} >/dev/null 2>&1
- fi
-}
-
build_and_test()
{
if [ -n "${BUILD_NSS}" ]; then
build_nss
[ $? -eq 0 ] || return 1
fi
if [ -n "${TEST_NSS}" ]; then
test_nss
[ $? -eq 0 ] || return 1
fi
if [ -n "${BUILD_JSS}" ]; then
- create_objdir_dist_link
build_jss
[ $? -eq 0 ] || return 1
fi
if [ -n "${TEST_JSS}" ]; then
test_jss
[ $? -eq 0 ] || return 1
fi
deleted file mode 100755
--- a/security/nss/automation/ossfuzz/build.sh
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/bin/bash -eu
-#
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-#
-################################################################################
-
-# List of targets disabled for oss-fuzz.
-declare -A disabled=([pkcs8]=1)
-
-# Build the library.
-CXX="$CXX -stdlib=libc++" LDFLAGS="$CFLAGS" \
- ./build.sh -c -v --fuzz=oss --fuzz=tls --disable-tests
-
-# Find fuzzing targets.
-for fuzzer in $(find ../dist/Debug/bin -name "nssfuzz-*" -printf "%f\n"); do
- name=${fuzzer:8}
- [ -n "${disabled[$name]:-}" ] && continue;
-
- # Copy the binary.
- cp ../dist/Debug/bin/$fuzzer $OUT/$name
-
- # Zip and copy the corpus, if any.
- if [ -d "$SRC/nss-corpus/$name" ]; then
- zip $OUT/${name}_seed_corpus.zip $SRC/nss-corpus/$name/*
- else
- zip $OUT/${name}_seed_corpus.zip $SRC/nss-corpus/*/*
- fi
-done
old mode 100755
new mode 100644
deleted file mode 100644
--- a/security/nss/automation/taskcluster/docker-aarch64/Dockerfile
+++ /dev/null
@@ -1,27 +0,0 @@
-FROM aarch64/ubuntu:xenial-20161213
-MAINTAINER Franziskus Kiefer <franziskuskiefer@gmail.com>
-
-RUN useradd -d /home/worker -s /bin/bash -m worker
-WORKDIR /home/worker
-
-# Add build and test scripts.
-ADD bin /home/worker/bin
-RUN chmod +x /home/worker/bin/*
-
-# Install dependencies.
-ADD setup.sh /tmp/setup.sh
-RUN bash /tmp/setup.sh
-
-# Env variables.
-ENV HOME /home/worker
-ENV SHELL /bin/bash
-ENV USER worker
-ENV LOGNAME worker
-ENV HOSTNAME taskcluster-worker
-ENV LANG en_US.UTF-8
-ENV LC_ALL en_US.UTF-8
-ENV HOST localhost
-ENV DOMSUF localdomain
-
-# Set a default command for debugging.
-CMD ["/bin/bash", "--login"]
deleted file mode 100755
--- a/security/nss/automation/taskcluster/docker-aarch64/bin/checkout.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/env bash
-
-set -v -e -x
-
-if [ $(id -u) = 0 ]; then
- # Drop privileges by re-running this script.
- exec su worker $0
-fi
-
-# Default values for testing.
-REVISION=${NSS_HEAD_REVISION:-default}
-REPOSITORY=${NSS_HEAD_REPOSITORY:-https://hg.mozilla.org/projects/nss}
-
-# Clone NSS.
-for i in 0 2 5; do
- sleep $i
- hg clone -r $REVISION $REPOSITORY nss && exit 0
- rm -rf nss
-done
-exit 1
deleted file mode 100755
--- a/security/nss/automation/taskcluster/docker-aarch64/setup.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/usr/bin/env bash
-
-set -v -e -x
-
-export DEBIAN_FRONTEND=noninteractive
-
-# Update.
-apt-get -y update
-apt-get -y dist-upgrade
-
-apt_packages=()
-apt_packages+=('build-essential')
-apt_packages+=('ca-certificates')
-apt_packages+=('curl')
-apt_packages+=('zlib1g-dev')
-apt_packages+=('gyp')
-apt_packages+=('ninja-build')
-apt_packages+=('mercurial')
-
-# Install packages.
-apt-get install -y --no-install-recommends ${apt_packages[@]}
-
-locale-gen en_US.UTF-8
-dpkg-reconfigure locales
-
-# Cleanup.
-rm -rf ~/.ccache ~/.cache
-apt-get autoremove -y
-apt-get clean
-apt-get autoclean
-rm $0
deleted file mode 100644
--- a/security/nss/automation/taskcluster/docker-fuzz/Dockerfile
+++ /dev/null
@@ -1,33 +0,0 @@
-FROM ubuntu:16.04
-MAINTAINER Tim Taubert <ttaubert@mozilla.com>
-
-RUN useradd -d /home/worker -s /bin/bash -m worker
-WORKDIR /home/worker
-
-# Add build and test scripts.
-ADD bin /home/worker/bin
-RUN chmod +x /home/worker/bin/*
-
-# Install dependencies.
-ADD setup.sh /tmp/setup.sh
-RUN bash /tmp/setup.sh
-
-# Change user.
-USER worker
-
-# Env variables.
-ENV HOME /home/worker
-ENV SHELL /bin/bash
-ENV USER worker
-ENV LOGNAME worker
-ENV HOSTNAME taskcluster-worker
-ENV LANG en_US.UTF-8
-ENV LC_ALL en_US.UTF-8
-ENV HOST localhost
-ENV DOMSUF localdomain
-
-# LLVM 4.0
-ENV PATH "${PATH}:/home/worker/third_party/llvm-build/Release+Asserts/bin/"
-
-# Set a default command for debugging.
-CMD ["/bin/bash", "--login"]
deleted file mode 100644
--- a/security/nss/automation/taskcluster/docker-fuzz/bin/checkout.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/env bash
-
-set -v -e -x
-
-if [ $(id -u) = 0 ]; then
- # Drop privileges by re-running this script.
- exec su worker $0
-fi
-
-# Default values for testing.
-REVISION=${NSS_HEAD_REVISION:-default}
-REPOSITORY=${NSS_HEAD_REPOSITORY:-https://hg.mozilla.org/projects/nss}
-
-# Clone NSS.
-for i in 0 2 5; do
- sleep $i
- hg clone -r $REVISION $REPOSITORY nss && exit 0
- rm -rf nss
-done
-exit 1
deleted file mode 100644
--- a/security/nss/automation/taskcluster/docker-fuzz/setup.sh
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/usr/bin/env bash
-
-set -v -e -x
-
-# Update packages.
-export DEBIAN_FRONTEND=noninteractive
-apt-get -y update && apt-get -y upgrade
-
-# Need this to add keys for PPAs below.
-apt-get install -y --no-install-recommends apt-utils
-
-apt_packages=()
-apt_packages+=('build-essential')
-apt_packages+=('ca-certificates')
-apt_packages+=('curl')
-apt_packages+=('git')
-apt_packages+=('gyp')
-apt_packages+=('libssl-dev')
-apt_packages+=('ninja-build')
-apt_packages+=('pkg-config')
-apt_packages+=('zlib1g-dev')
-
-# Latest Mercurial.
-apt_packages+=('mercurial')
-apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 41BD8711B1F0EC2B0D85B91CF59CE3A8323293EE
-echo "deb http://ppa.launchpad.net/mercurial-ppa/releases/ubuntu xenial main" > /etc/apt/sources.list.d/mercurial.list
-
-# Install packages.
-apt-get -y update
-apt-get install -y --no-install-recommends ${apt_packages[@]}
-
-# Install LLVM/clang-4.0.
-mkdir clang-tmp
-git clone -n --depth 1 https://chromium.googlesource.com/chromium/src/tools/clang clang-tmp/clang
-git -C clang-tmp/clang checkout HEAD scripts/update.py
-clang-tmp/clang/scripts/update.py
-rm -fr clang-tmp
-
-# Generate locales.
-locale-gen en_US.UTF-8
-dpkg-reconfigure locales
-
-# Cleanup.
-rm -rf ~/.ccache ~/.cache
-apt-get autoremove -y
-apt-get clean
-apt-get autoclean
-rm $0
--- a/security/nss/automation/taskcluster/docker/Dockerfile
+++ b/security/nss/automation/taskcluster/docker/Dockerfile
@@ -7,27 +7,21 @@ WORKDIR /home/worker
# Add build and test scripts.
ADD bin /home/worker/bin
RUN chmod +x /home/worker/bin/*
# Install dependencies.
ADD setup.sh /tmp/setup.sh
RUN bash /tmp/setup.sh
-# Change user.
-USER worker
-
# Env variables.
ENV HOME /home/worker
ENV SHELL /bin/bash
ENV USER worker
ENV LOGNAME worker
ENV HOSTNAME taskcluster-worker
ENV LANG en_US.UTF-8
ENV LC_ALL en_US.UTF-8
ENV HOST localhost
ENV DOMSUF localdomain
-# Rust + Go
-ENV PATH "${PATH}:/home/worker/.cargo/bin/:/usr/lib/go-1.6/bin"
-
# Set a default command for debugging.
CMD ["/bin/bash", "--login"]
--- a/security/nss/automation/taskcluster/docker/setup.sh
+++ b/security/nss/automation/taskcluster/docker/setup.sh
@@ -44,21 +44,17 @@ echo "deb http://ppa.launchpad.net/ubunt
# Install packages.
apt-get -y update
apt-get install -y --no-install-recommends ${apt_packages[@]}
# 32-bit builds
ln -s /usr/include/x86_64-linux-gnu/zconf.h /usr/include
# Install clang-3.9 into /usr/local/.
-# FIXME: verify signature
-curl -L http://releases.llvm.org/3.9.0/clang+llvm-3.9.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz | tar xJv -C /usr/local --strip-components=1
-
-# Install latest Rust (stable).
-su worker -c "curl https://sh.rustup.rs -sSf | sh -s -- -y"
+curl -L http://llvm.org/releases/3.9.0/clang+llvm-3.9.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz | tar xJv -C /usr/local --strip-components=1
locale-gen en_US.UTF-8
dpkg-reconfigure locales
# Cleanup.
rm -rf ~/.ccache ~/.cache
apt-get autoremove -y
apt-get clean
--- a/security/nss/automation/taskcluster/graph/src/extend.js
+++ b/security/nss/automation/taskcluster/graph/src/extend.js
@@ -1,67 +1,62 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import merge from "./merge";
import * as queue from "./queue";
const LINUX_IMAGE = {name: "linux", path: "automation/taskcluster/docker"};
-const FUZZ_IMAGE = {name: "fuzz", path: "automation/taskcluster/docker-fuzz"};
const WINDOWS_CHECKOUT_CMD =
"bash -c \"hg clone -r $NSS_HEAD_REVISION $NSS_HEAD_REPOSITORY nss || " +
"(sleep 2; hg clone -r $NSS_HEAD_REVISION $NSS_HEAD_REPOSITORY nss) || " +
"(sleep 5; hg clone -r $NSS_HEAD_REVISION $NSS_HEAD_REPOSITORY nss)\"";
/*****************************************************************************/
queue.filter(task => {
if (task.group == "Builds") {
// Remove extra builds on {A,UB}San and ARM.
- if (task.collection == "asan" || task.collection == "arm-debug") {
+ if (task.collection == "asan" || task.collection == "arm-debug" ||
+ task.collection == "gyp-asan") {
return false;
}
// Remove extra builds w/o libpkix for non-linux64-debug.
if (task.symbol == "noLibpkix" &&
(task.platform != "linux64" || task.collection != "debug")) {
return false;
}
}
- if (task.tests == "bogo" || task.tests == "interop") {
- // No windows
+ if (task.tests == "bogo") {
+ // No BoGo tests on Windows.
if (task.platform == "windows2012-64") {
return false;
}
- // No ARM
+ // No BoGo tests on ARM.
if (task.collection == "arm-debug") {
return false;
}
}
- // Temporarily disable SSL tests on ARM.
- if (task.tests == "ssl" && task.collection == "arm-debug") {
- return false;
- }
-
// GYP builds with -Ddisable_libpkix=1 by default.
- if ((task.collection == "gyp" || task.collection == "asan") &&
+ if ((task.collection == "gyp" || task.collection == "gyp-asan") &&
task.tests == "chains") {
return false;
}
return true;
});
queue.map(task => {
- if (task.collection == "asan") {
+ if (task.collection == "asan" || task.collection == "gyp-asan") {
// CRMF and FIPS tests still leak, unfortunately.
if (task.tests == "crmf" || task.tests == "fips") {
task.env.ASAN_OPTIONS = "detect_leaks=0";
}
}
if (task.collection == "arm-debug") {
// These tests take quite some time on our poor ARM devices.
@@ -70,16 +65,20 @@ queue.map(task => {
}
}
// Windows is slow.
if (task.platform == "windows2012-64" && task.tests == "chains") {
task.maxRunTime = 7200;
}
+ // Enable TLS 1.3 for every task.
+ task.env = task.env || {};
+ task.env.NSS_ENABLE_TLS_1_3 = "1";
+
return task;
});
/*****************************************************************************/
export default async function main() {
await scheduleLinux("Linux 32 (opt)", {
env: {BUILD_OPT: "1"},
@@ -112,28 +111,45 @@ export default async function main() {
"-c",
"bin/checkout.sh && nss/automation/taskcluster/scripts/build_gyp.sh"
],
platform: "linux64",
collection: "gyp",
image: LINUX_IMAGE
});
- await scheduleLinux("Linux 64 (GYP, ASan, debug)", {
+ await scheduleLinux("Linux 64 (debug, gyp, asan, ubsan)", {
command: [
"/bin/bash",
"-c",
"bin/checkout.sh && nss/automation/taskcluster/scripts/build_gyp.sh -g -v --ubsan --asan"
],
env: {
+ ASAN_OPTIONS: "detect_odr_violation=0", // bug 1316276
+ UBSAN_OPTIONS: "print_stacktrace=1",
+ NSS_DISABLE_ARENA_FREE_LIST: "1",
+ NSS_DISABLE_UNLOAD: "1",
+ CC: "clang",
+ CCC: "clang++"
+ },
+ platform: "linux64",
+ collection: "gyp-asan",
+ image: LINUX_IMAGE
+ });
+
+ await scheduleLinux("Linux 64 (ASan, debug)", {
+ env: {
UBSAN_OPTIONS: "print_stacktrace=1",
NSS_DISABLE_ARENA_FREE_LIST: "1",
NSS_DISABLE_UNLOAD: "1",
CC: "clang",
CCC: "clang++",
+ USE_UBSAN: "1",
+ USE_ASAN: "1",
+ USE_64: "1"
},
platform: "linux64",
collection: "asan",
image: LINUX_IMAGE
});
await scheduleWindows("Windows 2012 64 (opt)", {
env: {BUILD_OPT: "1"}
@@ -235,50 +251,44 @@ async function scheduleLinux(name, base)
}));
queue.scheduleTask(merge(extra_base, {
name: `${name} w/ NSS_DISABLE_LIBPKIX=1`,
env: {NSS_DISABLE_LIBPKIX: "1"},
symbol: "noLibpkix"
}));
- queue.scheduleTask(merge(extra_base, {
- name: `${name} w/ modular builds`,
- env: {NSS_BUILD_MODULAR: "1"},
- symbol: "modular"
- }));
-
return queue.submit();
}
/*****************************************************************************/
async function scheduleFuzzing() {
let base = {
env: {
- ASAN_OPTIONS: "allocator_may_return_null=1",
+ // bug 1316276
+ ASAN_OPTIONS: "allocator_may_return_null=1:detect_odr_violation=0",
UBSAN_OPTIONS: "print_stacktrace=1",
NSS_DISABLE_ARENA_FREE_LIST: "1",
NSS_DISABLE_UNLOAD: "1",
CC: "clang",
CCC: "clang++"
},
- features: ["allowPtrace"],
platform: "linux64",
collection: "fuzz",
- image: FUZZ_IMAGE
+ image: LINUX_IMAGE
};
// Build base definition.
let build_base = merge({
command: [
"/bin/bash",
"-c",
"bin/checkout.sh && " +
- "nss/automation/taskcluster/scripts/build_gyp.sh -g -v --fuzz=tls"
+ "nss/automation/taskcluster/scripts/build_gyp.sh -g -v --fuzz"
],
artifacts: {
public: {
expires: 24 * 7,
type: "directory",
path: "/home/worker/artifacts"
}
},
@@ -304,63 +314,41 @@ async function scheduleFuzzing() {
tests: "ssl_gtests gtests",
cycle: "standard",
symbol: "Gtest",
kind: "test"
}));
queue.scheduleTask(merge(base, {
parent: task_build,
- name: "Hash",
+ name: "Cert",
command: [
"/bin/bash",
"-c",
"bin/checkout.sh && nss/automation/taskcluster/scripts/fuzz.sh " +
- "hash nss/fuzz/corpus/hash -max_total_time=300 -max_len=4096"
+ "cert nss/fuzz/corpus/cert -max_total_time=300"
],
- symbol: "Hash",
+ // Need a privileged docker container to remove this.
+ env: {ASAN_OPTIONS: "detect_leaks=0"},
+ symbol: "SCert",
kind: "test"
}));
queue.scheduleTask(merge(base, {
parent: task_build,
- name: "QuickDER",
+ name: "SPKI",
command: [
"/bin/bash",
"-c",
"bin/checkout.sh && nss/automation/taskcluster/scripts/fuzz.sh " +
- "quickder nss/fuzz/corpus/quickder -max_total_time=300 -max_len=10000"
- ],
- symbol: "QuickDER",
- kind: "test"
- }));
-
- queue.scheduleTask(merge(base, {
- parent: task_build,
- name: "MPI",
- command: [
- "/bin/bash",
- "-c",
- "bin/checkout.sh && nss/automation/taskcluster/scripts/fuzz.sh " +
- "mpi nss/fuzz/corpus/mpi -max_total_time=300 -max_len=2048"
+ "spki nss/fuzz/corpus/spki -max_total_time=300"
],
- symbol: "MPI",
- kind: "test"
- }));
-
- queue.scheduleTask(merge(base, {
- parent: task_build,
- name: "CertDN",
- command: [
- "/bin/bash",
- "-c",
- "bin/checkout.sh && nss/automation/taskcluster/scripts/fuzz.sh " +
- "certDN nss/fuzz/corpus/certDN -max_total_time=300 -max_len=4096"
- ],
- symbol: "CertDN",
+ // Need a privileged docker container to remove this.
+ env: {ASAN_OPTIONS: "detect_leaks=0"},
+ symbol: "SPKI",
kind: "test"
}));
return queue.submit();
}
/*****************************************************************************/
@@ -373,17 +361,17 @@ async function scheduleTestBuilds() {
};
// Build base definition.
let build = merge({
command: [
"/bin/bash",
"-c",
"bin/checkout.sh && " +
- "nss/automation/taskcluster/scripts/build_gyp.sh -g -v --test --ct-verif"
+ "nss/automation/taskcluster/scripts/build_gyp.sh -g -v --test"
],
artifacts: {
public: {
expires: 24 * 7,
type: "directory",
path: "/home/worker/artifacts"
}
},
@@ -482,19 +470,16 @@ function scheduleTests(task_build, task_
let no_cert_base = merge(test_base, {parent: task_build});
queue.scheduleTask(merge(no_cert_base, {
name: "Gtests", symbol: "Gtest", tests: "ssl_gtests gtests", cycle: "standard"
}));
queue.scheduleTask(merge(no_cert_base, {
name: "Bogo tests", symbol: "Bogo", tests: "bogo", cycle: "standard"
}));
queue.scheduleTask(merge(no_cert_base, {
- name: "Interop tests", symbol: "Interop", tests: "interop", cycle: "standard"
- }));
- queue.scheduleTask(merge(no_cert_base, {
name: "Chains tests", symbol: "Chains", tests: "chains"
}));
queue.scheduleTask(merge(no_cert_base, {
name: "Cipher tests", symbol: "Cipher", tests: "cipher"
}));
queue.scheduleTask(merge(no_cert_base, {
name: "EC tests", symbol: "EC", tests: "ec"
}));
--- a/security/nss/automation/taskcluster/graph/src/queue.js
+++ b/security/nss/automation/taskcluster/graph/src/queue.js
@@ -75,17 +75,16 @@ function parseTreeherder(def) {
if (def.tier) {
treeherder.tier = def.tier;
}
return treeherder;
}
function convertTask(def) {
- let scopes = [];
let dependencies = [];
let env = merge({
NSS_HEAD_REPOSITORY: process.env.NSS_HEAD_REPOSITORY,
NSS_HEAD_REVISION: process.env.NSS_HEAD_REVISION
}, def.env || {});
if (def.parent) {
@@ -106,34 +105,29 @@ function convertTask(def) {
command: def.command,
maxRunTime: def.maxRunTime || 3600
};
if (def.image) {
payload.image = def.image;
}
- if (def.artifacts) {
- payload.artifacts = parseArtifacts(def.artifacts);
+ if (def.features) {
+ payload.features = parseFeatures(def.features);
}
- if (def.features) {
- payload.features = parseFeatures(def.features);
-
- if (payload.features.allowPtrace) {
- scopes.push("docker-worker:feature:allowPtrace");
- }
+ if (def.artifacts) {
+ payload.artifacts = parseArtifacts(def.artifacts);
}
return {
provisionerId: def.provisioner || "aws-provisioner-v1",
workerType: def.workerType || "hg-worker",
schedulerId: "task-graph-scheduler",
- scopes,
created: fromNow(0),
deadline: fromNow(24),
dependencies,
routes: parseRoutes(def.routes || []),
metadata: {
name: def.name,
--- a/security/nss/automation/taskcluster/graph/src/try_syntax.js
+++ b/security/nss/automation/taskcluster/graph/src/try_syntax.js
@@ -18,28 +18,28 @@ function parseOptions(opts) {
// If the given value is nonsense default to debug and opt builds.
if (builds.length == 0) {
builds = ["d", "o"];
}
// Parse platforms.
let allPlatforms = ["linux", "linux64", "linux64-asan", "win64", "arm",
- "linux64-gyp", "linux64-fuzz"];
+ "linux64-gyp", "linux64-gyp-asan", "linux64-fuzz"];
let platforms = intersect(opts.platform.split(/\s*,\s*/), allPlatforms);
// If the given value is nonsense or "none" default to all platforms.
if (platforms.length == 0 && opts.platform != "none") {
platforms = allPlatforms;
}
// Parse unit tests.
let aliases = {"gtests": "gtest"};
let allUnitTests = ["bogo", "crmf", "chains", "cipher", "db", "ec", "fips",
- "gtest", "interop", "lowhash", "merge", "sdr", "smime", "tools",
+ "gtest", "lowhash", "merge", "sdr", "smime", "tools",
"ssl", "mpi", "scert", "spki"];
let unittests = intersect(opts.unittests.split(/\s*,\s*/).map(t => {
return aliases[t] || t;
}), allUnitTests);
// If the given value is "all" run all tests.
// If it's nonsense then don't run any tests.
if (opts.unittests == "all") {
@@ -103,30 +103,33 @@ function filter(opts) {
// Filter by platform.
let found = opts.platforms.some(platform => {
let aliases = {
"linux": "linux32",
"linux64-asan": "linux64",
"linux64-fuzz": "linux64",
"linux64-gyp": "linux64",
+ "linux64-gyp-asan": "linux64",
"win64": "windows2012-64",
"arm": "linux32"
};
// Check the platform name.
let keep = (task.platform == (aliases[platform] || platform));
// Additional checks.
if (platform == "linux64-asan") {
keep &= coll("asan");
} else if (platform == "arm") {
keep &= coll("arm-opt") || coll("arm-debug");
} else if (platform == "linux64-gyp") {
keep &= coll("gyp");
+ } else if (platform == "linux64-gyp-asan") {
+ keep &= coll("gyp-asan");
} else if (platform == "linux64-fuzz") {
keep &= coll("fuzz");
} else {
keep &= coll("opt") || coll("debug");
}
return keep;
});
--- a/security/nss/automation/taskcluster/scripts/build.sh
+++ b/security/nss/automation/taskcluster/scripts/build.sh
@@ -1,21 +1,18 @@
#!/usr/bin/env bash
-source $(dirname "$0")/tools.sh
+source $(dirname $0)/tools.sh
-if [ -n "$NSS_BUILD_MODULAR" ]; then
- $(dirname "$0")/build_nspr.sh || exit $?
- $(dirname "$0")/build_util.sh || exit $?
- $(dirname "$0")/build_softoken.sh || exit $?
- $(dirname "$0")/build_nss.sh || exit $?
- exit
+if [[ $(id -u) -eq 0 ]]; then
+ # Drop privileges by re-running this script.
+ exec su worker $0
fi
# Clone NSPR if needed.
-hg_clone https://hg.mozilla.org/projects/nspr ./nspr default
+hg_clone https://hg.mozilla.org/projects/nspr nspr default
# Build.
make -C nss nss_build_all
# Package.
mkdir artifacts
tar cvfjh artifacts/dist.tar.bz2 dist
--- a/security/nss/automation/taskcluster/scripts/build_gyp.sh
+++ b/security/nss/automation/taskcluster/scripts/build_gyp.sh
@@ -1,13 +1,18 @@
#!/usr/bin/env bash
-source $(dirname "$0")/tools.sh
+source $(dirname $0)/tools.sh
+
+if [[ $(id -u) -eq 0 ]]; then
+ # Drop privileges by re-running this script.
+ exec su worker -c "$0 $*"
+fi
# Clone NSPR if needed.
-hg_clone https://hg.mozilla.org/projects/nspr ./nspr default
+hg_clone https://hg.mozilla.org/projects/nspr nspr default
# Build.
-nss/build.sh -g -v "$@"
+nss/build.sh ${*--g -v}
# Package.
mkdir artifacts
tar cvfjh artifacts/dist.tar.bz2 dist
deleted file mode 100755
--- a/security/nss/automation/taskcluster/scripts/build_nspr.sh
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/usr/bin/env bash
-
-set -v -e -x
-
-source $(dirname $0)/tools.sh
-
-# Clone NSPR if needed.
-hg_clone https://hg.mozilla.org/projects/nspr nspr default
-
-# Build.
-rm -rf dist
-make -C nss build_nspr
-
-# Package.
-test -d artifacts || mkdir artifacts
-rm -rf dist-nspr
-mv dist dist-nspr
-tar cvfjh artifacts/dist-nspr.tar.bz2 dist-nspr
deleted file mode 100755
--- a/security/nss/automation/taskcluster/scripts/build_nss.sh
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/usr/bin/env bash
-
-set -v -e -x
-
-source $(dirname $0)/tools.sh
-source $(dirname $0)/split.sh
-
-test -d dist-softoken || { echo "run build_softoken.sh first" 1>&2; exit 1; }
-
-rm -rf nss-nss
-split_nss nss nss-nss
-
-# Build.
-export NSS_BUILD_WITHOUT_SOFTOKEN=1
-export NSS_USE_SYSTEM_FREEBL=1
-
-platform=`make -s -C nss platform`
-
-export NSPR_LIB_DIR="$PWD/dist-nspr/$platform/lib"
-export NSSUTIL_LIB_DIR="$PWD/dist-util/$platform/lib"
-export FREEBL_LIB_DIR="$PWD/dist-softoken/$platform/lib"
-export SOFTOKEN_LIB_DIR="$PWD/dist-softoken/$platform/lib"
-export FREEBL_LIBS=-lfreebl
-
-export NSS_NO_PKCS11_BYPASS=1
-export FREEBL_NO_DEPEND=1
-
-export LIBRARY_PATH="$PWD/dist-nspr/$platform/lib:$PWD/dist-util/$platform/lib:$PWD/dist-softoken/$platform/lib"
-export LD_LIBRARY_PATH="$LIBRARY_PATH:$LD_LIBRARY_PATH"
-export INCLUDES="-I$PWD/dist-nspr/$platform/include -I$PWD/dist-util/public/nss -I$PWD/dist-softoken/public/nss"
-
-rm -rf dist
-make -C nss-nss nss_build_all
-
-# Package.
-test -d artifacts || mkdir artifacts
-rm -rf dist-nss
-mv dist dist-nss
-tar cvfjh artifacts/dist-nss.tar.bz2 dist-nss
deleted file mode 100755
--- a/security/nss/automation/taskcluster/scripts/build_softoken.sh
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/bin/env bash
-
-set -v -e -x
-
-source $(dirname $0)/tools.sh
-source $(dirname $0)/split.sh
-
-test -d dist-util || { echo "run build_util.sh first" 1>&2; exit 1; }
-
-rm -rf nss-softoken
-split_softoken nss nss-softoken
-
-# Build.
-platform=`make -s -C nss platform`
-export LIBRARY_PATH="$PWD/dist-nspr/$platform/lib:$PWD/dist-util/$platform/lib"
-export LD_LIBRARY_PATH="$LIBRARY_PATH:$LD_LIBRARY_PATH"
-export INCLUDES="-I$PWD/dist-nspr/$platform/include -I$PWD/dist-util/public/nss"
-export NSS_BUILD_SOFTOKEN_ONLY=1
-
-rm -rf dist
-make -C nss-softoken nss_build_all
-
-mv dist/private/nss/blapi.h dist/public/nss
-mv dist/private/nss/alghmac.h dist/public/nss
-
-# Package.
-test -d artifacts || mkdir artifacts
-rm -rf dist-softoken
-mv dist dist-softoken
-tar cvfjh artifacts/dist-softoken.tar.bz2 dist-softoken
deleted file mode 100755
--- a/security/nss/automation/taskcluster/scripts/build_util.sh
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/usr/bin/env bash
-
-set -v -e -x
-
-source $(dirname $0)/tools.sh
-source $(dirname $0)/split.sh
-
-rm -rf nss-util
-split_util nss nss-util
-
-# Build.
-platform=`make -s -C nss platform`
-export LIBRARY_PATH="$PWD/dist-nspr/$platform/lib"
-export LD_LIBRARY_PATH="$LIBRARY_PATH:$LD_LIBRARY_PATH"
-export INCLUDES="-I$PWD/dist-nspr/$platform/include"
-export NSS_BUILD_UTIL_ONLY=1
-
-rm -rf dist
-make -C nss-util nss_build_all
-
-# Package.
-test -d artifacts || mkdir artifacts
-rm -rf dist-util
-mv dist dist-util
-tar cvfjh artifacts/dist-util.tar.bz2 dist-util
--- a/security/nss/automation/taskcluster/scripts/extend_task_graph.sh
+++ b/security/nss/automation/taskcluster/scripts/extend_task_graph.sh
@@ -1,11 +1,16 @@
#!/usr/bin/env bash
-source $(dirname "$0")/tools.sh
+set -v -e -x
+
+if [ $(id -u) = 0 ]; then
+ # Drop privileges by re-running this script.
+ exec su worker $0
+fi
mkdir -p /home/worker/artifacts
# Install Node.JS dependencies.
cd nss/automation/taskcluster/graph/ && npm install
# Extend the task graph.
node lib/index.js
--- a/security/nss/automation/taskcluster/scripts/fuzz.sh
+++ b/security/nss/automation/taskcluster/scripts/fuzz.sh
@@ -1,28 +1,20 @@
#!/usr/bin/env bash
-source $(dirname "$0")/tools.sh
+source $(dirname $0)/tools.sh
-type="$1"
-shift
+if [ $(id -u) = 0 ]; then
+ # Drop privileges by re-running this script.
+ exec su worker -c "$0 $*"
+fi
# Fetch artifact if needed.
fetch_dist
# Clone corpus.
./nss/fuzz/clone_corpus.sh
-# Ensure we have a corpus.
-if [ ! -d "nss/fuzz/corpus/$type" ]; then
- mkdir -p nss/fuzz/corpus/$type
-
- # Create a corpus out of what we have.
- for f in $(find nss/fuzz/corpus -type f); do
- cp $f "nss/fuzz/corpus/$type"
- done
-fi
-
# Fetch objdir name.
objdir=$(cat dist/latest)
# Run nssfuzz.
-dist/$objdir/bin/nssfuzz-"$type" "$@"
+LD_LIBRARY_PATH=$LD_LIBRARY_PATH:dist/$objdir/lib dist/$objdir/bin/nssfuzz $*
--- a/security/nss/automation/taskcluster/scripts/gen_certs.sh
+++ b/security/nss/automation/taskcluster/scripts/gen_certs.sh
@@ -1,11 +1,21 @@
#!/usr/bin/env bash
-source $(dirname "$0")/tools.sh
+set -v -e -x
+
+source $(dirname $0)/tools.sh
+
+if [ $(id -u) = 0 ]; then
+ # Stupid Docker.
+ echo "127.0.0.1 localhost.localdomain" >> /etc/hosts
+
+ # Drop privileges by re-running this script.
+ exec su worker $0
+fi
# Fetch artifact if needed.
fetch_dist
# Generate certificates.
NSS_TESTS=cert NSS_CYCLES="standard pkix sharedb" $(dirname $0)/run_tests.sh
# Reset test counter so that test runs pick up our certificates.
--- a/security/nss/automation/taskcluster/scripts/run_clang_format.sh
+++ b/security/nss/automation/taskcluster/scripts/run_clang_format.sh
@@ -1,11 +1,16 @@
#!/usr/bin/env bash
-source $(dirname "$0")/tools.sh
+set -v -e -x
+
+if [ $(id -u) -eq 0 ]; then
+ # Drop privileges by re-running this script.
+ exec su worker $0 "$@"
+fi
# Apply clang-format on the provided folder and verify that this doesn't change any file.
# If any file differs after formatting, the script eventually exits with 1.
# Any differences between formatted and unformatted files is printed to stdout to give a hint what's wrong.
# Includes a default set of directories.
if [ $# -gt 0 ]; then
@@ -36,17 +41,16 @@ else
"$top/lib/sysinit" \
"$top/lib/util" \
"$top/gtests/common" \
"$top/gtests/der_gtest" \
"$top/gtests/freebl_gtest" \
"$top/gtests/pk11_gtest" \
"$top/gtests/ssl_gtest" \
"$top/gtests/util_gtest" \
- "$top/nss-tool" \
)
fi
for dir in "${dirs[@]}"; do
find "$dir" -type f \( -name '*.[ch]' -o -name '*.cc' \) -exec clang-format -i {} \+
done
TMPFILE=$(mktemp /tmp/$(basename $0).XXXXXX)
--- a/security/nss/automation/taskcluster/scripts/run_scan_build.sh
+++ b/security/nss/automation/taskcluster/scripts/run_scan_build.sh
@@ -1,15 +1,20 @@
#!/usr/bin/env bash
-source $(dirname "$0")/tools.sh
+source $(dirname $0)/tools.sh
+
+if [ $(id -u) = 0 ]; then
+ # Drop privileges by re-running this script.
+ exec su worker $0 $@
+fi
# Clone NSPR if needed.
if [ ! -d "nspr" ]; then
- hg_clone https://hg.mozilla.org/projects/nspr ./nspr default
+ hg_clone https://hg.mozilla.org/projects/nspr nspr default
fi
# Build.
cd nss
make nss_build_all
# What we want to scan.
# key: directory to scan
--- a/security/nss/automation/taskcluster/scripts/run_tests.sh
+++ b/security/nss/automation/taskcluster/scripts/run_tests.sh
@@ -1,9 +1,17 @@
#!/usr/bin/env bash
-source $(dirname "$0")/tools.sh
+source $(dirname $0)/tools.sh
+
+if [ $(id -u) = 0 ]; then
+ # Stupid Docker.
+ echo "127.0.0.1 localhost.localdomain" >> /etc/hosts
+
+ # Drop privileges by re-running this script.
+ exec su worker $0
+fi
# Fetch artifact if needed.
fetch_dist
# Run tests.
cd nss/tests && ./all.sh
deleted file mode 100644
--- a/security/nss/automation/taskcluster/scripts/split.sh
+++ /dev/null
@@ -1,152 +0,0 @@
-copy_top()
-{
- srcdir_="$1"
- dstdir_="$2"
- files=`find "$srcdir_" -maxdepth 1 -mindepth 1 -type f`
- for f in $files; do
- cp -p "$f" "$dstdir_"
- done
-}
-
-split_util() {
- nssdir="$1"
- dstdir="$2"
-
- # Prepare a source tree only containing files to build nss-util:
- #
- # nss/dbm full directory
- # nss/coreconf full directory
- # nss top files only
- # nss/lib top files only
- # nss/lib/util full directory
-
- # Copy everything.
- cp -R $nssdir $dstdir
-
- # Skip gtests when building.
- sed '/^DIRS = /s/ gtests$//' $nssdir/manifest.mn > $dstdir/manifest.mn-t && mv $dstdir/manifest.mn-t $dstdir/manifest.mn
-
- # Remove subdirectories that we don't want.
- rm -rf $dstdir/cmd
- rm -rf $dstdir/tests
- rm -rf $dstdir/lib
- rm -rf $dstdir/automation
- rm -rf $dstdir/gtests
- rm -rf $dstdir/doc
-
- # Start with an empty cmd lib directories to be filled selectively.
- mkdir $dstdir/cmd
- cp $nssdir/cmd/Makefile $dstdir/cmd
- cp $nssdir/cmd/manifest.mn $dstdir/cmd
- cp $nssdir/cmd/platlibs.mk $dstdir/cmd
- cp $nssdir/cmd/platrules.mk $dstdir/cmd
-
- # Copy some files at the top and the util subdirectory recursively.
- mkdir $dstdir/lib
- cp $nssdir/lib/Makefile $dstdir/lib
- cp $nssdir/lib/manifest.mn $dstdir/lib
- cp -R $nssdir/lib/util $dstdir/lib/util
-}
-
-split_softoken() {
- nssdir="$1"
- dstdir="$2"
-
- # Prepare a source tree only containing files to build nss-softoken:
- #
- # nss/dbm full directory
- # nss/coreconf full directory
- # nss top files only
- # nss/lib top files only
- # nss/lib/freebl full directory
- # nss/lib/softoken full directory
- # nss/lib/softoken/dbm full directory
-
- # Copy everything.
- cp -R $nssdir $dstdir
-
- # Skip gtests when building.
- sed '/^DIRS = /s/ gtests$//' $nssdir/manifest.mn > $dstdir/manifest.mn-t && mv $dstdir/manifest.mn-t $dstdir/manifest.mn
-
- # Remove subdirectories that we don't want.
- rm -rf $dstdir/cmd
- rm -rf $dstdir/tests
- rm -rf $dstdir/lib
- rm -rf $dstdir/pkg
- rm -rf $dstdir/automation
- rm -rf $dstdir/gtests
- rm -rf $dstdir/doc
-
- # Start with an empty lib directory and copy only what we need.
- mkdir $dstdir/lib
- copy_top $nssdir/lib $dstdir/lib
- cp -R $nssdir/lib/dbm $dstdir/lib/dbm
- cp -R $nssdir/lib/freebl $dstdir/lib/freebl
- cp -R $nssdir/lib/softoken $dstdir/lib/softoken
- cp -R $nssdir/lib/sqlite $dstdir/lib/sqlite
-
- mkdir $dstdir/cmd
- copy_top $nssdir/cmd $dstdir/cmd
- cp -R $nssdir/cmd/bltest $dstdir/cmd/bltest
- cp -R $nssdir/cmd/ecperf $dstdir/cmd/ecperf
- cp -R $nssdir/cmd/fbectest $dstdir/cmd/fbectest
- cp -R $nssdir/cmd/fipstest $dstdir/cmd/fipstest
- cp -R $nssdir/cmd/lib $dstdir/cmd/lib
- cp -R $nssdir/cmd/lowhashtest $dstdir/cmd/lowhashtest
- cp -R $nssdir/cmd/shlibsign $dstdir/cmd/shlibsign
-
- mkdir $dstdir/tests
- copy_top $nssdir/tests $dstdir/tests
-
- cp -R $nssdir/tests/cipher $dstdir/tests/cipher
- cp -R $nssdir/tests/common $dstdir/tests/common
- cp -R $nssdir/tests/ec $dstdir/tests/ec
- cp -R $nssdir/tests/lowhash $dstdir/tests/lowhash
-
- cp $nssdir/lib/util/verref.h $dstdir/lib/freebl
- cp $nssdir/lib/util/verref.h $dstdir/lib/softoken
- cp $nssdir/lib/util/verref.h $dstdir/lib/softoken/legacydb
-}
-
-split_nss() {
- nssdir="$1"
- dstdir="$2"
-
- # Prepare a source tree only containing files to build nss:
- #
- # nss/dbm full directory
- # nss/coreconf full directory
- # nss top files only
- # nss/lib top files only
- # nss/lib/freebl full directory
- # nss/lib/softoken full directory
- # nss/lib/softoken/dbm full directory
-
- # Copy everything.
- cp -R $nssdir $dstdir
-
- # Remove subdirectories that we don't want.
- rm -rf $dstdir/lib/freebl
- rm -rf $dstdir/lib/softoken
- rm -rf $dstdir/lib/util
- rm -rf $dstdir/cmd/bltest
- rm -rf $dstdir/cmd/fipstest
- rm -rf $dstdir/cmd/rsaperf_low
-
- # Copy these headers until the upstream bug is accepted
- # Upstream https://bugzilla.mozilla.org/show_bug.cgi?id=820207
- cp $nssdir/lib/softoken/lowkeyi.h $dstdir/cmd/rsaperf
- cp $nssdir/lib/softoken/lowkeyti.h $dstdir/cmd/rsaperf
-
- # Copy verref.h which will be needed later during the build phase.
- cp $nssdir/lib/util/verref.h $dstdir/lib/ckfw/builtins/verref.h
- cp $nssdir/lib/util/verref.h $dstdir/lib/nss/verref.h
- cp $nssdir/lib/util/verref.h $dstdir/lib/smime/verref.h
- cp $nssdir/lib/util/verref.h $dstdir/lib/ssl/verref.h
- cp $nssdir/lib/util/templates.c $dstdir/lib/nss/templates.c
-
- # FIXME: Skip util_gtest because it links with libnssutil.a. Note
- # that we can't use libnssutil3.so instead, because util_gtest
- # depends on internal symbols not exported from the shared library.
- sed '/ util_gtest \\/d' $dstdir/gtests/manifest.mn > $dstdir/gtests/manifest.mn-t && mv $dstdir/gtests/manifest.mn-t $dstdir/gtests/manifest.mn
-}
--- a/security/nss/automation/taskcluster/scripts/tools.sh
+++ b/security/nss/automation/taskcluster/scripts/tools.sh
@@ -1,27 +1,17 @@
#!/usr/bin/env bash
set -v -e -x
-if [[ $(id -u) -eq 0 ]]; then
- # Drop privileges by re-running this script.
- # Note: this mangles arguments, better to avoid running scripts as root.
- exec su worker -c "$0 $*"
-fi
-
# Usage: hg_clone repo dir [revision=@]
hg_clone() {
repo=$1
dir=$2
rev=${3:-@}
- if [ -d "$dir" ]; then
- hg pull -R "$dir" -ur "$rev" "$repo" && return
- rm -rf "$dir"
- fi
for i in 0 2 5; do
sleep $i
hg clone -r "$rev" "$repo" "$dir" && return
rm -rf "$dir"
done
exit 1
}
--- a/security/nss/automation/taskcluster/windows/releng.manifest
+++ b/security/nss/automation/taskcluster/windows/releng.manifest
@@ -1,10 +1,10 @@
[
{
- "version": "Visual Studio 2015 Update 3 14.0.25425.01 / SDK 10.0.14393.0",
- "size": 326656969,
- "digest": "babc414ffc0457d27f5a1ed24a8e4873afbe2f1c1a4075469a27c005e1babc3b2a788f643f825efedff95b79686664c67ec4340ed535487168a3482e68559bc7",
+ "version": "Visual Studio 2015 Update 2 / SDK 10.0.10586.0/212",
+ "size": 332442800,
+ "digest": "995394a4a515c7cb0f8595f26f5395361a638870dd0bbfcc22193fe1d98a0c47126057d5999cc494f3f3eac5cb49160e79757c468f83ee5797298e286ef6252c",
"algorithm": "sha512",
- "filename": "vs2015u3.zip",
+ "filename": "vs2015u2.zip",
"unpack": true
}
]
--- a/security/nss/automation/taskcluster/windows/setup.sh
+++ b/security/nss/automation/taskcluster/windows/setup.sh
@@ -13,18 +13,18 @@ hg_clone() {
rm -rf "$dir"
done
exit 1
}
hg_clone https://hg.mozilla.org/build/tools tools default
tools/scripts/tooltool/tooltool_wrapper.sh $(dirname $0)/releng.manifest https://api.pub.build.mozilla.org/tooltool/ non-existant-file.sh /c/mozilla-build/python/python.exe /c/builds/tooltool.py --authentication-file /c/builds/relengapi.tok -c /c/builds/tooltool_cache
-VSPATH="$(pwd)/vs2015u3"
+VSPATH="$(pwd)/vs2015u2"
export WINDOWSSDKDIR="${VSPATH}/SDK"
export WIN32_REDIST_DIR="${VSPATH}/VC/redist/x64/Microsoft.VC140.CRT"
export WIN_UCRT_REDIST_DIR="${VSPATH}/SDK/Redist/ucrt/DLLs/x64"
export PATH="${VSPATH}/VC/bin/amd64:${VSPATH}/VC/bin:${VSPATH}/SDK/bin/x64:${VSPATH}/VC/redist/x64/Microsoft.VC140.CRT:${VSPATH}/SDK/Redist/ucrt/DLLs/x64:${PATH}"
-export INCLUDE="${VSPATH}/VC/include:${VSPATH}/SDK/Include/10.0.14393.0/ucrt:${VSPATH}/SDK/Include/10.0.14393.0/shared:${VSPATH}/SDK/Include/10.0.14393.0/um"
-export LIB="${VSPATH}/VC/lib/amd64:${VSPATH}/SDK/lib/10.0.14393.0/ucrt/x64:${VSPATH}/SDK/lib/10.0.14393.0/um/x64"
+export INCLUDE="${VSPATH}/VC/include:${VSPATH}/SDK/Include/10.0.10586.0/ucrt:${VSPATH}/SDK/Include/10.0.10586.0/shared:${VSPATH}/SDK/Include/10.0.10586.0/um"
+export LIB="${VSPATH}/VC/lib/amd64:${VSPATH}/SDK/lib/10.0.10586.0/ucrt/x64:${VSPATH}/SDK/lib/10.0.10586.0/um/x64"
--- a/security/nss/build.sh
+++ b/security/nss/build.sh
@@ -1,236 +1,204 @@
-#!/usr/bin/env bash
-#
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-################################################################################
-#
+#!/bin/bash
# This script builds NSS with gyp and ninja.
#
# This build system is still under development. It does not yet support all
# the features or platforms that NSS supports.
set -e
-cwd=$(cd $(dirname $0); pwd -P)
-source "$cwd"/coreconf/nspr.sh
-source "$cwd"/coreconf/sanitizers.sh
+source $(dirname $0)/coreconf/nspr.sh
# Usage info
-show_help()
-{
- cat << EOF
-Usage: ${0##*/} [-hcv] [-j <n>] [--nspr] [--gyp|-g] [--opt|-o] [-m32]
- [--test] [--pprof] [--scan-build[=output]] [--ct-verif]
- [--asan] [--ubsan] [--msan] [--sancov[=edge|bb|func|...]]
- [--disable-tests] [--fuzz[=tls|oss]]
+show_help() {
+cat << EOF
+
+Usage: ${0##*/} [-hcgv] [-j <n>] [--test] [--fuzz] [--scan-build[=output]]
+ [-m32] [--opt|-o] [--asan] [--ubsan] [--sancov[=edge|bb|func]]
+ [--pprof] [--msan]
This script builds NSS with gyp and ninja.
This build system is still under development. It does not yet support all
the features or platforms that NSS supports.
NSS build tool options:
- -h display this help and exit
- -c clean before build
- -v verbose build
- -j <n> run at most <n> concurrent jobs
- --nspr force a rebuild of NSPR
- --gyp|-g force a rerun of gyp
- --opt|-o do an opt build
- -m32 do a 32-bit build on a 64-bit system
- --test ignore map files and export everything we have
- --fuzz build fuzzing targets (this always enables test builds)
- --fuzz=tls to enable TLS fuzzing mode
- --fuzz=oss to build for OSS-Fuzz
- --pprof build with gperftool support
- --ct-verif build with valgrind for ct-verif
- --scan-build run the build with scan-build (scan-build has to be in the path)
- --scan-build=/out/path sets the output path for scan-build
- --asan do an asan build
- --ubsan do an ubsan build
- --ubsan=bool,shift,... sets specific UB sanitizers
- --msan do an msan build
- --sancov do sanitize coverage builds
- --sancov=func sets coverage to function level for example
- --disable-tests don't build tests and corresponding cmdline utils
+ -h display this help and exit
+ -c clean before build
+ -g force a rebuild of gyp (and NSPR, because why not)
+ -j <n> run at most <n> concurrent jobs
+ -v verbose build
+ -m32 do a 32-bit build on a 64-bit system
+ --test ignore map files and export everything we have
+ --fuzz enable fuzzing mode. this always enables test builds
+ --scan-build run the build with scan-build (scan-build has to be in the path)
+ --scan-build=/out/path sets the output path for scan-build
+ --opt|-o do an opt build
+ --asan do an asan build
+ --ubsan do an ubsan build
+ --msan do an msan build
+ --sancov do sanitize coverage builds
+ --sancov=func sets coverage to function level for example
+ --pprof build with gperftool support
EOF
}
-run_verbose()
-{
- if [ "$verbose" = 1 ]; then
- echo "$@"
- exec 3>&1
- else
- exec 3>/dev/null
- fi
- "$@" 1>&3 2>&3
- exec 3>&-
-}
-
if [ -n "$CCC" ] && [ -z "$CXX" ]; then
export CXX="$CCC"
fi
opt_build=0
build_64=0
clean=0
rebuild_gyp=0
-rebuild_nspr=0
target=Debug
verbose=0
fuzz=0
-fuzz_tls=0
-fuzz_oss=0
-gyp_params=(--depth="$cwd" --generator-output=".")
-nspr_params=()
-ninja_params=()
+# parse parameters to store in config
+params=$(echo "$*" | perl -pe 's/-c|-v|-g|-j [0-9]*|-h//g' | perl -pe 's/^\s*(.*?)\s*$/\1/')
+params=$(echo "$params $CC $CCC" | tr " " "\n" | perl -pe '/^\s*$/d')
+params=$(echo "${params[*]}" | sort)
+
+cwd=$(cd $(dirname $0); pwd -P)
+dist_dir="$cwd/../dist"
# try to guess sensible defaults
-arch=$(python "$cwd"/coreconf/detect_host_arch.py)
+arch=$(python "$cwd/coreconf/detect_host_arch.py")
if [ "$arch" = "x64" -o "$arch" = "aarch64" ]; then
build_64=1
fi
+gyp_params=()
+ninja_params=()
+scanbuild=()
+
+enable_fuzz()
+{
+ fuzz=1
+ nspr_sanitizer asan
+ nspr_sanitizer ubsan
+ nspr_sanitizer sancov edge
+ gyp_params+=(-Duse_asan=1)
+ gyp_params+=(-Duse_ubsan=1)
+ gyp_params+=(-Duse_sancov=edge)
+
+ # Adding debug symbols even for opt builds.
+ nspr_opt+=(--enable-debug-symbols)
+}
+
# parse command line arguments
while [ $# -gt 0 ]; do
case $1 in
-c) clean=1 ;;
- --gyp|-g) rebuild_gyp=1 ;;
- --nspr) nspr_clean; rebuild_nspr=1 ;;
+ -g) rebuild_gyp=1 ;;
-j) ninja_params+=(-j "$2"); shift ;;
-v) ninja_params+=(-v); verbose=1 ;;
--test) gyp_params+=(-Dtest_build=1) ;;
- --fuzz) fuzz=1 ;;
- --fuzz=oss) fuzz=1; fuzz_oss=1 ;;
- --fuzz=tls) fuzz=1; fuzz_tls=1 ;;
- --scan-build) enable_scanbuild ;;
- --scan-build=?*) enable_scanbuild "${1#*=}" ;;
+ --fuzz) gyp_params+=(-Dtest_build=1 -Dfuzz=1); enable_fuzz ;;
+ --scan-build) scanbuild=(scan-build) ;;
+ --scan-build=?*) scanbuild=(scan-build -o "${1#*=}") ;;
--opt|-o) opt_build=1 ;;
-m32|--m32) build_64=0 ;;
- --asan) enable_sanitizer asan ;;
- --msan) enable_sanitizer msan ;;
- --ubsan) enable_ubsan ;;
- --ubsan=?*) enable_ubsan "${1#*=}" ;;
- --sancov) enable_sancov ;;
- --sancov=?*) enable_sancov "${1#*=}" ;;
+ --asan) gyp_params+=(-Duse_asan=1); nspr_sanitizer asan ;;
+ --ubsan) gyp_params+=(-Duse_ubsan=1); nspr_sanitizer ubsan ;;
+ --sancov) gyp_params+=(-Duse_sancov=edge); nspr_sanitizer sancov edge ;;
+ --sancov=?*) gyp_params+=(-Duse_sancov="${1#*=}"); nspr_sanitizer sancov "${1#*=}" ;;
--pprof) gyp_params+=(-Duse_pprof=1) ;;
- --ct-verif) gyp_params+=(-Dct_verif=1) ;;
- --disable-tests) gyp_params+=(-Ddisable_tests=1) ;;
- --no-zdefs) gyp_params+=(-Dno_zdefs=1) ;;
- *) show_help; exit 2 ;;
+ --msan) gyp_params+=(-Duse_msan=1); nspr_sanitizer msan ;;
+ *) show_help; exit ;;
esac
shift
done
-if [ "$opt_build" = 1 ]; then
+if [ "$opt_build" = "1" ]; then
target=Release
+ nspr_opt+=(--disable-debug --enable-optimize)
else
target=Debug
fi
-if [ "$build_64" = 1 ]; then
- nspr_params+=(--enable-64bit)
+if [ "$build_64" == "1" ]; then
+ nspr_opt+=(--enable-64bit)
else
gyp_params+=(-Dtarget_arch=ia32)
+ nspr_opt+=(--enable-x32)
fi
-if [ "$fuzz" = 1 ]; then
- source "$cwd"/coreconf/fuzz.sh
+
+# clone fuzzing stuff
+if [ "$fuzz" = "1" ]; then
+ [ $verbose = 0 ] && exec 3>/dev/null || exec 3>&1
+
+ echo "[1/2] Cloning libFuzzer files ..."
+ $cwd/fuzz/clone_libfuzzer.sh 1>&3 2>&3
+
+ echo "[2/2] Cloning fuzzing corpus ..."
+ $cwd/fuzz/clone_corpus.sh 1>&3 2>&3
+
+ exec 3>&-
+fi
+
+# check if we have to rebuild gyp
+if [ "$params" != "$(cat $cwd/out/config 2>/dev/null)" -o "$rebuild_gyp" == 1 -o "$clean" == 1 ]; then
+ rebuild_gyp=1
+ rm -rf "$cwd/../nspr/$target" # force NSPR to rebuild
fi
# set paths
-target_dir="$cwd"/out/$target
-mkdir -p "$target_dir"
-dist_dir="$cwd"/../dist
-dist_dir=$(mkdir -p "$dist_dir"; cd "$dist_dir"; pwd -P)
-gyp_params+=(-Dnss_dist_dir="$dist_dir")
+target_dir="$cwd/out/$target"
+
+# get the realpath of $dist_dir
+dist_dir=$(mkdir -p $dist_dir; cd $dist_dir; pwd -P)
+
+# get object directory
+obj_dir="$dist_dir/$target"
+gyp_params+=(-Dnss_dist_dir=$dist_dir)
+gyp_params+=(-Dnss_dist_obj_dir=$obj_dir)
+gyp_params+=(-Dnspr_lib_dir=$obj_dir/lib)
+gyp_params+=(-Dnspr_include_dir=$obj_dir/include/nspr)
# -c = clean first
if [ "$clean" = 1 ]; then
- nspr_clean
- rm -rf "$cwd"/out
+ rm -rf "$cwd/out"
+ rm -rf "$cwd/../nspr/$target"
rm -rf "$dist_dir"
fi
-# This saves a canonical representation of arguments that we are passing to gyp
-# or the NSPR build so that we can work out if a rebuild is needed.
-# Caveat: This can fail for arguments that are position-dependent.
-# e.g., "-e 2 -f 1" and "-e 1 -f 2" canonicalize the same.
-check_config()
-{
- local newconf="$1".new oldconf="$1"
- shift
- mkdir -p $(dirname "$newconf")
- echo CC="$CC" >"$newconf"
- echo CCC="$CCC" >>"$newconf"
- echo CXX="$CXX" >>"$newconf"
- for i in "$@"; do echo $i; done | sort >>"$newconf"
+# save the chosen target
+mkdir -p $dist_dir
+echo $target > $dist_dir/latest
- # Note: The following diff fails if $oldconf isn't there as well, which
- # happens if we don't have a previous successful build.
- ! diff -q "$newconf" "$oldconf" >/dev/null 2>&1
-}
-
-gyp_config="$cwd"/out/gyp_config
-nspr_config="$cwd"/out/$target/nspr_config
-
-# If we don't have a build directory make sure that we rebuild.
-if [ ! -d "$target_dir" ]; then
- rebuild_nspr=1
- rebuild_gyp=1
-elif [ ! -d "$dist_dir"/$target ]; then
- rebuild_nspr=1
-fi
-
-# Update NSPR ${C,CXX,LD}FLAGS.
-nspr_set_flags $sanitizer_flags
+# pass on CC and CCC
+if [ "${#scanbuild[@]}" -gt 0 ]; then
+ if [ -n "$CC" ]; then
+ scanbuild+=(--use-cc="$CC")
+ fi
+ if [ -n "$CCC" ]; then
+ scanbuild+=(--use-c++="$CCC")
+ fi
+ fi
-if check_config "$nspr_config" "${nspr_params[@]}" \
- nspr_cflags="$nspr_cflags" \
- nspr_cxxflags="$nspr_cxxflags" \
- nspr_ldflags="$nspr_ldflags"; then
- rebuild_nspr=1
-fi
-
-# Forward sanitizer flags.
-if [ ! -z "$sanitizer_flags" ]; then
- gyp_params+=(-Dsanitizer_flags="$sanitizer_flags")
-fi
-
-if check_config "$gyp_config" "${gyp_params[@]}"; then
- rebuild_gyp=1
-fi
+# These steps can take a while, so don't overdo them.
+# Force a redo with -g.
+if [ "$rebuild_gyp" = 1 -o ! -d "$target_dir" ]; then
+ build_nspr $verbose
-# save the chosen target
-mkdir -p "$dist_dir"
-echo $target > "$dist_dir"/latest
-
-if [ "$rebuild_nspr" = 1 ]; then
- nspr_build "${nspr_params[@]}"
- mv -f "$nspr_config".new "$nspr_config"
-fi
-if [ "$rebuild_gyp" = 1 ]; then
+ # Run gyp.
+ [ $verbose = 1 ] && set -v -x
+ "${scanbuild[@]}" gyp -f ninja "${gyp_params[@]}" --depth="$cwd" \
+ --generator-output="." "$cwd/nss.gyp"
+ [ $verbose = 1 ] && set +v +x
- # These extra arguments aren't used in determining whether to rebuild.
- obj_dir="$dist_dir"/$target
- gyp_params+=(-Dnss_dist_obj_dir=$obj_dir)
- gyp_params+=(-Dnspr_lib_dir=$obj_dir/lib)
- gyp_params+=(-Dnspr_include_dir=$obj_dir/include/nspr)
-
- run_verbose run_scanbuild gyp -f ninja "${gyp_params[@]}" "$cwd"/nss.gyp
-
- mv -f "$gyp_config".new "$gyp_config"
+ # Store used parameters for next run.
+ echo "$params" > "$cwd/out/config"
fi
# Run ninja.
-if hash ninja 2>/dev/null; then
- ninja=ninja
-elif hash ninja-build 2>/dev/null; then
- ninja=ninja-build
+if which ninja >/dev/null 2>&1; then
+ ninja=(ninja)
+elif which ninja-build >/dev/null 2>&1; then
+ ninja=(ninja-build)
else
echo "Please install ninja" 1>&2
exit 1
fi
-run_scanbuild $ninja -C "$target_dir" "${ninja_params[@]}"
+"${scanbuild[@]}" $ninja -C "$target_dir" "${ninja_params[@]}"
--- a/security/nss/cmd/bltest/blapitest.c
+++ b/security/nss/cmd/bltest/blapitest.c
@@ -912,25 +912,23 @@ SECStatus
setupIO(PLArenaPool *arena, bltestIO *input, PRFileDesc *file,
char *str, int numBytes)
{
SECStatus rv = SECSuccess;
SECItem fileData;
SECItem *in;
unsigned char *tok;
unsigned int i, j;
- PRBool needToFreeFile = PR_FALSE;
if (file && (numBytes == 0 || file == PR_STDIN)) {
/* grabbing data from a file */
rv = SECU_FileToItem(&fileData, file);
if (rv != SECSuccess)
return SECFailure;
in = &fileData;
- needToFreeFile = PR_TRUE;
} else if (str) {
/* grabbing data from command line */
fileData.data = (unsigned char *)str;
fileData.len = PL_strlen(str);
in = &fileData;
} else if (file) {
/* create nonce */
SECITEM_AllocItem(arena, &input->buf, numBytes);
@@ -954,17 +952,20 @@ setupIO(PLArenaPool *arena, bltestIO *in
input->buf.data = NULL;
input->buf.len = 0;
break;
}
if (in->data[in->len - 1] == '\n')
--in->len;
if (in->data[in->len - 1] == '\r')
--in->len;
- rv = SECITEM_CopyItem(arena, &input->buf, in);
+ SECITEM_CopyItem(arena, &input->buf, in);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
break;
case bltestHexSpaceDelim:
SECITEM_AllocItem(arena, &input->buf, in->len / 5);
for (i = 0, j = 0; i < in->len; i += 5, j++) {
tok = &in->data[i];
if (tok[0] != '0' || tok[1] != 'x' || tok[4] != ' ')
/* bad hex token */
break;
@@ -980,17 +981,17 @@ setupIO(PLArenaPool *arena, bltestIO *in
tok = &in->data[i];
rv = hex_from_2char(tok, input->buf.data + j);
if (rv)
break;
}
break;
}
- if (needToFreeFile)
+ if (file)
SECITEM_FreeItem(&fileData, PR_FALSE);
return rv;
}
SECStatus
finishIO(bltestIO *output, PRFileDesc *file)
{
SECStatus rv = SECSuccess;
--- a/security/nss/cmd/certutil/keystuff.c
+++ b/security/nss/cmd/certutil/keystuff.c
@@ -47,20 +47,19 @@ const SEC_ASN1Template SECKEY_PQGParamsT
{ 0 }
};
/* returns 0 for success, -1 for failure (EOF encountered) */
static int
UpdateRNG(void)
{
char randbuf[RAND_BUF_SIZE];
- int fd;
+ int fd, count;
int c;
int rv = 0;
- size_t count;
#ifdef XP_UNIX
cc_t orig_cc_min;
cc_t orig_cc_time;
tcflag_t orig_lflag;
struct termios tio;
#endif
char meter[] = {
"\r| |"
--- a/security/nss/cmd/crlutil/crlutil.c
+++ b/security/nss/cmd/crlutil/crlutil.c
@@ -61,21 +61,18 @@ FindCRL(CERTCertDBHandle *certHandle, ch
return ((CERTSignedCrl *)NULL);
}
if (!derName.len || !derName.data) {
SECU_PrintError(progName, "could not find certificate named '%s'", name);
return ((CERTSignedCrl *)NULL);
}
} else {
- SECStatus rv = SECITEM_CopyItem(NULL, &derName, &cert->derSubject);
+ SECITEM_CopyItem(NULL, &derName, &cert->derSubject);
CERT_DestroyCertificate(cert);
- if (rv != SECSuccess) {
- return ((CERTSignedCrl *)NULL);
- }
}
crl = SEC_FindCrlByName(certHandle, &derName, type);
if (crl == NULL)
SECU_PrintError(progName, "could not find %s's CRL", name);
if (derName.data) {
SECITEM_FreeItem(&derName, PR_FALSE);
}
--- a/security/nss/cmd/ecperf/ecperf.c
+++ b/security/nss/cmd/ecperf/ecperf.c
@@ -4,16 +4,17 @@
#include "blapi.h"
#include "ec.h"
#include "ecl-curve.h"
#include "prprf.h"
#include "basicutil.h"
#include "pkcs11.h"
#include "nspr.h"
+#include "secutil.h"
#include <stdio.h>
#define __PASTE(x, y) x##y
/*
* Get the NSS specific PKCS #11 function names.
*/
#undef CK_PKCS11_FUNCTION_INFO
@@ -100,18 +101,16 @@ typedef struct ThreadDataStr {
void *p3;
int iters;
PRLock *lock;
int count;
SECStatus status;
int isSign;
} ThreadData;
-typedef SECItem SECKEYECParams;
-
void
PKCS11Thread(void *data)
{
ThreadData *threadData = (ThreadData *)data;
pk11_op_func op = (pk11_op_func)threadData->op;
int iters = threadData->iters;
unsigned char sigData[256];
SECItem sig;
--- a/security/nss/cmd/fbectest/fbectest.c
+++ b/security/nss/cmd/fbectest/fbectest.c
@@ -4,16 +4,17 @@
#include "blapi.h"
#include "ec.h"
#include "ecl-curve.h"
#include "prprf.h"
#include "basicutil.h"
#include "secder.h"
#include "secitem.h"
+#include "secutil.h"
#include "nspr.h"
#include <stdio.h>
typedef struct {
ECCurveName curve;
int iterations;
char *privhex;
char *our_pubhex;
--- a/security/nss/cmd/lib/basicutil.c
+++ b/security/nss/cmd/lib/basicutil.c
@@ -20,16 +20,17 @@
#include <sys/stat.h>
#include <errno.h>
#ifdef XP_UNIX
#include <unistd.h>
#endif
#include "secoid.h"
+#include "sslt.h"
extern long DER_GetInteger(const SECItem *src);
static PRBool wrapEnabled = PR_TRUE;
void
SECU_EnableWrap(PRBool enable)
{
@@ -727,50 +728,102 @@ SECU_SECItemHexStringToBinary(SECItem *s
}
/* adjust length */
srcdest->len -= 2;
srcdest->len /= 2;
return SECSuccess;
}
-SECItem *
-SECU_HexString2SECItem(PLArenaPool *arena, SECItem *item, const char *str)
+SSLNamedGroup
+groupNameToNamedGroup(char *name)
{
- int i = 0;
- int byteval = 0;
- int tmp = PORT_Strlen(str);
-
- PORT_Assert(arena);
- PORT_Assert(item);
-
- if ((tmp % 2) != 0) {
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
- return NULL;
+ if (PL_strlen(name) == 4) {
+ if (!strncmp(name, "P256", 4)) {
+ return ssl_grp_ec_secp256r1;
+ }
+ if (!strncmp(name, "P384", 4)) {
+ return ssl_grp_ec_secp384r1;
+ }
+ if (!strncmp(name, "P521", 4)) {
+ return ssl_grp_ec_secp521r1;
+ }
}
-
- item = SECITEM_AllocItem(arena, item, tmp / 2);
- if (item == NULL) {
- return NULL;
+ if (PL_strlen(name) == 6) {
+ if (!strncmp(name, "x25519", 6)) {
+ return ssl_grp_ec_curve25519;
+ }
+ if (!strncmp(name, "FF2048", 6)) {
+ return ssl_grp_ffdhe_2048;
+ }
+ if (!strncmp(name, "FF3072", 6)) {
+ return ssl_grp_ffdhe_3072;
+ }
+ if (!strncmp(name, "FF4096", 6)) {
+ return ssl_grp_ffdhe_4096;
+ }
+ if (!strncmp(name, "FF6144", 6)) {
+ return ssl_grp_ffdhe_6144;
+ }
+ if (!strncmp(name, "FF8192", 6)) {
+ return ssl_grp_ffdhe_8192;
+ }
}
- while (str[i]) {
- if ((str[i] >= '0') && (str[i] <= '9')) {
- tmp = str[i] - '0';
- } else if ((str[i] >= 'a') && (str[i] <= 'f')) {
- tmp = str[i] - 'a' + 10;
- } else if ((str[i] >= 'A') && (str[i] <= 'F')) {
- tmp = str[i] - 'A' + 10;
- } else {
- /* item is in arena and gets freed by the caller */
- return NULL;
- }
+ return ssl_grp_none;
+}
+
+SECStatus
+parseGroupList(const char *arg, SSLNamedGroup **enabledGroups,
+ unsigned int *enabledGroupsCount)
+{
+ SSLNamedGroup *groups;
+ char *str;
+ char *p;
+ unsigned int numValues = 0;
+ unsigned int count = 0;
- byteval = byteval * 16 + tmp;
- if ((i % 2) != 0) {
- item->data[i / 2] = byteval;
- byteval = 0;
- }
- i++;
+ /* Count the number of groups. */
+ str = PORT_Strdup(arg);
+ if (!str) {
+ return SECFailure;
+ }
+ p = strtok(str, ",");
+ while (p) {
+ ++numValues;
+ p = strtok(NULL, ",");
+ }
+ PORT_Free(str);
+ str = NULL;
+ groups = PORT_ZNewArray(SSLNamedGroup, numValues);
+ if (!groups) {
+ goto done;
}
- return item;
+ /* Get group names. */
+ str = PORT_Strdup(arg);
+ if (!str) {
+ goto done;
+ }
+ p = strtok(str, ",");
+ while (p) {
+ SSLNamedGroup group = groupNameToNamedGroup(p);
+ if (group == ssl_grp_none) {
+ count = 0;
+ goto done;
+ }
+ groups[count++] = group;
+ p = strtok(NULL, ",");
+ }
+
+done:
+ if (str) {
+ PORT_Free(str);
+ }
+ if (!count) {
+ PORT_Free(groups);
+ return SECFailure;
+ }
+
+ *enabledGroupsCount = count;
+ *enabledGroups = groups;
+ return SECSuccess;
}
--- a/security/nss/cmd/lib/basicutil.h
+++ b/security/nss/cmd/lib/basicutil.h
@@ -8,16 +8,17 @@
#include "secitem.h"
#include "secoid.h"
#include "secoidt.h"
#include "secport.h"
#include "prerror.h"
#include "base64.h"
#include "secasn1.h"
#include "secder.h"
+#include "sslt.h"
#include <stdio.h>
#ifdef SECUTIL_NEW
typedef int (*SECU_PPFunc)(PRFileDesc *out, SECItem *item,
char *msg, int level);
#else
typedef int (*SECU_PPFunc)(FILE *out, SECItem *item, char *msg, int level);
#endif
@@ -76,22 +77,16 @@ void
SECU_SECItemToHex(const SECItem *item, char *dst);
/* Requires 0x prefix. Case-insensitive. Will do in-place replacement if
* successful */
SECStatus
SECU_SECItemHexStringToBinary(SECItem *srcdest);
/*
-** Read a hex string into a SecItem.
-*/
-extern SECItem *SECU_HexString2SECItem(PLArenaPool *arena, SECItem *item,
- const char *str);
-
-/*
*
* Utilities for parsing security tools command lines
*
*/
/* A single command flag */
typedef struct {
char flag;
@@ -113,16 +108,20 @@ typedef struct
/* fill the "arg" and "activated" fields for each flag */
SECStatus
SECU_ParseCommandLine(int argc, char **argv, char *progName,
const secuCommand *cmd);
char *
SECU_GetOptionArg(const secuCommand *cmd, int optionNum);
+SECStatus parseGroupList(const char *arg, SSLNamedGroup **enabledGroups,
+ unsigned int *enabledGroupsCount);
+SSLNamedGroup groupNameToNamedGroup(char *name);
+
/*
*
* Error messaging
*
*/
void printflags(char *trusts, unsigned int flags);
--- a/security/nss/cmd/lib/secutil.c
+++ b/security/nss/cmd/lib/secutil.c
@@ -3828,102 +3828,50 @@ SECU_ParseSSLVersionRangeString(const ch
if (vrange->min > vrange->max) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
return SECSuccess;
}
-SSLNamedGroup
-groupNameToNamedGroup(char *name)
-{
- if (PL_strlen(name) == 4) {
- if (!strncmp(name, "P256", 4)) {
- return ssl_grp_ec_secp256r1;
- }
- if (!strncmp(name, "P384", 4)) {
- return ssl_grp_ec_secp384r1;
- }
- if (!strncmp(name, "P521", 4)) {
- return ssl_grp_ec_secp521r1;
- }
- }
- if (PL_strlen(name) == 6) {
- if (!strncmp(name, "x25519", 6)) {
- return ssl_grp_ec_curve25519;
- }
- if (!strncmp(name, "FF2048", 6)) {
- return ssl_grp_ffdhe_2048;
- }
- if (!strncmp(name, "FF3072", 6)) {
- return ssl_grp_ffdhe_3072;
- }
- if (!strncmp(name, "FF4096", 6)) {
- return ssl_grp_ffdhe_4096;
- }
- if (!strncmp(name, "FF6144", 6)) {
- return ssl_grp_ffdhe_6144;
- }
- if (!strncmp(name, "FF8192", 6)) {
- return ssl_grp_ffdhe_8192;
- }
- }
-
- return ssl_grp_none;
-}
-
-SECStatus
-parseGroupList(const char *arg, SSLNamedGroup **enabledGroups,
- unsigned int *enabledGroupsCount)
+SECItem *
+SECU_HexString2SECItem(PLArenaPool *arena, SECItem *item, const char *str)
{
- SSLNamedGroup *groups;
- char *str;
- char *p;
- unsigned int numValues = 0;
- unsigned int count = 0;
-
- /* Count the number of groups. */
- str = PORT_Strdup(arg);
- if (!str) {
- return SECFailure;
+ int i = 0;
+ int byteval = 0;
+ int tmp = PORT_Strlen(str);
+
+ PORT_Assert(arena);
+ PORT_Assert(item);
+
+ if ((tmp % 2) != 0) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return NULL;
}
- p = strtok(str, ",");
- while (p) {
- ++numValues;
- p = strtok(NULL, ",");
- }
- PORT_Free(str);
- str = NULL;
- groups = PORT_ZNewArray(SSLNamedGroup, numValues);
- if (!groups) {
- goto done;
+
+ item = SECITEM_AllocItem(arena, item, tmp / 2);
+ if (item == NULL) {
+ return NULL;
}
- /* Get group names. */
- str = PORT_Strdup(arg);
- if (!str) {
- goto done;
- }
- p = strtok(str, ",");
- while (p) {
- SSLNamedGroup group = groupNameToNamedGroup(p);
- if (group == ssl_grp_none) {
- count = 0;
- goto done;
+ while (str[i]) {
+ if ((str[i] >= '0') && (str[i] <= '9')) {
+ tmp = str[i] - '0';
+ } else if ((str[i] >= 'a') && (str[i] <= 'f')) {
+ tmp = str[i] - 'a' + 10;
+ } else if ((str[i] >= 'A') && (str[i] <= 'F')) {
+ tmp = str[i] - 'A' + 10;
+ } else {
+ /* item is in arena and gets freed by the caller */
+ return NULL;
}
- groups[count++] = group;
- p = strtok(NULL, ",");
+
+ byteval = byteval * 16 + tmp;
+ if ((i % 2) != 0) {
+ item->data[i / 2] = byteval;
+ byteval = 0;
+ }
+ i++;
}
-done:
- if (str) {
- PORT_Free(str);
- }
- if (!count) {
- PORT_Free(groups);
- return SECFailure;
- }
-
- *enabledGroupsCount = count;
- *enabledGroups = groups;
- return SECSuccess;
+ return item;
}
--- a/security/nss/cmd/lib/secutil.h
+++ b/security/nss/cmd/lib/secutil.h
@@ -403,20 +403,16 @@ SECU_ParseSSLVersionRangeString(const ch
const SSLVersionRange defaultVersionRange,
SSLVersionRange *vrange);
/*
** Read a hex string into a SecItem.
*/
extern SECItem *SECU_HexString2SECItem(PLArenaPool *arena, SECItem *item,
const char *str);
-SECStatus parseGroupList(const char *arg, SSLNamedGroup **enabledGroups,
- unsigned int *enabledGroupsCount);
-SSLNamedGroup groupNameToNamedGroup(char *name);
-
/*
*
* Error messaging
*
*/
void printflags(char *trusts, unsigned int flags);
--- a/security/nss/cmd/lowhashtest/manifest.mn
+++ b/security/nss/cmd/lowhashtest/manifest.mn
@@ -17,9 +17,8 @@ EXPORTS = \
PRIVATE_EXPORTS = \
$(NULL)
CSRCS = \
lowhashtest.c \
$(NULL)
-USE_STATIC_LIBS = 1
--- a/security/nss/cmd/mpitests/mpitests.gyp
+++ b/security/nss/cmd/mpitests/mpitests.gyp
@@ -9,26 +9,17 @@
'targets': [
{
'target_name': 'mpi_tests',
'type': 'executable',
'sources': [
'mpi-test.c',
],
'dependencies': [
- '<(DEPTH)/exports.gyp:nss_exports',
- '<(DEPTH)/lib/util/util.gyp:nssutil3',
- '<(DEPTH)/lib/nss/nss.gyp:nss_static',
- '<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap_static',
- '<(DEPTH)/lib/cryptohi/cryptohi.gyp:cryptohi',
- '<(DEPTH)/lib/certhigh/certhigh.gyp:certhi',
- '<(DEPTH)/lib/certdb/certdb.gyp:certdb',
- '<(DEPTH)/lib/base/base.gyp:nssb',
- '<(DEPTH)/lib/dev/dev.gyp:nssdev',
- '<(DEPTH)/lib/pki/pki.gyp:nsspki',
+ '<(DEPTH)/lib/freebl/freebl.gyp:<(freebl_name)',
]
}
],
'target_defaults': {
'include_dirs': [
'<(DEPTH)/lib/freebl/mpi',
'<(DEPTH)/lib/util',
]
--- a/security/nss/cmd/platlibs.gypi
+++ b/security/nss/cmd/platlibs.gypi
@@ -27,16 +27,18 @@
'<(DEPTH)/lib/cryptohi/cryptohi.gyp:cryptohi',
'<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap',
'<(DEPTH)/lib/softoken/softoken.gyp:softokn',
'<(DEPTH)/lib/certdb/certdb.gyp:certdb',
'<(DEPTH)/lib/pki/pki.gyp:nsspki',
'<(DEPTH)/lib/dev/dev.gyp:nssdev',
'<(DEPTH)/lib/base/base.gyp:nssb',
'<(DEPTH)/lib/freebl/freebl.gyp:freebl',
+ '<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap',
+ '<(DEPTH)/lib/certhigh/certhigh.gyp:certhi',
'<(DEPTH)/lib/sqlite/sqlite.gyp:sqlite3',
],
'conditions': [
[ 'disable_dbm==0', {
'dependencies': [
'<(DEPTH)/lib/dbm/src/src.gyp:dbm',
'<(DEPTH)/lib/softoken/legacydb/legacydb.gyp:nssdbm',
],
--- a/security/nss/cmd/platlibs.mk
+++ b/security/nss/cmd/platlibs.mk
@@ -226,29 +226,26 @@ EXTRA_LIBS += \
ifeq ($(OS_ARCH), AIX)
EXTRA_SHARED_LIBS += -brtl
endif
# $(PROGRAM) has NO explicit dependencies on $(EXTRA_SHARED_LIBS)
# $(EXTRA_SHARED_LIBS) come before $(OS_LIBS), except on AIX.
EXTRA_SHARED_LIBS += \
-L$(DIST)/lib \
+ -lssl3 \
+ -lsmime3 \
+ -lnss3 \
-L$(NSSUTIL_LIB_DIR) \
-lnssutil3 \
-L$(NSPR_LIB_DIR) \
-lplc4 \
-lplds4 \
-lnspr4 \
$(NULL)
-ifndef NSS_BUILD_SOFTOKEN_ONLY
-EXTRA_SHARED_LIBS += \
- -lssl3 \
- -lsmime3 \
- -lnss3
-endif
endif
ifdef SOFTOKEN_LIB_DIR
ifdef NSS_USE_SYSTEM_FREEBL
EXTRA_SHARED_LIBS += -L$(SOFTOKEN_LIB_DIR) -lsoftokn3
endif
endif
--- a/security/nss/cmd/selfserv/selfserv.c
+++ b/security/nss/cmd/selfserv/selfserv.c
@@ -154,17 +154,17 @@ static PRLogModuleInfo *lm;
fflush(stderr); \
}
#define VLOG(arg) PR_LOG(lm, PR_LOG_DEBUG, arg)
static void
PrintUsageHeader(const char *progName)
{
fprintf(stderr,
- "Usage: %s -n rsa_nickname -p port [-BDENRZbjlmrsuvx] [-w password]\n"
+ "Usage: %s -n rsa_nickname -p port [-BDENRbjlmrsuvx] [-w password]\n"
" [-t threads] [-i pid_file] [-c ciphers] [-Y] [-d dbdir] [-g numblocks]\n"
" [-f password_file] [-L [seconds]] [-M maxProcs] [-P dbprefix]\n"
" [-V [min-version]:[max-version]] [-a sni_name]\n"
" [ T <good|revoked|unknown|badsig|corrupted|none|ocsp>] [-A ca]\n"
" [-C SSLCacheEntries] [-S dsa_nickname] -Q [-I groups]"
#ifndef NSS_DISABLE_ECC
" [-e ec_nickname]"
#endif /* NSS_DISABLE_ECC */
@@ -214,26 +214,25 @@ PrintParameterUsage()
" badsig: use a good status but with an invalid signature\n"
" corrupted: stapled cert status is an invalid block of data\n"
" random: each connection uses a random status from this list:\n"
" good, revoked, unknown, failure, badsig, corrupted\n"
" ocsp: fetch from external OCSP server using AIA, or none\n"
"-A <ca> Nickname of a CA used to sign a stapled cert status\n"
"-U override default ECDHE ephemeral key reuse, 0: refresh, 1: reuse\n"
"-H override default DHE server support, 0: disable, 1: enable, "
- " 2: require DH named groups\n"
+ " 2: require DH named groups\n"
"-W override default DHE server weak parameters support, 0: disable, 1: enable\n"
"-c Restrict ciphers\n"
"-Y prints cipher values allowed for parameter -c and exits\n"
"-G enables the extended master secret extension [RFC7627]\n"
"-Q enables ALPN for HTTP/1.1 [RFC7301]\n"
"-I comma separated list of enabled groups for TLS key exchange.\n"
" The following values are valid:\n"
- " P256, P384, P521, x25519, FF2048, FF3072, FF4096, FF6144, FF8192\n"
- "-Z enable 0-RTT (for TLS 1.3; also use -u)\n",
+ " P256, P384, P521, x25519, FF2048, FF3072, FF4096, FF6144, FF8192\n",
stderr);
}
static void
Usage(const char *progName)
{
PrintUsageHeader(progName);
PrintParameterUsage();
@@ -2301,19 +2300,17 @@ main(int argc, char **argv)
case 'U':
configureReuseECDHE = (PORT_Atoi(optstate->value) != 0);
break;
case 'V':
if (SECU_ParseSSLVersionRangeString(optstate->value,
enabledVersions, &enabledVersions) !=
SECSuccess) {
- fprintf(stderr, "Bad version specified.\n");
Usage(progName);
- exit(1);
}
break;
case 'W':
configureWeakDHE = (PORT_Atoi(optstate->value) != 0);
break;
case 'Y':
--- a/security/nss/cmd/strsclnt/strsclnt.c
+++ b/security/nss/cmd/strsclnt/strsclnt.c
@@ -1345,17 +1345,16 @@ main(int argc, char **argv)
case 'U':
ThrottleUp = PR_TRUE;
break;
case 'V':
if (SECU_ParseSSLVersionRangeString(optstate->value,
enabledVersions, &enabledVersions) !=
SECSuccess) {
- fprintf(stderr, "Bad version specified.\n");
Usage(progName);
}
break;
case 'a':
sniHostName = PL_strdup(optstate->value);
break;
--- a/security/nss/cmd/tstclnt/tstclnt.c
+++ b/security/nss/cmd/tstclnt/tstclnt.c
@@ -164,16 +164,30 @@ printSecurityInfo(PRFileDesc *fd)
scts = SSL_PeerSignedCertTimestamps(fd);
if (scts && scts->len) {
fprintf(stderr, "Received a Signed Certificate Timestamp of length"
" %u\n",
scts->len);
}
}
+void
+handshakeCallback(PRFileDesc *fd, void *client_data)
+{
+ const char *secondHandshakeName = (char *)client_data;
+ if (secondHandshakeName) {
+ SSL_SetURL(fd, secondHandshakeName);
+ }
+ printSecurityInfo(fd);
+ if (renegotiationsDone < renegotiationsToDo) {
+ SSL_ReHandshake(fd, (renegotiationsToDo < 2));
+ ++renegotiationsDone;
+ }
+}
+
static void
PrintUsageHeader(const char *progName)
{
fprintf(stderr,
"Usage: %s -h host [-a 1st_hs_name ] [-a 2nd_hs_name ] [-p port]\n"
"[-D | -d certdir] [-C] [-b | -R root-module] \n"
"[-n nickname] [-Bafosvx] [-c ciphers] [-Y] [-Z]\n"
"[-V [min-version]:[max-version]] [-K] [-T] [-U]\n"
@@ -904,29 +918,23 @@ PRBool clientSpeaksFirst = PR_FALSE;
PRBool skipProtoHeader = PR_FALSE;
ServerCertAuth serverCertAuth;
char *hs1SniHostName = NULL;
char *hs2SniHostName = NULL;
PRUint16 portno = 443;
int override = 0;
char *requestString = NULL;
PRInt32 requestStringLen = 0;
-PRBool requestSent = PR_FALSE;
PRBool enableZeroRtt = PR_FALSE;
static int
-writeBytesToServer(PRFileDesc *s, const char *buf, int nb)
+writeBytesToServer(PRFileDesc *s, PRPollDesc *pollset, const char *buf, int nb)
{
SECStatus rv;
const char *bufp = buf;
- PRPollDesc pollDesc;
-
- pollDesc.in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT;
- pollDesc.out_flags = 0;
- pollDesc.fd = s;
FPRINTF(stderr, "%s: Writing %d bytes to server\n",
progName, nb);
do {
PRInt32 cc = PR_Send(s, bufp, nb, 0, maxInterval);
if (cc < 0) {
PRErrorCode err = PR_GetError();
if (err != PR_WOULD_BLOCK_ERROR) {
@@ -943,80 +951,49 @@ writeBytesToServer(PRFileDesc *s, const
rv = restartHandshakeAfterServerCertIfNeeded(s,
&serverCertAuth, override);
if (rv != SECSuccess) {
SECU_PrintError(progName, "authentication of server cert failed");
return EXIT_CODE_HANDSHAKE_FAILED;
}
- pollDesc.in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT;
- pollDesc.out_flags = 0;
+ pollset[SSOCK_FD].in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT;
+ pollset[SSOCK_FD].out_flags = 0;
FPRINTF(stderr,
"%s: about to call PR_Poll on writable socket !\n",
progName);
- cc = PR_Poll(&pollDesc, 1, PR_INTERVAL_NO_TIMEOUT);
+ cc = PR_Poll(pollset, 1, PR_INTERVAL_NO_TIMEOUT);
if (cc < 0) {
SECU_PrintError(progName,
"PR_Poll failed");
return -1;
}
FPRINTF(stderr,
"%s: PR_Poll returned with writable socket !\n",
progName);
} while (1);
return 0;
}
-void
-handshakeCallback(PRFileDesc *fd, void *client_data)
-{
- const char *secondHandshakeName = (char *)client_data;
- if (secondHandshakeName) {
- SSL_SetURL(fd, secondHandshakeName);
- }
- printSecurityInfo(fd);
- if (renegotiationsDone < renegotiationsToDo) {
- SSL_ReHandshake(fd, (renegotiationsToDo < 2));
- ++renegotiationsDone;
- }
- if (requestString && requestSent) {
- /* This data was sent in 0-RTT. */
- SSLChannelInfo info;
- SECStatus rv;
-
- rv = SSL_GetChannelInfo(fd, &info, sizeof(info));
- if (rv != SECSuccess)
- return;
-
- if (!info.earlyDataAccepted) {
- FPRINTF(stderr, "Early data rejected. Re-sending\n");
- writeBytesToServer(fd, requestString, requestStringLen);
- }
- }
-}
-
-#define REQUEST_WAITING (requestString && !requestSent)
-
static int
run_client(void)
{
int headerSeparatorPtrnId = 0;
int error = 0;
SECStatus rv;
PRStatus status;
PRInt32 filesReady;
int npds;
PRFileDesc *s = NULL;
PRFileDesc *std_out;
PRPollDesc pollset[2];
PRBool wrStarted = PR_FALSE;
-
- requestSent = PR_FALSE;
+ char *requestStringInt = requestString;
/* Create socket */
s = PR_OpenTCPSocket(addr.raw.family);
if (s == NULL) {
SECU_PrintError(progName, "error creating socket");
error = 1;
goto done;
}
@@ -1263,17 +1240,17 @@ run_client(void)
goto done;
}
}
pollset[SSOCK_FD].fd = s;
pollset[SSOCK_FD].in_flags = PR_POLL_EXCEPT |
(clientSpeaksFirst ? 0 : PR_POLL_READ);
pollset[STDIN_FD].fd = PR_GetSpecialFD(PR_StandardInput);
- if (!REQUEST_WAITING) {
+ if (!requestStringInt) {
pollset[STDIN_FD].in_flags = PR_POLL_READ;
npds = 2;
} else {
npds = 1;
}
std_out = PR_GetSpecialFD(PR_StandardOutput);
#if defined(WIN32) || defined(OS2)
@@ -1313,17 +1290,17 @@ run_client(void)
}
/*
** Select on stdin and on the socket. Write data from stdin to
** socket, read data from socket and write to stdout.
*/
FPRINTF(stderr, "%s: ready...\n", progName);
while ((pollset[SSOCK_FD].in_flags | pollset[STDIN_FD].in_flags) ||
- REQUEST_WAITING) {
+ requestStringInt) {
char buf[4000]; /* buffer for stdin */
int nb; /* num bytes read from stdin. */
rv = restartHandshakeAfterServerCertIfNeeded(s, &serverCertAuth,
override);
if (rv != SECSuccess) {
error = EXIT_CODE_HANDSHAKE_FAILED;
SECU_PrintError(progName, "authentication of server cert failed");
@@ -1351,39 +1328,40 @@ run_client(void)
"%s: PR_Poll returned 0x%02x for stdin out_flags.\n",
progName, pollset[STDIN_FD].out_flags);
}
if (pollset[SSOCK_FD].in_flags) {
FPRINTF(stderr,
"%s: PR_Poll returned 0x%02x for socket out_flags.\n",
progName, pollset[SSOCK_FD].out_flags);
}
- if (REQUEST_WAITING) {
- error = writeBytesToServer(s, requestString, requestStringLen);
+ if (requestStringInt) {
+ error = writeBytesToServer(s, pollset,
+ requestStringInt, requestStringLen);
if (error) {
goto done;
}
- requestSent = PR_TRUE;
+ requestStringInt = NULL;
pollset[SSOCK_FD].in_flags = PR_POLL_READ;
}
if (pollset[STDIN_FD].out_flags & PR_POLL_READ) {
/* Read from stdin and write to socket */
nb = PR_Read(pollset[STDIN_FD].fd, buf, sizeof(buf));
FPRINTF(stderr, "%s: stdin read %d bytes\n", progName, nb);
if (nb < 0) {
if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
SECU_PrintError(progName, "read from stdin failed");
error = 1;
break;
}
} else if (nb == 0) {
/* EOF on stdin, stop polling stdin for read. */
pollset[STDIN_FD].in_flags = 0;
} else {
- error = writeBytesToServer(s, buf, nb);
+ error = writeBytesToServer(s, pollset, buf, nb);
if (error) {
goto done;
}
pollset[SSOCK_FD].in_flags = PR_POLL_READ;
}
}
if (pollset[SSOCK_FD].in_flags) {
@@ -1605,17 +1583,16 @@ main(int argc, char **argv)
case 'U':
enableSignedCertTimestamps = 1;
break;
case 'V':
if (SECU_ParseSSLVersionRangeString(optstate->value,
enabledVersions, &enabledVersions) !=
SECSuccess) {
- fprintf(stderr, "Bad version specified.\n");
Usage(progName);
}
break;
case 'Y':
PrintCipherUsage(progName);
exit(0);
break;
--- a/security/nss/coreconf/Darwin.mk
+++ b/security/nss/coreconf/Darwin.mk
@@ -140,8 +140,11 @@ SYS_SQLITE3_VERSION_MINOR := $(shell ech
ifeq (3,$(SYS_SQLITE3_VERSION_MAJOR))
ifeq (,$(filter-out 0 1 2 3 4,$(SYS_SQLITE3_VERSION_MINOR)))
# sqlite <= 3.4.x is too old, it doesn't provide sqlite3_file_control
else
NSS_USE_SYSTEM_SQLITE = 1
endif
endif
+
+include $(CORE_DEPTH)/coreconf/sanitizers.mk
+DARWIN_SDK_SHLIBFLAGS += $(SANITIZER_LDFLAGS)
--- a/security/nss/coreconf/Linux.mk
+++ b/security/nss/coreconf/Linux.mk
@@ -101,16 +101,26 @@ endif
endif
endif
ifneq ($(OS_TARGET),Android)
LIBC_TAG = _glibc
endif
+ifeq ($(OS_RELEASE),2.0)
+ OS_REL_CFLAGS += -DLINUX2_0
+ MKSHLIB = $(CC) -shared -Wl,-soname -Wl,$(@:$(OBJDIR)/%.so=%.so) $(RPATH)
+ ifdef MAPFILE
+ MKSHLIB += -Wl,--version-script,$(MAPFILE)
+ endif
+ PROCESS_MAP_FILE = grep -v ';-' $< | \
+ sed -e 's,;+,,' -e 's; DATA ;;' -e 's,;;,,' -e 's,;.*,;,' > $@
+endif
+
ifdef BUILD_OPT
ifeq (11,$(ALLOW_OPT_CODE_SIZE)$(OPT_CODE_SIZE))
OPTIMIZER = -Os
else
OPTIMIZER = -O2
endif
ifdef MOZ_DEBUG_SYMBOLS
ifdef MOZ_DEBUG_FLAGS
@@ -124,43 +134,45 @@ endif
ifndef COMPILER_TAG
COMPILER_TAG := _$(CC_NAME)
endif
ifeq ($(USE_PTHREADS),1)
OS_PTHREAD = -lpthread
endif
-OS_CFLAGS = $(DSO_CFLAGS) $(OS_REL_CFLAGS) $(ARCHFLAG) -pipe -ffunction-sections -fdata-sections -DHAVE_STRERROR
-ifeq ($(KERNEL),Linux)
- OS_CFLAGS += -DLINUX -Dlinux
-endif
+OS_CFLAGS = $(DSO_CFLAGS) $(OS_REL_CFLAGS) $(ARCHFLAG) -pipe -ffunction-sections -fdata-sections -DLINUX -Dlinux -DHAVE_STRERROR
OS_LIBS = $(OS_PTHREAD) -ldl -lc
ifdef USE_PTHREADS
DEFINES += -D_REENTRANT
endif
+ARCH = linux
+
DSO_CFLAGS = -fPIC
DSO_LDOPTS = -shared $(ARCHFLAG) -Wl,--gc-sections
# The linker on Red Hat Linux 7.2 and RHEL 2.1 (GNU ld version 2.11.90.0.8)
# incorrectly reports undefined references in the libraries we link with, so
# we don't use -z defs there.
# Also, -z defs conflicts with Address Sanitizer, which emits relocations
# against the libsanitizer runtime built into the main executable.
ZDEFS_FLAG = -Wl,-z,defs
+ifneq ($(USE_ASAN),1)
DSO_LDOPTS += $(if $(findstring 2.11.90.0.8,$(shell ld -v)),,$(ZDEFS_FLAG))
+endif
LDFLAGS += $(ARCHFLAG)
# On Maemo, we need to use the -rpath-link flag for even the standard system
# library directories.
ifdef _SBOX_DIR
LDFLAGS += -Wl,-rpath-link,/usr/lib:/lib
endif
+# INCLUDES += -I/usr/include -Y/usr/include/linux
G++INCLUDES = -I/usr/include/g++
#
# Always set CPU_TAG on Linux.
#
CPU_TAG = _$(CPU_ARCH)
#
@@ -185,16 +197,17 @@ ZLIB_LIBS = -lz
ifeq ($(BUILD_SUN_PKG), 1)
ifeq ($(USE_64), 1)
RPATH = -Wl,-rpath,'$$ORIGIN:/opt/sun/private/lib64:/opt/sun/private/lib'
else
RPATH = -Wl,-rpath,'$$ORIGIN:/opt/sun/private/lib'
endif
endif
+OS_REL_CFLAGS += -DLINUX2_1
MKSHLIB = $(CC) $(DSO_LDOPTS) -Wl,-soname -Wl,$(@:$(OBJDIR)/%.so=%.so) $(RPATH)
ifdef MAPFILE
MKSHLIB += -Wl,--version-script,$(MAPFILE)
endif
PROCESS_MAP_FILE = grep -v ';-' $< | \
sed -e 's,;+,,' -e 's; DATA ;;' -e 's,;;,,' -e 's,;.*,;,' > $@
@@ -202,8 +215,10 @@ ifeq ($(OS_RELEASE),2.4)
DEFINES += -DNO_FORK_CHECK
endif
ifdef USE_GCOV
OS_CFLAGS += --coverage
LDFLAGS += --coverage
DSO_LDOPTS += --coverage
endif
+
+include $(CORE_DEPTH)/coreconf/sanitizers.mk
--- a/security/nss/coreconf/arch.mk
+++ b/security/nss/coreconf/arch.mk
@@ -7,17 +7,17 @@
# Master "Core Components" macros for getting the OS architecture #
# defines these symbols:
# OS_ARCH (from uname -r)
# OS_TEST (from uname -m)
# OS_RELEASE (from uname -v and/or -r)
# OS_TARGET User defined, or set to OS_ARCH
# CPU_ARCH (from unmame -m or -p, ONLY on WINNT)
# OS_CONFIG OS_TARGET + OS_RELEASE
-# OBJDIR_TAG (uses GCOV_TAG, 64BIT_TAG)
+# OBJDIR_TAG (uses ASAN_TAG, GCOV_TAG, 64BIT_TAG)
# OBJDIR_NAME
#######################################################################
#
# Macros for getting the OS architecture
#
OS_ARCH := $(subst /,_,$(shell uname -s))
@@ -110,30 +110,16 @@ ifeq (,$(filter-out Linux FreeBSD IRIX,$
OS_RELEASE := $(shell echo $(OS_RELEASE) | sed 's/-.*//')
endif
ifeq ($(OS_ARCH),Linux)
OS_RELEASE := $(subst ., ,$(OS_RELEASE))
ifneq ($(words $(OS_RELEASE)),1)
OS_RELEASE := $(word 1,$(OS_RELEASE)).$(word 2,$(OS_RELEASE))
endif
- KERNEL = Linux
-endif
-
-# Since all uses of OS_ARCH that follow affect only userland, we can
-# merge other Glibc systems with Linux here.
-ifeq ($(OS_ARCH),GNU)
- OS_ARCH = Linux
- OS_RELEASE = 2.6
- KERNEL = GNU
-endif
-ifeq ($(OS_ARCH),GNU_kFreeBSD)
- OS_ARCH = Linux
- OS_RELEASE = 2.6
- KERNEL = FreeBSD
endif
#
# For OS/2
#
ifeq ($(OS_ARCH),OS_2)
OS_ARCH = OS2
OS_RELEASE := $(shell uname -v)
@@ -263,27 +249,32 @@ endif
OS_CONFIG = $(OS_TARGET)$(OS_RELEASE)
#
# OBJDIR_TAG depends on the predefined variable BUILD_OPT,
# to distinguish between debug and release builds.
#
+ifeq ($(USE_ASAN), 1)
+ ASAN_TAG = _ASAN
+else
+ ASAN_TAG =
+endif
ifeq ($(USE_GCOV), 1)
GCOV_TAG = _GCOV
else
GCOV_TAG =
endif
ifeq ($(USE_64), 1)
64BIT_TAG = _64
else
64BIT_TAG =
endif
-OBJDIR_TAG_BASE=$(GCOV_TAG)$(64BIT_TAG)
+OBJDIR_TAG_BASE=$(ASAN_TAG)$(GCOV_TAG)$(64BIT_TAG)
ifdef BUILD_OPT
OBJDIR_TAG = $(OBJDIR_TAG_BASE)_OPT
else
ifdef BUILD_IDG
OBJDIR_TAG = $(OBJDIR_TAG_BASE)_IDG
else
OBJDIR_TAG = $(OBJDIR_TAG_BASE)_DBG
--- a/security/nss/coreconf/check_cc_clang.py
+++ b/security/nss/coreconf/check_cc_clang.py
@@ -1,21 +1,20 @@
#!/usr/bin/env python
import os
import subprocess
import sys
def main():
if sys.platform == 'win32':
- print(0)
+ print 0
else:
cc = os.environ.get('CC', 'cc')
try:
- cc_is_clang = 'clang' in subprocess.check_output(
- [cc, '--version'], universal_newlines=True)
+ cc_is_clang = 'clang' in subprocess.check_output([cc, '--version'])
except OSError:
# We probably just don't have CC/cc.
cc_is_clang = False
- print(int(cc_is_clang))
+ print int(cc_is_clang)
if __name__ == '__main__':
main()
--- a/security/nss/coreconf/config.gypi
+++ b/security/nss/coreconf/config.gypi
@@ -19,54 +19,49 @@
'conditions': [
['OS=="android"', {
'target_arch%': 'arm',
}, {
# Default architecture we're building for is the architecture we're
# building on.
'target_arch%': '<(host_arch)',
}],
- ['OS=="linux"', {
- # FIPS-140 LOWHASH
- 'freebl_name': 'freeblpriv3',
- }, {
- 'freebl_name': 'freebl3',
- }],
- ['OS=="mac"', {
- 'use_system_sqlite%': 1,
- },{
- 'use_system_sqlite%': 0,
- }],
- ['OS=="mac" or OS=="win"', {
- 'cc_use_gnu_ld%': 0,
- }, {
- 'cc_use_gnu_ld%': 1,
- }],
['OS=="win"', {
'use_system_zlib%': 0,
- 'nspr_libs%': ['libnspr4.lib', 'libplc4.lib', 'libplds4.lib'],
+ 'nspr_libs%': ['nspr4.lib', 'plc4.lib', 'plds4.lib'],
'zlib_libs%': [],
#TODO
'moz_debug_flags%': '',
'dll_prefix': '',
'dll_suffix': 'dll',
}, {
+ 'nspr_libs%': ['-lplds4', '-lplc4', '-lnspr4'],
'use_system_zlib%': 1,
- 'nspr_libs%': ['-lplds4', '-lplc4', '-lnspr4'],
+ }],
+ ['OS=="linux" or OS=="android"', {
'zlib_libs%': ['-lz'],
+ 'moz_debug_flags%': '-gdwarf-2',
+ 'optimize_flags%': '-O2',
'dll_prefix': 'lib',
- 'conditions': [
- ['OS=="mac"', {
- 'moz_debug_flags%': '-gdwarf-2 -gfull',
- 'dll_suffix': 'dylib',
- }, {
- 'moz_debug_flags%': '-gdwarf-2',
- 'dll_suffix': 'so',
- }],
- ],
+ 'dll_suffix': 'so',
+ }],
+ ['OS=="linux"', {
+ 'freebl_name': 'freeblpriv3',
+ }, {
+ 'freebl_name': 'freebl3',
+ }],
+ ['OS=="mac"', {
+ 'zlib_libs%': ['-lz'],
+ 'use_system_sqlite%': 1,
+ 'moz_debug_flags%': '-gdwarf-2 -gfull',
+ 'optimize_flags%': '-O2',
+ 'dll_prefix': 'lib',
+ 'dll_suffix': 'dylib',
+ }, {
+ 'use_system_sqlite%': 0,
}],
['"<(GENERATOR)"=="ninja"', {
'cc_is_clang%': '<!(<(python) <(DEPTH)/coreconf/check_cc_clang.py)',
}, {
'cc_is_clang%': '0',
}],
],
},
@@ -81,97 +76,84 @@
'nspr_lib_dir%': '<(nspr_lib_dir)',
'nspr_include_dir%': '<(nspr_include_dir)',
'use_system_sqlite%': '<(use_system_sqlite)',
'sqlite_libs%': ['-lsqlite3'],
'dll_prefix': '<(dll_prefix)',
'dll_suffix': '<(dll_suffix)',
'freebl_name': '<(freebl_name)',
'cc_is_clang%': '<(cc_is_clang)',
- 'cc_use_gnu_ld%': '<(cc_use_gnu_ld)',
# Some defaults
'disable_tests%': 0,
'disable_chachapoly%': 0,
'disable_dbm%': 0,
'disable_libpkix%': 1,
'disable_werror%': 0,
'mozilla_client%': 0,
'moz_fold_libs%': 0,
'moz_folded_library_name%': '',
'ssl_enable_zlib%': 1,
- 'sanitizer_flags%': 0,
+ 'use_asan%': 0,
+ 'use_ubsan%': 0,
+ 'use_msan%': 0,
+ 'use_sancov%': 0,
'test_build%': 0,
- 'no_zdefs%': 0,
'fuzz%': 0,
- 'fuzz_tls%': 0,
- 'fuzz_oss%': 0,
'sign_libs%': 1,
'use_pprof%': 0,
- 'ct_verif%': 0,
'nss_public_dist_dir%': '<(nss_dist_dir)/public',
'nss_private_dist_dir%': '<(nss_dist_dir)/private',
},
'target_defaults': {
# Settings specific to targets should go here.
# This is mostly for linking to libraries.
'variables': {
'mapfile%': '',
'test_build%': 0,
- 'debug_optimization_level%': '0',
- 'release_optimization_level%': '2',
},
'standalone_static_library': 0,
'include_dirs': [
'<(nspr_include_dir)',
'<(nss_dist_dir)/private/<(module)',
],
'conditions': [
- [ 'OS!="android" and OS!="mac" and OS!="win"', {
+ [ 'OS=="linux"', {
'libraries': [
'-lpthread',
- ],
- }],
- [ 'OS=="linux"', {
- 'libraries': [
'-ldl',
'-lc',
],
}],
- [ 'fuzz==1', {
- 'variables': {
- 'debug_optimization_level%': '1',
- },
- }],
],
'target_conditions': [
# If we want to properly export a static library, and copy it to lib,
# we need to mark it as a 'standalone_static_library'. Otherwise,
# the relative paths in the thin archive will break linking.
[ '_type=="shared_library"', {
'product_dir': '<(nss_dist_obj_dir)/lib'
}, '_type=="executable"', {
'product_dir': '<(nss_dist_obj_dir)/bin'
}, '_standalone_static_library==1', {
'product_dir': '<(nss_dist_obj_dir)/lib'
}],
# mapfile handling
- [ 'mapfile!=""', {
+ [ 'test_build==0 and mapfile!=""', {
# Work around a gyp bug. Fixed upstream but not in Ubuntu packages:
# https://chromium.googlesource.com/external/gyp/+/b85ad3e578da830377dbc1843aa4fbc5af17a192%5E%21/
'sources': [
'<(DEPTH)/coreconf/empty.c',
],
'xcode_settings': {
'OTHER_LDFLAGS': [
'-exported_symbols_list',
'<(INTERMEDIATE_DIR)/out.>(mapfile)',
],
},
'conditions': [
- [ 'cc_use_gnu_ld==1', {
+ [ 'OS=="linux" or OS=="android"', {
'ldflags': [
'-Wl,--version-script,<(INTERMEDIATE_DIR)/out.>(mapfile)',
],
}],
[ 'OS=="win"', {
# On Windows, .def files are used directly as sources.
'sources': [
'>(mapfile)',
@@ -208,32 +190,20 @@
],
'library_dirs': [
'<(nspr_lib_dir)',
],
}],
# Shared library specific settings.
[ '_type=="shared_library"', {
'conditions': [
- [ 'cc_use_gnu_ld==1', {
+ [ 'OS=="linux" or OS=="android"', {
'ldflags': [
'-Wl,--gc-sections',
- ],
- 'conditions': [
- ['OS=="dragonfly" or OS=="freebsd" or OS=="netbsd" or OS=="openbsd"', {
- # Bug 1321317 - unix_rand.c:880: undefined reference to `environ'
- 'ldflags': [
- '-Wl,--warn-unresolved-symbols',
- ],
- }],
- ['no_zdefs==0', {
- 'ldflags': [
- '-Wl,-z,defs',
- ],
- }],
+ '-Wl,-z,defs',
],
}],
],
'xcode_settings': {
'DYLIB_INSTALL_NAME_BASE': '@executable_path',
'DYLIB_COMPATIBILITY_VERSION': '1',
'DYLIB_CURRENT_VERSION': '1',
'OTHER_LDFLAGS': [
@@ -276,46 +246,20 @@
],
},
'conditions': [
[ 'OS=="linux" or OS=="android"', {
'defines': [
'LINUX2_1',
'LINUX',
'linux',
- ],
- }],
- [ 'OS=="dragonfly" or OS=="freebsd"', {
- 'defines': [
- 'FREEBSD',
- ],
- }],
- [ 'OS=="netbsd"', {
- 'defines': [
- 'NETBSD',
- ],
- }],
- [ 'OS=="openbsd"', {
- 'defines': [
- 'OPENBSD',
- ],
- }],
- ['OS=="mac" or OS=="dragonfly" or OS=="freebsd" or OS=="netbsd" or OS=="openbsd"', {
- 'defines': [
- 'HAVE_BSD_FLOCK',
- ],
- }],
- [ 'OS!="win"', {
- 'defines': [
'HAVE_STRERROR',
'XP_UNIX',
'_REENTRANT',
],
- }],
- [ 'OS!="mac" and OS!="win"', {
'cflags': [
'-fPIC',
'-pipe',
'-ffunction-sections',
'-fdata-sections',
],
'cflags_cc': [
'-std=c++0x',
@@ -324,77 +268,114 @@
[ 'target_arch=="ia32"', {
'cflags': ['-m32'],
'ldflags': ['-m32'],
}],
[ 'target_arch=="x64"', {
'cflags': ['-m64'],
'ldflags': ['-m64'],
}],
- ],
- }],
- [ 'use_pprof==1 and OS!="android" and OS!="win"', {
- 'conditions': [
- [ 'OS=="mac"', {
- 'xcode_settings': {
- 'OTHER_LDFLAGS': [ '-lprofiler' ],
- },
- }, {
+ [ 'use_pprof==1' , {
'ldflags': [ '-lprofiler' ],
}],
- [ 'OS!="linux"', {
- 'library_dirs': [
- '/usr/local/lib/',
- ],
- }],
],
}],
- [ 'disable_werror==0 and OS!="android" and OS!="win"', {
+ [ 'disable_werror==0 and (OS=="linux" or OS=="mac")', {
'cflags': [
'<!@(<(python) <(DEPTH)/coreconf/werror.py)',
],
- 'xcode_settings': {
- 'OTHER_CFLAGS': [
- '<!@(<(python) <(DEPTH)/coreconf/werror.py)',
- ],
- },
}],
- [ 'fuzz_tls==1', {
+ [ 'fuzz==1', {
'cflags': [
'-Wno-unused-function',
- ],
+ ]
+ }],
+ [ 'use_asan==1 or use_ubsan==1', {
+ 'cflags': ['-O1'],
'xcode_settings': {
- 'OTHER_CFLAGS': [
- '-Wno-unused-function',
- ],
+ 'GCC_OPTIMIZATION_LEVEL': '1', # -O1
+ }
+ }],
+ [ 'use_asan==1', {
+ 'variables': {
+ 'asan_flags': '<!(<(python) <(DEPTH)/coreconf/sanitizers.py asan)',
+ 'no_ldflags': '<!(<(python) <(DEPTH)/coreconf/sanitizers.py ld)',
},
- }],
- [ 'sanitizer_flags!=0', {
- 'cflags': ['<@(sanitizer_flags)'],
- 'ldflags': ['<@(sanitizer_flags)'],
+ 'cflags': ['<@(asan_flags)'],
+ 'ldflags': ['<@(asan_flags)'],
+ 'ldflags!': ['<@(no_ldflags)'],
'xcode_settings': {
- 'OTHER_CFLAGS': ['<@(sanitizer_flags)'],
+ 'OTHER_CFLAGS': ['<@(asan_flags)'],
+ 'OTHER_LDFLAGS!': ['<@(no_ldflags)'],
# We want to pass -fsanitize=... to our final link call,
# but not to libtool. OTHER_LDFLAGS is passed to both.
# To trick GYP into doing what we want, we'll piggyback on
# LIBRARY_SEARCH_PATHS, producing "-L/usr/lib -fsanitize=...".
# The -L/usr/lib is redundant but innocuous: it's a default path.
- 'LIBRARY_SEARCH_PATHS': ['/usr/lib <(sanitizer_flags)'],
+ 'LIBRARY_SEARCH_PATHS': ['/usr/lib <(asan_flags)'],
+ },
+ }],
+ [ 'use_ubsan==1', {
+ 'variables': {
+ 'ubsan_flags': '<!(<(python) <(DEPTH)/coreconf/sanitizers.py ubsan)',
+ 'no_ldflags': '<!(<(python) <(DEPTH)/coreconf/sanitizers.py ld)',
+ },
+ 'cflags': ['<@(ubsan_flags)'],
+ 'ldflags': ['<@(ubsan_flags)'],
+ 'ldflags!': ['<@(no_ldflags)'],
+ 'xcode_settings': {
+ 'OTHER_CFLAGS': ['<@(ubsan_flags)'],
+ 'OTHER_LDFLAGS!': ['<@(no_ldflags)'],
+ # See comment above.
+ 'LIBRARY_SEARCH_PATHS': ['/usr/lib <(ubsan_flags)'],
+ },
+ }],
+ [ 'use_msan==1', {
+ 'variables': {
+ 'msan_flags': '<!(<(python) <(DEPTH)/coreconf/sanitizers.py msan)',
+ 'no_ldflags': '<!(<(python) <(DEPTH)/coreconf/sanitizers.py ld)',
+ },
+ 'cflags': ['<@(msan_flags)'],
+ 'ldflags': ['<@(msan_flags)'],
+ 'ldflags!': ['<@(no_ldflags)'],
+ 'xcode_settings': {
+ 'OTHER_CFLAGS': ['<@(msan_flags)'],
+ 'OTHER_LDFLAGS!': ['<@(no_ldflags)'],
+ # See comment above.
+ 'LIBRARY_SEARCH_PATHS': ['/usr/lib <(msan_flags)'],
+ },
+ }],
+ [ 'use_sancov!=0', {
+ 'variables': {
+ 'sancov_flags': '<!(<(python) <(DEPTH)/coreconf/sanitizers.py sancov <(use_sancov))',
+ 'no_ldflags': '<!(<(python) <(DEPTH)/coreconf/sanitizers.py ld)',
+ },
+ 'cflags': ['<@(sancov_flags)'],
+ 'ldflags': ['<@(sancov_flags)'],
+ 'ldflags!': ['<@(no_ldflags)'],
+ 'xcode_settings': {
+ 'OTHER_CFLAGS': ['<@(sancov_flags)'],
+ 'OTHER_LDFLAGS!': ['<@(no_ldflags)'],
+ # See comment above.
+ 'LIBRARY_SEARCH_PATHS': ['/usr/lib <(sancov_flags)'],
},
}],
[ 'OS=="android" and mozilla_client==0', {
'defines': [
'NO_SYSINFO',
'NO_FORK_CHECK',
'ANDROID',
],
}],
[ 'OS=="mac"', {
'defines': [
'DARWIN',
+ 'HAVE_STRERROR',
+ 'HAVE_BSD_FLOCK',
+ 'XP_UNIX',
],
'conditions': [
[ 'target_arch=="ia32"', {
'xcode_settings': {
'ARCHS': ['i386'],
},
}],
[ 'target_arch=="x64"', {
@@ -431,16 +412,17 @@
'ImageHasSafeExceptionHandlers': 'false',
},
'VCCLCompilerTool': {
'PreprocessorDefinitions': [
'WIN32',
],
},
},
+
}],
[ 'target_arch=="x64"', {
'msvs_configuration_platform': 'x64',
'msvs_settings': {
'VCLinkerTool': {
'TargetMachine': '17', # x86-64
},
'VCCLCompilerTool': {
@@ -464,57 +446,57 @@
],
}],
],
},
# Common settings for debug should go here.
'Debug': {
'inherit_from': ['Common'],
'conditions': [
- [ 'OS!="mac" and OS!="win"', {
+ [ 'OS=="linux" or OS=="android"', {
'cflags': [
'-g',
'<(moz_debug_flags)',
],
}]
],
#TODO: DEBUG_$USER
'defines': ['DEBUG'],
- 'cflags': [ '-O<(debug_optimization_level)' ],
'xcode_settings': {
'COPY_PHASE_STRIP': 'NO',
- 'GCC_OPTIMIZATION_LEVEL': '<(debug_optimization_level)',
+ 'GCC_OPTIMIZATION_LEVEL': '0',
'GCC_GENERATE_DEBUGGING_SYMBOLS': 'YES',
},
'msvs_settings': {
'VCCLCompilerTool': {
- 'Optimization': '<(debug_optimization_level)',
+ 'Optimization': '0',
'BasicRuntimeChecks': '3',
'RuntimeLibrary': '2', # /MD
},
'VCLinkerTool': {
'LinkIncremental': '1',
},
'VCResourceCompilerTool': {
'PreprocessorDefinitions': ['DEBUG'],
},
},
},
# Common settings for release should go here.
'Release': {
'inherit_from': ['Common'],
- 'defines': ['NDEBUG'],
- 'cflags': [ '-O<(release_optimization_level)' ],
+ 'defines': [
+ 'NDEBUG',
+ ],
'xcode_settings': {
'DEAD_CODE_STRIPPING': 'YES', # -Wl,-dead_strip
- 'GCC_OPTIMIZATION_LEVEL': '<(release_optimization_level)',
+ 'GCC_OPTIMIZATION_LEVEL': '2', # -O2
},
'msvs_settings': {
'VCCLCompilerTool': {
- 'Optimization': '<(release_optimization_level)',
+ 'Optimization': '2', # /Os
'RuntimeLibrary': '2', # /MD
},
'VCLinkerTool': {
'LinkIncremental': '1',
},
},
},
'conditions': [
@@ -529,19 +511,19 @@
'Release_x64': {
'inherit_from': ['Release'],
},
}],
],
},
},
'conditions': [
- [ 'cc_use_gnu_ld==1', {
+ [ 'OS=="linux" or OS=="android"', {
'variables': {
- 'process_map_file': ['/bin/sh', '-c', '/usr/bin/env grep -v ";-" >(mapfile) | sed -e "s,;+,," -e "s; DATA ;;" -e "s,;;,," -e "s,;.*,;," > >@(_outputs)'],
+ 'process_map_file': ['/bin/sh', '-c', '/bin/grep -v ";-" >(mapfile) | sed -e "s,;+,," -e "s; DATA ;;" -e "s,;;,," -e "s,;.*,;," > >@(_outputs)'],
},
}],
[ 'OS=="mac"', {
'variables': {
'process_map_file': ['/bin/sh', '-c', '/usr/bin/grep -v ";+" >(mapfile) | grep -v ";-" | sed -e "s; DATA ;;" -e "s,;;,," -e "s,;.*,," -e "s,^,_," > >@(_outputs)'],
},
}],
],
--- a/security/nss/coreconf/coreconf.dep
+++ b/security/nss/coreconf/coreconf.dep
@@ -5,8 +5,9 @@
/*
* A dummy header file that is a dependency for all the object files.
* Used to force a full recompilation of NSS in Mozilla's Tinderbox
* depend builds. See comments in rules.mk.
*/
#error "Do not include this header file."
+
--- a/security/nss/coreconf/detect_host_arch.py
+++ b/security/nss/coreconf/detect_host_arch.py
@@ -9,17 +9,17 @@ from __future__ import print_function
import fnmatch
import platform
def main():
host_arch = platform.machine().lower()
if host_arch in ('amd64', 'x86_64'):
host_arch = 'x64'
elif fnmatch.fnmatch(host_arch, 'i?86') or host_arch == 'i86pc':
- host_arch = 'ia32'
+ host_arch = 'x64'
elif host_arch.startswith('arm'):
host_arch = 'arm'
elif host_arch.startswith('mips'):
host_arch = 'mips'
print(host_arch)
if __name__ == '__main__':
main()
deleted file mode 100644
--- a/security/nss/coreconf/fuzz.sh
+++ /dev/null
@@ -1,38 +0,0 @@
-#!/usr/bin/env bash
-# This file is used by build.sh to setup fuzzing.
-
-set +e
-
-# Default to clang if CC is not set.
-if [ -z "$CC" ]; then
- command -v clang &> /dev/null 2>&1
- if [ $? != 0 ]; then
- echo "Fuzzing requires clang!"
- exit 1
- fi
- export CC=clang
- export CCC=clang++
- export CXX=clang++
-fi
-
-gyp_params+=(-Dtest_build=1 -Dfuzz=1 -Dsign_libs=0)
-
-# Add debug symbols even for opt builds.
-nspr_params+=(--enable-debug-symbols)
-
-if [ "$fuzz_oss" = 1 ]; then
- gyp_params+=(-Dno_zdefs=1 -Dfuzz_oss=1)
-else
- enable_sanitizer asan
- enable_ubsan
- enable_sancov
-fi
-
-if [ "$fuzz_tls" = 1 ]; then
- gyp_params+=(-Dfuzz_tls=1)
-fi
-
-if [ ! -f "/usr/lib/libFuzzingEngine.a" ]; then
- echo "Cloning libFuzzer files ..."
- run_verbose "$cwd"/fuzz/clone_libfuzzer.sh
-fi
--- a/security/nss/coreconf/nspr.sh
+++ b/security/nss/coreconf/nspr.sh
@@ -1,51 +1,48 @@
-#!/usr/bin/env bash
+#!/bin/bash
# This script builds NSPR for NSS.
#
# This build system is still under development. It does not yet support all
# the features or platforms that the regular NSPR build supports.
# variables
+nspr_opt=()
nspr_cflags=
nspr_cxxflags=
nspr_ldflags=
-# Try to avoid bmake on OS X and BSD systems
-if hash gmake 2>/dev/null; then
- make() { command gmake "$@"; }
-fi
+nspr_sanitizer()
+{
+ nspr_cflags="$nspr_cflags $(python $cwd/coreconf/sanitizers.py $1 $2)"
+ nspr_cxxflags="$nspr_cxxflags $(python $cwd/coreconf/sanitizers.py $1 $2)"
+ nspr_ldflags="$nspr_ldflags $(python $cwd/coreconf/sanitizers.py $1 $2)"
+}
-nspr_set_flags()
+verbose()
{
- nspr_cflags="$CFLAGS $@"
- nspr_cxxflags="$CXXFLAGS $@"
- nspr_ldflags="$LDFLAGS $@"
+ CFLAGS=$nspr_cflags CXXFLAGS=$nspr_cxxflags LDFLAGS=$nspr_ldflags \
+ CC=$CC CXX=$CCC ../configure "${nspr_opt[@]}" --prefix="$obj_dir"
+ make -C "$cwd/../nspr/$target"
+ make -C "$cwd/../nspr/$target" install
}
-nspr_build()
+silent()
{
- local nspr_dir="$cwd"/../nspr/$target
- mkdir -p "$nspr_dir"
-
- # These NSPR options are directory-specific, so they don't need to be
- # included in nspr_opt and changing them doesn't force a rebuild of NSPR.
- extra_params=(--prefix="$dist_dir"/$target)
- if [ "$opt_build" = 1 ]; then
- extra_params+=(--disable-debug --enable-optimize)
- fi
-
- echo "NSPR [1/3] configure ..."
- pushd "$nspr_dir" >/dev/null
- CFLAGS="$nspr_cflags" CXXFLAGS="$nspr_cxxflags" \
- LDFLAGS="$nspr_ldflags" CC="$CC" CXX="$CCC" \
- run_verbose ../configure "${extra_params[@]}" "$@"
- popd >/dev/null
- echo "NSPR [2/3] make ..."
- run_verbose make -C "$nspr_dir"
- echo "NSPR [3/3] install ..."
- run_verbose make -C "$nspr_dir" install
+ echo "[1/3] configure NSPR ..."
+ CFLAGS=$nspr_cflags CXXFLAGS=$nspr_cxxflags LDFLAGS=$nspr_ldflags \
+ CC=$CC CXX=$CCC ../configure "${nspr_opt[@]}" --prefix="$obj_dir" 1> /dev/null
+ echo "[2/3] make NSPR ..."
+ make -C "$cwd/../nspr/$target" 1> /dev/null
+ echo "[3/3] install NSPR ..."
+ make -C "$cwd/../nspr/$target" install 1> /dev/null
}
-nspr_clean()
+build_nspr()
{
- rm -rf "$cwd"/../nspr/$target
+ mkdir -p "$cwd/../nspr/$target"
+ cd "$cwd/../nspr/$target"
+ if [ "$1" == 1 ]; then
+ verbose
+ else
+ silent
+ fi
}
new file mode 100644
--- /dev/null
+++ b/security/nss/coreconf/sanitizers.mk
@@ -0,0 +1,35 @@
+# Address Sanitizer support; include this in OS-specific .mk files
+# *after* defining the variables that are appended to here.
+
+ifeq ($(USE_ASAN), 1)
+SANITIZER_FLAGS_COMMON = -fsanitize=address
+
+ifeq ($(USE_UBSAN), 1)
+SANITIZER_FLAGS_COMMON += -fsanitize=undefined -fno-sanitize-recover=undefined
+endif
+
+ifeq ($(FUZZ), 1)
+SANITIZER_FLAGS_COMMON += -fsanitize-coverage=edge
+endif
+
+SANITIZER_FLAGS_COMMON += $(EXTRA_SANITIZER_FLAGS)
+SANITIZER_CFLAGS = $(SANITIZER_FLAGS_COMMON)
+SANITIZER_LDFLAGS = $(SANITIZER_FLAGS_COMMON)
+OS_CFLAGS += $(SANITIZER_CFLAGS)
+LDFLAGS += $(SANITIZER_LDFLAGS)
+
+# ASan needs frame pointers to save stack traces for allocation/free sites.
+# (Warning: some platforms, like ARM Linux in Thumb mode, don't have useful
+# frame pointers even with this option.)
+SANITIZER_CFLAGS += -fno-omit-frame-pointer -fno-optimize-sibling-calls
+
+ifdef BUILD_OPT
+# You probably want to be able to get debug info for failures, even with an
+# optimized build.
+OPTIMIZER += -g
+else
+# Try maintaining reasonable performance, ASan and UBSan slow things down.
+OPTIMIZER += -O1
+endif
+
+endif
--- a/security/nss/coreconf/sanitizers.py
+++ b/security/nss/coreconf/sanitizers.py
@@ -1,33 +1,36 @@
#!/usr/bin/env python2
from __future__ import print_function
import sys
def main():
if len(sys.argv) < 2:
- raise Exception('Specify either "asan", "msan", "sancov" or "ubsan" as argument.')
+ raise Exception('Specify either "ld", asan", "msan", "sancov" or "ubsan" as argument.')
sanitizer = sys.argv[1]
if sanitizer == "ubsan":
- if len(sys.argv) < 3:
- raise Exception('ubsan requires another argument.')
- print('-fsanitize='+sys.argv[2]+' -fno-sanitize-recover=undefined ', end='')
+ print('-fsanitize=undefined -fno-sanitize-recover=undefined ', end='')
return
if sanitizer == "asan":
print('-fsanitize=address ', end='')
print('-fno-omit-frame-pointer -fno-optimize-sibling-calls ', end='')
return
if sanitizer == "msan":
print('-fsanitize=memory -fsanitize-memory-track-origins ', end='')
print('-fno-omit-frame-pointer -fno-optimize-sibling-calls ', end='')
return
if sanitizer == "sancov":
if len(sys.argv) < 3:
raise Exception('sancov requires another argument (edge|bb|func).')
print('-fsanitize-coverage='+sys.argv[2]+' ', end='')
return
- raise Exception('Specify either "asan", "msan", "sancov" or "ubsan" as argument.')
+ # We have to remove this from the ld flags when building asan.
+ if sanitizer == "ld":
+ print('-Wl,-z,defs ', end='')
+ return
+
+ raise Exception('Specify either "ld", asan", "msan", "sancov" or "ubsan" as argument.')
if __name__ == '__main__':
main()
deleted file mode 100644
--- a/security/nss/coreconf/sanitizers.sh
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/env bash
-# This file is used by build.sh to setup sanitizers.
-
-sanitizer_flags=""
-sanitizers=()
-
-# This tracks what sanitizers are enabled so they don't get enabled twice. This
-# means that doing things that enable the same sanitizer twice (such as enabling
-# both --asan and --fuzz) is order-dependent: only the first is used.
-enable_sanitizer()
-{
- local san="$1"
- for i in "${sanitizers[@]}"; do
- [ "$san" = "$i" ] && return
- done
- sanitizers+=("$san")
-
- if [ -z "$sanitizer_flags" ]; then
- gyp_params+=(-Dno_zdefs=1)
- fi
-
- local cflags=$(python $cwd/coreconf/sanitizers.py "$@")
- sanitizer_flags="$sanitizer_flags $cflags"
-}
-
-enable_sancov()
-{
- local clang_version=$($CC --version | grep -oE '([0-9]{1,}\.)+[0-9]{1,}')
- if [[ ${clang_version:0:1} -lt 4 && ${clang_version:0:1} -eq 3 && ${clang_version:2:1} -lt 9 ]]; then
- echo "Need at least clang-3.9 (better 4.0) for sancov." 1>&2
- exit 1
- fi
-
- local sancov
- if [ -n "$1" ]; then
- sancov="$1"
- elif [ "${clang_version:0:3}" = "3.9" ]; then
- sancov=edge,indirect-calls,8bit-counters
- else
- sancov=trace-pc-guard,trace-cmp
- fi
- enable_sanitizer sancov "$sancov"
-}
-
-enable_ubsan()
-{
- local ubsan
- if [ -n "$1" ]; then
- ubsan="$1"
- else
- ubsan=bool,signed-integer-overflow,shift,vptr
- fi
- enable_sanitizer ubsan "$ubsan"
-}
-
-# Not strictly a sanitizer, but the pattern fits
-scanbuild=()
-enable_scanbuild()
-{
- [ "${#scanbuild[@]}" -gt 0 ] && return
-
- scanbuild=(scan-build)
- if [ -n "$1" ]; then
- scanbuild+=(-o "$1")
- fi
- # pass on CC and CCC to scanbuild
- if [ -n "$CC" ]; then
- scanbuild+=(--use-cc="$CC")
- fi
- if [ -n "$CCC" ]; then
- scanbuild+=(--use-c++="$CCC")
- fi
-}
-
-run_scanbuild()
-{
- "${scanbuild[@]}" "$@"
-}
--- a/security/nss/coreconf/werror.py
+++ b/security/nss/coreconf/werror.py
@@ -2,18 +2,17 @@
import os
import subprocess
def main():
cc = os.environ.get('CC', 'cc')
sink = open(os.devnull, 'wb')
try:
- cc_is_clang = 'clang' in subprocess.check_output(
- [cc, '--version'], universal_newlines=True, stderr=sink)
+ cc_is_clang = 'clang' in subprocess.check_output([cc, '--version'], stderr=sink)
except OSError:
# We probably just don't have CC/cc.
return
def warning_supported(warning):
return subprocess.call([cc, '-x', 'c', '-E', '-Werror',
'-W%s' % warning, os.devnull], stdout=sink, stderr=sink) == 0
def can_enable():
@@ -21,17 +20,16 @@ def main():
if not warning_supported('all'):
return False
# If we aren't clang, make sure we have gcc 4.8 at least
if not cc_is_clang:
try:
v = subprocess.check_output([cc, '-dumpversion'], stderr=sink)
v = v.strip(' \r\n').split('.')
- v = list(map(int, v))
if v[0] < 4 or (v[0] == 4 and v[1] < 8):
# gcc 4.8 minimum
return False
except OSError:
return False
return True
if not can_enable():
deleted file mode 100644
--- a/security/nss/fuzz/asn1_mutators.cc
+++ /dev/null
@@ -1,122 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <assert.h>
-#include <string.h>
-#include <random>
-#include <tuple>
-
-#include "asn1_mutators.h"
-
-using namespace std;
-
-static tuple<uint8_t *, size_t> ParseItem(uint8_t *Data, size_t MaxLength) {
- // Short form. Bit 8 has value "0" and bits 7-1 give the length.
- if ((Data[1] & 0x80) == 0) {
- size_t length = min(static_cast<size_t>(Data[1]), MaxLength - 2);
- return make_tuple(&Data[2], length);
- }
-
- // Constructed, indefinite length. Read until {0x00, 0x00}.
- if (Data[1] == 0x80) {
- void *offset = memmem(&Data[2], MaxLength - 2, "\0", 2);
- size_t length = offset ? (static_cast<uint8_t *>(offset) - &Data[2]) + 2
- : MaxLength - 2;
- return make_tuple(&Data[2], length);
- }
-
- // Long form. Two to 127 octets. Bit 8 of first octet has value "1"
- // and bits 7-1 give the number of additional length octets.
- size_t octets = min(static_cast<size_t>(Data[1] & 0x7f), MaxLength - 2);
-
- // Handle lengths bigger than 32 bits.
- if (octets > 4) {
- // Ignore any further children, assign remaining length.
- return make_tuple(&Data[2] + octets, MaxLength - 2 - octets);
- }
-
- // Parse the length.
- size_t length = 0;
- for (size_t j = 0; j < octets; j++) {
- length = (length << 8) | Data[2 + j];
- }
-
- length = min(length, MaxLength - 2 - octets);
- return make_tuple(&Data[2] + octets, length);
-}
-
-static vector<uint8_t *> ParseItems(uint8_t *Data, size_t Size) {
- vector<uint8_t *> items;
- vector<size_t> lengths;
-
- // The first item is always the whole corpus.
- items.push_back(Data);
- lengths.push_back(Size);
-
- // Can't use iterators here because the `items` vector is modified inside the
- // loop. That's safe as long as we always check `items.size()` before every
- // iteration, and only call `.push_back()` to append new items we found.
- // Items are accessed through `items.at()`, we hold no references.
- for (size_t i = 0; i < items.size(); i++) {
- uint8_t *item = items.at(i);
- size_t remaining = lengths.at(i);
-
- // Empty or primitive items have no children.
- if (remaining == 0 || (0x20 & item[0]) == 0) {
- continue;
- }
-
- while (remaining > 2) {
- uint8_t *content;
- size_t length;
-
- tie(content, length) = ParseItem(item, remaining);
-
- if (length > 0) {
- // Record the item.
- items.push_back(content);
-
- // Record the length for further parsing.
- lengths.push_back(length);
- }
-
- // Reduce number of bytes left in current item.
- remaining -= length + (content - item);
-
- // Skip the item we just parsed.
- item = content + length;
- }
- }
-
- return items;
-}
-
-size_t ASN1MutatorFlipConstructed(uint8_t *Data, size_t Size, size_t MaxSize,
- unsigned int Seed) {
- auto items = ParseItems(Data, Size);
-
- std::mt19937 rng(Seed);
- std::uniform_int_distribution<size_t> dist(0, items.size() - 1);
- uint8_t *item = items.at(dist(rng));
-
- // Flip "constructed" type bit.
- item[0] ^= 0x20;
-
- return Size;
-}
-
-size_t ASN1MutatorChangeType(uint8_t *Data, size_t Size, size_t MaxSize,
- unsigned int Seed) {
- auto items = ParseItems(Data, Size);
-
- std::mt19937 rng(Seed);
- std::uniform_int_distribution<size_t> dist(0, items.size() - 1);
- uint8_t *item = items.at(dist(rng));
-
- // Change type to a random int [0, 30].
- static std::uniform_int_distribution<size_t> tdist(0, 30);
- item[0] = tdist(rng);
-
- return Size;
-}
deleted file mode 100644
--- a/security/nss/fuzz/asn1_mutators.h
+++ /dev/null
@@ -1,16 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef asn1_mutators_h__
-#define asn1_mutators_h__
-
-#include <stdint.h>
-#include <cstddef>
-
-size_t ASN1MutatorFlipConstructed(uint8_t *Data, size_t Size, size_t MaxSize,
- unsigned int Seed);
-size_t ASN1MutatorChangeType(uint8_t *Data, size_t Size, size_t MaxSize,
- unsigned int Seed);
-
-#endif // asn1_mutators_h__
deleted file mode 100644
--- a/security/nss/fuzz/certDN_target.cc
+++ /dev/null
@@ -1,45 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <string>
-
-#include "shared.h"
-
-#define TEST_FUNCTION(f) \
- out = f(certName); \
- free(out);
-
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
- std::string name(data, data + size);
-
- assert(SECOID_Init() == SECSuccess);
-
- CERTName* certName = CERT_AsciiToName(name.c_str());
- if (certName) {
- char* out;
- TEST_FUNCTION(CERT_NameToAscii)
- TEST_FUNCTION(CERT_GetCertEmailAddress)
-
- // These functions call CERT_GetNameElement with different OIDs.
- // Unfotunately CERT_GetNameElement is not accesible from here.
- TEST_FUNCTION(CERT_GetCertUid)
- TEST_FUNCTION(CERT_GetCommonName)
- TEST_FUNCTION(CERT_GetCountryName)
- TEST_FUNCTION(CERT_GetDomainComponentName)
- TEST_FUNCTION(CERT_GetLocalityName)
- TEST_FUNCTION(CERT_GetOrgName)
- TEST_FUNCTION(CERT_GetOrgUnitName)
- TEST_FUNCTION(CERT_GetStateName)
-
- out = CERT_NameToAsciiInvertible(certName, CERT_N2A_READABLE);
- free(out);
- out = CERT_NameToAsciiInvertible(certName, CERT_N2A_STRICT);
- free(out);
- out = CERT_NameToAsciiInvertible(certName, CERT_N2A_INVERTIBLE);
- free(out);
- }
- CERT_DestroyName(certName);
-
- return 0;
-}
--- a/security/nss/fuzz/clone_corpus.sh
+++ b/security/nss/fuzz/clone_corpus.sh
@@ -1,4 +1,4 @@
#!/bin/sh
d=$(dirname $0)
-$d/git-copy.sh https://github.com/mozilla/nss-fuzzing-corpus master $d/corpus
+exec $d/git-copy.sh https://github.com/mozilla/nss-fuzzing-corpus master $d/corpus
--- a/security/nss/fuzz/clone_libfuzzer.sh
+++ b/security/nss/fuzz/clone_libfuzzer.sh
@@ -1,46 +1,4 @@
#!/bin/sh
d=$(dirname $0)
-$d/git-copy.sh https://chromium.googlesource.com/chromium/llvm-project/llvm/lib/Fuzzer 0b27dad707a1d67ec854423e25b1a521c9d5ab7a $d/libFuzzer
-
-# [https://llvm.org/bugs/show_bug.cgi?id=31318]
-# This prevents a known buffer overrun that won't be fixed as the affected code
-# will go away in the near future. Until that is we have to patch it as we seem
-# to constantly run into it.
-cat <<EOF | patch -p0 -d $d
-diff --git libFuzzer/FuzzerLoop.cpp libFuzzer/FuzzerLoop.cpp
---- libFuzzer/FuzzerLoop.cpp
-+++ libFuzzer/FuzzerLoop.cpp
-@@ -476,6 +476,9 @@
- uint8_t dummy;
- ExecuteCallback(&dummy, 0);
-
-+ // Number of counters might have changed.
-+ PrepareCounters(&MaxCoverage);
-+
- for (const auto &U : *InitialCorpus) {
- if (size_t NumFeatures = RunOne(U)) {
- CheckExitOnSrcPosOrItem();
-EOF
-
-# Latest Libfuzzer uses __sanitizer_dump_coverage(), a symbol to be introduced
-# with LLVM 4.0. To keep our code working with LLVM 3.x to simplify development
-# of fuzzers we'll just provide it ourselves.
-cat <<EOF | patch -p0 -d $d
-diff --git libFuzzer/FuzzerTracePC.cpp libFuzzer/FuzzerTracePC.cpp
---- libFuzzer/FuzzerTracePC.cpp
-+++ libFuzzer/FuzzerTracePC.cpp
-@@ -31,6 +31,12 @@
- __sancov_trace_pc_guard_8bit_counters[fuzzer::TracePC::kNumPCs];
- uintptr_t __sancov_trace_pc_pcs[fuzzer::TracePC::kNumPCs];
-
-+#if defined(__clang_major__) && (__clang_major__ == 3)
-+void __sanitizer_dump_coverage(const uintptr_t *pcs, uintptr_t len) {
-+ // SanCov in LLVM 4.x will provide this symbol. Make 3.x work.
-+}
-+#endif
-+
- namespace fuzzer {
-
- TracePC TPC;
-EOF
+exec $d/git-copy.sh https://chromium.googlesource.com/chromium/llvm-project/llvm/lib/Fuzzer 1b543d6e5073b56be214394890c9193979a3d7e1 $d/libFuzzer
--- a/security/nss/fuzz/fuzz.gyp
+++ b/security/nss/fuzz/fuzz.gyp
@@ -1,157 +1,65 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
{
'includes': [
'../coreconf/config.gypi',
+ '../cmd/platlibs.gypi'
],
- 'target_defaults': {
- 'variables': {
- 'debug_optimization_level': '2',
- },
- 'target_conditions': [
- [ '_type=="executable"', {
- 'libraries!': [
- '<@(nspr_libs)',
- ],
- 'libraries': [
- '<(nss_dist_obj_dir)/lib/libplds4.a',
- '<(nss_dist_obj_dir)/lib/libnspr4.a',
- '<(nss_dist_obj_dir)/lib/libplc4.a',
- ],
- }],
- ],
- },
'targets': [
{
- 'target_name': 'fuzz_base',
- 'dependencies': [
- '<(DEPTH)/lib/certdb/certdb.gyp:certdb',
- '<(DEPTH)/lib/certhigh/certhigh.gyp:certhi',
- '<(DEPTH)/lib/cryptohi/cryptohi.gyp:cryptohi',
- '<(DEPTH)/lib/base/base.gyp:nssb',
- '<(DEPTH)/lib/dev/dev.gyp:nssdev',
- '<(DEPTH)/lib/pki/pki.gyp:nsspki',
- '<(DEPTH)/lib/util/util.gyp:nssutil',
- '<(DEPTH)/lib/nss/nss.gyp:nss_static',
- '<(DEPTH)/lib/pkcs7/pkcs7.gyp:pkcs7',
- # This is a static build of pk11wrap, softoken, and freebl.
- '<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap_static',
+ 'target_name': 'libFuzzer',
+ 'type': 'static_library',
+ 'sources': [
+ 'libFuzzer/FuzzerCrossOver.cpp',
+ 'libFuzzer/FuzzerDriver.cpp',
+ 'libFuzzer/FuzzerExtFunctionsDlsym.cpp',
+ 'libFuzzer/FuzzerExtFunctionsWeak.cpp',
+ 'libFuzzer/FuzzerIO.cpp',
+ 'libFuzzer/FuzzerLoop.cpp',
+ 'libFuzzer/FuzzerMutate.cpp',
+ 'libFuzzer/FuzzerSHA1.cpp',
+ 'libFuzzer/FuzzerTracePC.cpp',
+ 'libFuzzer/FuzzerTraceState.cpp',
+ 'libFuzzer/FuzzerUtil.cpp',
+ 'libFuzzer/FuzzerUtilDarwin.cpp',
+ 'libFuzzer/FuzzerUtilLinux.cpp',
],
- 'conditions': [
- ['fuzz_oss==0', {
- 'type': 'static_library',
- 'sources': [
- '<!@(ls <(DEPTH)/fuzz/libFuzzer/*.cpp)',
- ],
- 'cflags/': [
- ['exclude', '-fsanitize-coverage'],
- ],
- 'xcode_settings': {
- 'OTHER_CFLAGS/': [
- ['exclude', '-fsanitize-coverage'],
- ],
- },
- 'direct_dependent_settings': {
- 'include_dirs': [
- 'libFuzzer',
- ],
- },
- }, {
- 'type': 'none',
- 'direct_dependent_settings': {
- 'libraries': ['-lFuzzingEngine'],
- }
- }]
+ 'cflags': [
+ '-O2',
+ ],
+ 'cflags/': [
+ ['exclude', '-fsanitize='],
+ ['exclude', '-fsanitize-'],
],
+ 'xcode_settings': {
+ 'GCC_OPTIMIZATION_LEVEL': '2', # -O2
+ 'OTHER_CFLAGS/': [
+ ['exclude', '-fsanitize='],
+ ['exclude', '-fsanitize-'],
+ ],
+ },
},
{
- 'target_name': 'nssfuzz-pkcs8',
+ 'target_name': 'nssfuzz',
'type': 'executable',
'sources': [
- 'asn1_mutators.cc',
+ 'nssfuzz.cc',
'pkcs8_target.cc',
+ 'quickder_targets.cc',
],
'dependencies': [
'<(DEPTH)/exports.gyp:nss_exports',
- 'fuzz_base',
- ],
- },
- {
- 'target_name': 'nssfuzz-quickder',
- 'type': 'executable',
- 'sources': [
- 'asn1_mutators.cc',
- 'quickder_target.cc',
- ],
- 'dependencies': [
- '<(DEPTH)/exports.gyp:nss_exports',
- 'fuzz_base',
- ],
- },
- {
- 'target_name': 'nssfuzz-hash',
- 'type': 'executable',
- 'sources': [
- 'hash_target.cc',
- ],
- 'dependencies': [
- '<(DEPTH)/exports.gyp:nss_exports',
- 'fuzz_base',
- ],
- },
- {
- 'target_name': 'nssfuzz-mpi',
- 'type': 'executable',
- 'sources': [
- 'mpi_target.cc',
- ],
- 'dependencies': [
- '<(DEPTH)/exports.gyp:nss_exports',
- 'fuzz_base',
- ],
- 'conditions': [
- [ 'fuzz_oss==1', {
- 'libraries': [
- '/usr/lib/x86_64-linux-gnu/libcrypto.a',
- ],
- }, {
- 'libraries': [
- '-lcrypto',
- ],
- }],
- ],
- 'include_dirs': [
- '<(DEPTH)/lib/freebl/mpi',
- ],
- },
- {
- 'target_name': 'nssfuzz-certDN',
- 'type': 'executable',
- 'sources': [
- 'certDN_target.cc',
- ],
- 'dependencies': [
- '<(DEPTH)/exports.gyp:nss_exports',
- 'fuzz_base',
- ],
- },
- {
- 'target_name': 'nssfuzz',
- 'type': 'none',
- 'dependencies': [
- 'nssfuzz-certDN',
- 'nssfuzz-hash',
- 'nssfuzz-pkcs8',
- 'nssfuzz-quickder',
- ],
- 'conditions': [
- ['OS=="linux"', {
- 'dependencies': [
- 'nssfuzz-mpi',
- ],
- }],
- ],
+ 'libFuzzer',
+ ]
}
],
+ 'target_defaults': {
+ 'include_dirs': [
+ 'libFuzzer',
+ ],
+ },
+ 'variables': {
+ 'module': 'nss',
+ }
}
deleted file mode 100644
--- a/security/nss/fuzz/hash_target.cc
+++ /dev/null
@@ -1,39 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <memory>
-#include <vector>
-
-#include "hasht.h"
-#include "pk11pub.h"
-#include "secoidt.h"
-#include "shared.h"
-
-const std::vector<SECOidTag> algos = {SEC_OID_MD5, SEC_OID_SHA1, SEC_OID_SHA256,
- SEC_OID_SHA384, SEC_OID_SHA512};
-
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
- uint8_t hashOut[HASH_LENGTH_MAX];
-
- static std::unique_ptr<NSSDatabase> db(new NSSDatabase());
- assert(db != nullptr);
-
- // simple hashing.
- for (auto algo : algos) {
- assert(PK11_HashBuf(algo, hashOut, data, size) == SECSuccess);
- }
-
- // hashing with context.
- for (auto algo : algos) {
- unsigned int len = 0;
- PK11Context *context = PK11_CreateDigestContext(algo);
- assert(context != nullptr);
- assert(PK11_DigestBegin(context) == SECSuccess);
- assert(PK11_DigestFinal(context, hashOut, &len, HASH_LENGTH_MAX) ==
- SECSuccess);
- PK11_DestroyContext(context, PR_TRUE);
- }
-
- return 0;
-}
deleted file mode 100644
--- a/security/nss/fuzz/mpi_target.cc
+++ /dev/null
@@ -1,177 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
- * This target fuzzes NSS mpi against openssl bignum.
- * It therefore requires openssl to be installed.
- */
-
-#include <algorithm>
-#include <iostream>
-#include <string>
-
-#include "hasht.h"
-#include "mpi.h"
-#include "shared.h"
-
-#include <openssl/bn.h>
-
-#define CLEAR_NUMS \
- mp_zero(&c); \
- BN_zero(C); \
- mp_zero(&r); \
- BN_zero(R);
-
-// Check that the two numbers are equal.
-void check_equal(BIGNUM *b, mp_int *m, size_t max_size) {
- char *bnBc = BN_bn2hex(b);
- char mpiMc[max_size];
- mp_tohex(m, mpiMc);
- std::string bnA(bnBc);
- std::string mpiA(mpiMc);
- OPENSSL_free(bnBc);
- // We have to strip leading zeros from bignums, ignoring the sign.
- if (bnA.at(0) != '-') {
- bnA.erase(0, std::min(bnA.find_first_not_of('0'), bnA.size() - 1));
- } else if (bnA.at(1) == '0') {
- bnA.erase(1, std::min(bnA.find_first_not_of('0', 1) - 1, bnA.size() - 1));
- }
-
- if (mpiA != bnA) {
- std::cout << "openssl: " << std::hex << bnA << std::endl;
- std::cout << "nss: " << std::hex << mpiA << std::endl;
- }
-
- assert(mpiA == bnA);
-}
-
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
- // We require at least size 3 to get two integers from Data.
- if (size <= 3) {
- return 0;
- }
- size_t max_size = 2 * size + 1;
-
- mp_int a, b, c, r;
- BN_CTX *ctx = BN_CTX_new();
- BN_CTX_start(ctx);
- BIGNUM *A = BN_CTX_get(ctx);
- BIGNUM *B = BN_CTX_get(ctx);
- BIGNUM *C = BN_CTX_get(ctx);
- BIGNUM *R = BN_CTX_get(ctx);
- assert(mp_init(&a) == MP_OKAY);
- assert(mp_init(&b) == MP_OKAY);
- assert(mp_init(&c) == MP_OKAY);
- assert(mp_init(&r) == MP_OKAY);
-
- // Note that b might overlap a.
- size_t len = (size_t)size / 2;
- assert(mp_read_raw(
- &a, reinterpret_cast<char *>(const_cast<unsigned char *>(data)),
- len) == MP_OKAY);
- assert(mp_read_raw(
- &b,
- reinterpret_cast<char *>(const_cast<unsigned char *>(data)) + len,
- len) == MP_OKAY);
- // Force a positive sign.
- // TODO: add tests for negatives.
- MP_SIGN(&a) = MP_ZPOS;
- MP_SIGN(&b) = MP_ZPOS;
-
- // Skip the first byte as it's interpreted as sign by NSS.
- assert(BN_bin2bn(data + 1, len - 1, A) != nullptr);
- assert(BN_bin2bn(data + len + 1, len - 1, B) != nullptr);
-
- check_equal(A, &a, max_size);
- check_equal(B, &b, max_size);
-
- // Addition
- assert(mp_add(&a, &b, &c) == MP_OKAY);
- (void)BN_add(C, A, B);
- check_equal(C, &c, max_size);
-
- // Subtraction
- CLEAR_NUMS
- assert(mp_sub(&a, &b, &c) == MP_OKAY);
- (void)BN_sub(C, A, B);
- check_equal(C, &c, max_size);
-
- // Sqr
- CLEAR_NUMS
- assert(mp_sqr(&a, &c) == MP_OKAY);
- (void)BN_sqr(C, A, ctx);
- check_equal(C, &c, max_size);
-
- // We can't divide by 0.
- if (mp_cmp_z(&b) != 0) {
- CLEAR_NUMS
- assert(mp_div(&a, &b, &c, &r) == MP_OKAY);
- BN_div(C, R, A, B, ctx);
- check_equal(C, &c, max_size);
- check_equal(R, &r, max_size);
-
- // Modulo
- CLEAR_NUMS
- assert(mp_mod(&a, &b, &c) == MP_OKAY);
- (void)BN_mod(C, A, B, ctx);
- check_equal(C, &c, max_size);
-
- // Mod sqr
- CLEAR_NUMS
- assert(mp_sqrmod(&a, &b, &c) == MP_OKAY);
- (void)BN_mod_sqr(C, A, B, ctx);
- check_equal(C, &c, max_size);
- }
-
- // Mod add
- CLEAR_NUMS
- mp_add(&a, &b, &r);
- (void)BN_add(R, A, B);
- assert(mp_addmod(&a, &b, &r, &c) == MP_OKAY);
- (void)BN_mod_add(C, A, B, R, ctx);
- check_equal(C, &c, max_size);
-
- // Mod sub
- CLEAR_NUMS
- mp_add(&a, &b, &r);
- (void)BN_add(R, A, B);
- assert(mp_submod(&a, &b, &r, &c) == MP_OKAY);
- (void)BN_mod_sub(C, A, B, R, ctx);
- check_equal(C, &c, max_size);
-
- // Mod mul
- CLEAR_NUMS
- mp_add(&a, &b, &r);
- (void)BN_add(R, A, B);
- assert(mp_mulmod(&a, &b, &r, &c) == MP_OKAY);
- (void)BN_mod_mul(C, A, B, R, ctx);
- check_equal(C, &c, max_size);
-
- // Mod exp
- // NOTE: This must be the last test as we change b!
- CLEAR_NUMS
- mp_add(&a, &b, &r);
- mp_add_d(&r, 1, &r); // NSS doesn't allow 0 as modulus here.
- size_t num = MP_USED(&b) * MP_DIGIT_BIT;
- mp_div_2d(&b, num, &b, nullptr); // make the exponent smaller, larger
- // exponents need too much memory
- MP_USED(&b) = 1;
- (void)BN_add(R, A, B);
- BN_add_word(R, 1);
- BN_rshift(B, B, num);
- check_equal(B, &b, max_size);
- assert(mp_exptmod(&a, &b, &r, &c) == MP_OKAY);
- (void)BN_mod_exp(C, A, B, R, ctx);
- check_equal(C, &c, max_size);
-
- mp_clear(&a);
- mp_clear(&b);
- mp_clear(&c);
- mp_clear(&r);
-
- BN_CTX_end(ctx);
- BN_CTX_free(ctx);
-
- return 0;
-}
new file mode 100644
--- /dev/null
+++ b/security/nss/fuzz/nssfuzz.cc
@@ -0,0 +1,148 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <iomanip>
+#include <iostream>
+#include <memory>
+
+#include "keyhi.h"
+#include "pk11pub.h"
+
+#include "FuzzerInternal.h"
+#include "registry.h"
+#include "shared.h"
+
+using namespace std;
+
+class Args {
+ public:
+ Args(int argc, char **argv) : args_(argv, argv + argc) {}
+
+ string &operator[](const int idx) { return args_[idx]; }
+
+ bool Has(const string &arg) {
+ return any_of(args_.begin(), args_.end(),
+ [&arg](string &a) { return a.find(arg) == 0; });
+ }
+
+ void Append(const string &arg) { args_.push_back(arg); }
+
+ void Remove(const int index) {
+ assert(index < count());
+ args_.erase(args_.begin() + index);
+ }
+
+ vector<char *> argv() {
+ vector<char *> out;
+ out.resize(count());
+
+ transform(args_.begin(), args_.end(), out.begin(),
+ [](string &a) { return const_cast<char *>(a.c_str()); });
+
+ return out;
+ }
+
+ size_t count() { return args_.size(); }
+
+ private:
+ vector<string> args_;
+};
+
+void printUsage(Args &args) {
+ size_t sep = args[0].rfind("/") + 1;
+ string progName = args[0].substr(sep);
+
+ cerr << progName << " - Various libFuzzer targets for NSS" << endl << endl;
+ cerr << "Usage: " << progName << " <target> <libFuzzer options>" << endl
+ << endl;
+ cerr << "Valid targets:" << endl;
+
+ vector<string> names = Registry::Names();
+
+ // Find length of the longest name.
+ size_t name_w =
+ max_element(names.begin(), names.end(), [](string &a, string &b) {
+ return a.size() < b.size();
+ })->size();
+
+ // Find length of the longest description.
+ auto max = max_element(names.begin(), names.end(), [](string &a, string &b) {
+ return Registry::Desc(a).size() < Registry::Desc(b).size();
+ });
+ size_t desc_w = Registry::Desc(*max).size();
+
+ // Print list of targets.
+ for (string name : names) {
+ cerr << " " << left << setw(name_w) << name << " - " << setw(desc_w)
+ << Registry::Desc(name)
+ << " [default max_len=" << Registry::MaxLen(name) << "]" << endl;
+ }
+
+ // Some usage examples.
+ cerr << endl << "Run fuzzer with a given corpus directory:" << endl;
+ cerr << " " << progName << " <target> /path/to/corpus" << endl;
+
+ cerr << endl << "Run fuzzer with a single test input:" << endl;
+ cerr << " " << progName
+ << " <target> ./crash-14d4355b971092e39572bc306a135ddf9f923e19" << endl;
+
+ cerr << endl
+ << "Specify the number of cores you wish to dedicate to fuzzing:"
+ << endl;
+ cerr << " " << progName << " <target> -jobs=8 -workers=8 /path/to/corpus"
+ << endl;
+
+ cerr << endl << "Override the maximum length of a test input:" << endl;
+ cerr << " " << progName << " <target> -max_len=2048 /path/to/corpus" << endl;
+
+ cerr << endl
+ << "Minimize a given corpus and put the result into 'new_corpus':"
+ << endl;
+ cerr << " " << progName
+ << " <target> -merge=1 -max_len=50000 ./new_corpus /path/to/corpus"
+ << endl;
+
+ cerr << endl << "Merge new test inputs into a corpus:" << endl;
+ cerr
+ << " " << progName
+ << " <target> -merge=1 -max_len=50000 /path/to/corpus ./inputs1 ./inputs2"
+ << endl;
+
+ cerr << endl << "Print libFuzzer usage information:" << endl;
+ cerr << " " << progName << " <target> -help=1" << endl << endl;
+
+ cerr << "Check out the docs at http://llvm.org/docs/LibFuzzer.html" << endl;
+}
+
+int main(int argc, char **argv) {
+ Args args(argc, argv);
+
+ if (args.count() < 2 || !Registry::Has(args[1])) {
+ printUsage(args);
+ return 1;
+ }
+
+ string targetName(args[1]);
+
+ // Remove the target argument when -workers=x or -jobs=y is NOT given.
+ // If both are given, libFuzzer will spawn multiple processes for the target.
+ if (!args.Has("-workers=") || !args.Has("-jobs=")) {
+ args.Remove(1);
+ }
+
+ // Set default max_len arg, if none given and we're not merging.
+ if (!args.Has("-max_len=") && !args.Has("-merge=1")) {
+ uint16_t maxLen = Registry::MaxLen(targetName);
+ args.Append("-max_len=" + to_string(maxLen));
+ }
+
+ // Hand control to the libFuzzer driver.
+ vector<char *> args_new(args.argv());
+ argc = args_new.size();
+ argv = args_new.data();
+
+ return fuzzer::FuzzerDriver(&argc, &argv, Registry::Func(targetName));
+}
--- a/security/nss/fuzz/pkcs8_target.cc
+++ b/security/nss/fuzz/pkcs8_target.cc
@@ -1,22 +1,25 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include <assert.h>
+#include <stdint.h>
#include <memory>
-#include <vector>
#include "keyhi.h"
#include "pk11pub.h"
-#include "asn1_mutators.h"
+#include "registry.h"
#include "shared.h"
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
+extern "C" int pkcs8_fuzzing_target(const uint8_t *Data, size_t Size) {
SECItem data = {siBuffer, (unsigned char *)Data, (unsigned int)Size};
static std::unique_ptr<NSSDatabase> db(new NSSDatabase());
assert(db != nullptr);
PK11SlotInfo *slot = PK11_GetInternalSlot();
assert(slot != nullptr);
@@ -26,14 +29,9 @@ extern "C" int LLVMFuzzerTestOneInput(co
nullptr) == SECSuccess) {
SECKEY_DestroyPrivateKey(key);
}
PK11_FreeSlot(slot);
return 0;
}
-extern "C" size_t LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size,
- size_t MaxSize, unsigned int Seed) {
- static Mutators mutators = {&ASN1MutatorFlipConstructed,
- &ASN1MutatorChangeType};
- return CustomMutate(mutators, Data, Size, MaxSize, Seed);
-}
+REGISTER_FUZZING_TARGET("pkcs8", pkcs8_fuzzing_target, 2048, "PKCS#8 Import")
deleted file mode 100644
--- a/security/nss/fuzz/quickder_target.cc
+++ /dev/null
@@ -1,85 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "asn1_mutators.h"
-#include "shared.h"
-
-const std::vector<const SEC_ASN1Template *> templates = {
- CERT_AttributeTemplate,
- CERT_CertExtensionTemplate,
- CERT_CertificateRequestTemplate,
- CERT_CertificateTemplate,
- CERT_CrlTemplate,
- CERT_IssuerAndSNTemplate,
- CERT_NameTemplate,
- CERT_PublicKeyAndChallengeTemplate,
- CERT_RDNTemplate,
- CERT_SequenceOfCertExtensionTemplate,
- CERT_SetOfAttributeTemplate,
- CERT_SetOfSignedCrlTemplate,
- CERT_SignedCrlTemplate,
- CERT_SignedDataTemplate,
- CERT_SubjectPublicKeyInfoTemplate,
- CERT_TimeChoiceTemplate,
- CERT_ValidityTemplate,
- SEC_AnyTemplate,
- SEC_BitStringTemplate,
- SEC_BMPStringTemplate,
- SEC_BooleanTemplate,
- SEC_CertSequenceTemplate,
- SEC_EnumeratedTemplate,
- SEC_GeneralizedTimeTemplate,
- SEC_IA5StringTemplate,
- SEC_IntegerTemplate,
- SEC_NullTemplate,
- SEC_ObjectIDTemplate,
- SEC_OctetStringTemplate,
- SEC_PointerToAnyTemplate,
- SEC_PointerToEnumeratedTemplate,
- SEC_PointerToGeneralizedTimeTemplate,
- SEC_PointerToOctetStringTemplate,
- SEC_PrintableStringTemplate,
- SEC_SetOfAnyTemplate,
- SEC_SetOfEnumeratedTemplate,
- SEC_SequenceOfAnyTemplate,
- SEC_SequenceOfObjectIDTemplate,
- SEC_SignedCertificateTemplate,
- SEC_SkipTemplate,
- SEC_T61StringTemplate,
- SEC_UniversalStringTemplate,
- SEC_UTCTimeTemplate,
- SEC_UTF8StringTemplate,
- SEC_VisibleStringTemplate,
- SECKEY_DHParamKeyTemplate,
- SECKEY_DHPublicKeyTemplate,
- SECKEY_DSAPrivateKeyExportTemplate,
- SECKEY_DSAPublicKeyTemplate,
- SECKEY_PQGParamsTemplate,
- SECKEY_PrivateKeyInfoTemplate,
- SECKEY_RSAPSSParamsTemplate,
- SECKEY_RSAPublicKeyTemplate,
- SECOID_AlgorithmIDTemplate};
-
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
- char *dest[2048];
-
- for (auto tpl : templates) {
- PORTCheapArenaPool pool;
- SECItem buf = {siBuffer, const_cast<unsigned char *>(Data),
- static_cast<unsigned int>(Size)};
-
- PORT_InitCheapArena(&pool, DER_DEFAULT_CHUNKSIZE);
- (void)SEC_QuickDERDecodeItem(&pool.arena, dest, tpl, &buf);
- PORT_DestroyCheapArena(&pool);
- }
-
- return 0;
-}
-
-extern "C" size_t LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size,
- size_t MaxSize, unsigned int Seed) {
- static Mutators mutators = {&ASN1MutatorFlipConstructed,
- &ASN1MutatorChangeType};
- return CustomMutate(mutators, Data, Size, MaxSize, Seed);
-}
new file mode 100644
--- /dev/null
+++ b/security/nss/fuzz/quickder_targets.cc
@@ -0,0 +1,36 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <stdint.h>
+
+#include "cert.h"
+
+#include "registry.h"
+
+void QuickDERDecode(void *dst, const SEC_ASN1Template *tpl, const uint8_t *buf,
+ size_t len) {
+ PORTCheapArenaPool pool;
+ SECItem data = {siBuffer, const_cast<unsigned char *>(buf),
+ static_cast<unsigned int>(len)};
+
+ PORT_InitCheapArena(&pool, DER_DEFAULT_CHUNKSIZE);
+ (void)SEC_QuickDERDecodeItem(&pool.arena, dst, tpl, &data);
+ PORT_DestroyCheapArena(&pool);
+}
+
+extern "C" int cert_fuzzing_target(const uint8_t *Data, size_t Size) {
+ CERTCertificate cert;
+ QuickDERDecode(&cert, SEC_SignedCertificateTemplate, Data, Size);
+ return 0;
+}
+
+REGISTER_FUZZING_TARGET("cert", cert_fuzzing_target, 3072, "Certificate Import")
+
+extern "C" int spki_fuzzing_target(const uint8_t *Data, size_t Size) {
+ CERTSubjectPublicKeyInfo spki;
+ QuickDERDecode(&spki, CERT_SubjectPublicKeyInfoTemplate, Data, Size);
+ return 0;
+}
+
+REGISTER_FUZZING_TARGET("spki", spki_fuzzing_target, 1024, "SPKI Import")
new file mode 100644
--- /dev/null
+++ b/security/nss/fuzz/registry.h
@@ -0,0 +1,71 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef registry_h__
+#define registry_h__
+
+#include <map>
+#include "FuzzerInternal.h"
+#include "nss.h"
+
+class Registry {
+ public:
+ static void Add(std::string name, fuzzer::UserCallback func, uint16_t max_len,
+ std::string desc) {
+ assert(!Has(name));
+ GetInstance().targets_[name] = TargetData(func, max_len, desc);
+ }
+
+ static bool Has(std::string name) {
+ return GetInstance().targets_.count(name) > 0;
+ }
+
+ static fuzzer::UserCallback Func(std::string name) {
+ assert(Has(name));
+ return std::get<0>(Get(name));
+ }
+
+ static uint16_t MaxLen(std::string name) {
+ assert(Has(name));
+ return std::get<1>(Get(name));
+ }
+
+ static std::string& Desc(std::string name) {
+ assert(Has(name));
+ return std::get<2>(Get(name));
+ }
+
+ static std::vector<std::string> Names() {
+ std::vector<std::string> names;
+ for (auto& it : GetInstance().targets_) {
+ names.push_back(it.first);
+ }
+ return names;
+ }
+
+ private:
+ typedef std::tuple<fuzzer::UserCallback, uint16_t, std::string> TargetData;
+
+ static Registry& GetInstance() {
+ static Registry registry;
+ return registry;
+ }
+
+ static TargetData& Get(std::string name) {
+ return GetInstance().targets_[name];
+ }
+
+ Registry() {}
+
+ std::map<std::string, TargetData> targets_;
+};
+
+#define REGISTER_FUZZING_TARGET(name, func, max_len, desc) \
+ static void __attribute__((constructor)) Register_##func() { \
+ Registry::Add(name, func, max_len, desc); \
+ }
+
+#endif // registry_h__
--- a/security/nss/fuzz/shared.h
+++ b/security/nss/fuzz/shared.h
@@ -2,39 +2,17 @@
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef shared_h__
#define shared_h__
-#include <assert.h>
-#include <random>
-#include "cert.h"
#include "nss.h"
-extern "C" size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize);
-extern "C" size_t LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size,
- size_t MaxSize, unsigned int Seed);
-
class NSSDatabase {
public:
- NSSDatabase() { assert(NSS_NoDB_Init(nullptr) == SECSuccess); }
- ~NSSDatabase() { assert(NSS_Shutdown() == SECSuccess); }
+ NSSDatabase() { NSS_NoDB_Init(nullptr); }
+ ~NSSDatabase() { NSS_Shutdown(); }
};
-typedef std::vector<decltype(LLVMFuzzerCustomMutator) *> Mutators;
-
-size_t CustomMutate(Mutators &mutators, uint8_t *Data, size_t Size,
- size_t MaxSize, unsigned int Seed) {
- std::mt19937 rng(Seed);
- static std::bernoulli_distribution bdist;
-
- if (bdist(rng)) {
- std::uniform_int_distribution<size_t> idist(0, mutators.size() - 1);
- return mutators.at(idist(rng))(Data, Size, MaxSize, Seed);
- }
-
- return LLVMFuzzerMutate(Data, Size, MaxSize);
-}
-
#endif // shared_h__
--- a/security/nss/fuzz/warning.txt
+++ b/security/nss/fuzz/warning.txt
@@ -1,16 +1,15 @@
-##################################################
-## ##
-## WARNING: You're building with -Dfuzz_tls=1 ##
-## ##
-## This means: ##
-## ##
-## * Your PRNG is DETERMINISTIC. ##
-## * TLS transcripts are PLAINTEXT. ##
-## * Session tickets are NOT encrypted. ##
-## * TLS signature/MAC checks are DISABLED. ##
-## ##
-## Thank you for fuzzing! ##
-## ##
-##################################################
+##############################################
+## ##
+## WARNING: You're building with -Dfuzz=1 ##
+## ##
+## This means: ##
+## ##
+## * Your PRNG is DETERMINISTIC. ##
+## * TLS transcripts are PLAINTEXT. ##
+## * TLS signature checks are DISABLED. ##
+## ##
+## Thank you for fuzzing! ##
+## ##
+##############################################
new file mode 100644
--- /dev/null
+++ b/security/nss/gtests/common/common.gyp
@@ -0,0 +1,35 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+{
+ 'includes': [
+ '../../coreconf/config.gypi',
+ 'gtest.gypi',
+ ],
+ 'targets': [
+ {
+ 'target_name': 'gtests',
+ 'type': 'executable',
+ 'sources': [
+ 'gtests.cc'
+ ],
+ 'dependencies': [
+ '<(DEPTH)/exports.gyp:nss_exports',
+ '<(DEPTH)/lib/nss/nss.gyp:nss3',
+ '<(DEPTH)/lib/util/util.gyp:nssutil3',
+ '<(DEPTH)/lib/smime/smime.gyp:smime3',
+ '<(DEPTH)/gtests/google_test/google_test.gyp:gtest',
+ '<(DEPTH)/cmd/lib/lib.gyp:sectool'
+ ]
+ }
+ ],
+ 'target_defaults': {
+ 'include_dirs': [
+ '../../gtests/google_test/gtest/include',
+ '../../gtests/common'
+ ],
+ },
+ 'variables': {
+ 'module': 'nss'
+ }
+}
--- a/security/nss/gtests/common/gtest.gypi
+++ b/security/nss/gtests/common/gtest.gypi
@@ -1,33 +1,28 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
{
+ 'includes': [
+ '../../coreconf/config.gypi'
+ ],
'target_defaults': {
- 'cflags': [
- '-Wsign-compare',
- ],
- 'xcode_settings': {
- 'OTHER_CFLAGS': [
- '-Wsign-compare',
- ],
- },
'conditions': [
['OS=="win"', {
'libraries': [
'-lws2_32',
],
}],
['OS=="android"', {
'libraries': [
'-lstdc++',
],
}],
- [ 'fuzz_tls==1', {
+ [ 'fuzz==1', {
'defines': [
'UNSAFE_FUZZER_MODE',
],
}],
],
'msvs_settings': {
'VCCLCompilerTool': {
'ExceptionHandling': 1,
--- a/security/nss/gtests/der_gtest/der_gtest.gyp
+++ b/security/nss/gtests/der_gtest/der_gtest.gyp
@@ -13,19 +13,16 @@
'sources': [
'der_getint_unittest.cc',
'der_private_key_import_unittest.cc',
'<(DEPTH)/gtests/common/gtests.cc'
],
'dependencies': [
'<(DEPTH)/exports.gyp:nss_exports',
'<(DEPTH)/gtests/google_test/google_test.gyp:gtest',
- '<(DEPTH)/lib/util/util.gyp:nssutil3',
- '<(DEPTH)/lib/ssl/ssl.gyp:ssl3',
- '<(DEPTH)/lib/nss/nss.gyp:nss3',
]
}
],
'target_defaults': {
'include_dirs': [
'../../gtests/google_test/gtest/include',
'../../gtests/common'
]
--- a/security/nss/gtests/freebl_gtest/freebl_gtest.gyp
+++ b/security/nss/gtests/freebl_gtest/freebl_gtest.gyp
@@ -11,34 +11,21 @@
'target_name': 'freebl_gtest',
'type': 'executable',
'sources': [
'mpi_unittest.cc',
'<(DEPTH)/gtests/common/gtests.cc'
],
'dependencies': [
'<(DEPTH)/exports.gyp:nss_exports',
- '<(DEPTH)/lib/util/util.gyp:nssutil3',
+ '<(DEPTH)/lib/freebl/freebl.gyp:<(freebl_name)',
'<(DEPTH)/gtests/google_test/google_test.gyp:gtest',
- '<(DEPTH)/lib/nss/nss.gyp:nss_static',
- '<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap_static',
- '<(DEPTH)/lib/cryptohi/cryptohi.gyp:cryptohi',
- '<(DEPTH)/lib/certhigh/certhigh.gyp:certhi',
- '<(DEPTH)/lib/certdb/certdb.gyp:certdb',
- '<(DEPTH)/lib/base/base.gyp:nssb',
- '<(DEPTH)/lib/dev/dev.gyp:nssdev',
- '<(DEPTH)/lib/pki/pki.gyp:nsspki',
- '<(DEPTH)/lib/ssl/ssl.gyp:ssl',
],
- 'conditions': [
- [ 'ct_verif==1', {
- 'defines': [
- 'CT_VERIF',
- ],
- }],
+ 'defines': [
+ 'CT_VERIF',
],
}
],
'target_defaults': {
'include_dirs': [
'<(DEPTH)/gtests/google_test/gtest/include',
'<(DEPTH)/gtests/common',
'<(DEPTH)/lib/freebl/mpi',
--- a/security/nss/gtests/freebl_gtest/mpi_unittest.cc
+++ b/security/nss/gtests/freebl_gtest/mpi_unittest.cc
@@ -78,20 +78,18 @@ TEST_F(MPITest, MpiCmpConstTest) {
"FF0FFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"),
16);
mp_read_radix(
&c,
const_cast<char *>(
"FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632550"),
16);
-#ifdef CT_VERIF
mp_taint(&b);
mp_taint(&c);
-#endif
uint32_t runs = 5000000;
uint32_t time_b = 0, time_c = 0;
for (uint32_t i = 0; i < runs; ++i) {
struct timespec start, end;
gettime(&start);
int r = mp_cmp(&a, &b);
gettime(&end);
--- a/security/nss/gtests/google_test/google_test.gyp
+++ b/security/nss/gtests/google_test/google_test.gyp
@@ -8,17 +8,49 @@
],
'targets': [
{
'target_name': 'gtest',
'type': 'static_library',
'sources': [
'gtest/src/gtest-all.cc'
],
+ 'dependencies': [
+ '<(DEPTH)/lib/nss/nss.gyp:nss3',
+ '<(DEPTH)/lib/util/util.gyp:nssutil3',
+ '<(DEPTH)/lib/smime/smime.gyp:smime3',
+ '<(DEPTH)/lib/ssl/ssl.gyp:ssl3',
+ '<(DEPTH)/cmd/lib/lib.gyp:sectool'
+ ]
},
+ {
+ 'target_name': 'gtest1',
+ 'type': 'shared_library',
+ 'dependencies': [
+ 'gtest'
+ ],
+ # Work around a gyp bug. Fixed upstream in gyp:
+ # https://chromium.googlesource.com/external/gyp/+/93cc6e2c23e4d5ebd179f388e67aa907d0dfd43d
+ 'conditions': [
+ ['OS!="win"', {
+ 'libraries': [
+ '-lstdc++',
+ ],
+ }],
+ ],
+ # For some reason when just linking static libraries into
+ # a DLL the link fails without this.
+ 'msvs_settings': {
+ 'VCLinkerTool': {
+ 'AdditionalDependencies': [
+ '/DEFAULTLIB:MSVCRT',
+ ],
+ },
+ },
+ }
],
'target_defaults': {
'include_dirs': [
'gtest/include/',
'gtest'
],
},
'variables': {
--- a/security/nss/gtests/nss_bogo_shim/nss_bogo_shim.cc
+++ b/security/nss/gtests/nss_bogo_shim/nss_bogo_shim.cc
@@ -7,26 +7,29 @@
#include <cstdlib>
#include <iostream>
#include <memory>
#include "nspr.h"
#include "nss.h"
#include "prio.h"
#include "prnetdb.h"
-#include "secerr.h"
#include "ssl.h"
-#include "ssl3prot.h"
#include "sslerr.h"
#include "sslproto.h"
#include "nsskeys.h"
-static const char* kVersionDisableFlags[] = {"no-ssl3", "no-tls1", "no-tls11",
- "no-tls12", "no-tls13"};
+static const char* kVersionDisableFlags[] = {
+ "no-ssl3",
+ "no-tls1",
+ "no-tls11",
+ "no-tls12",
+ "no-tls13"
+};
bool exitCodeUnimplemented = false;
std::string FormatError(PRErrorCode code) {
return std::string(":") + PORT_ErrorToName(code) + ":" + ":" +
PORT_ErrorToString(code);
}
@@ -111,17 +114,21 @@ class TestAgent {
return true;
}
bool SetupKeys() {
SECStatus rv;
if (cfg_.get<std::string>("key-file") != "") {
key_ = ReadPrivateKey(cfg_.get<std::string>("key-file"));
- if (!key_) return false;
+ if (!key_) {
+ // Temporary to handle our inability to handle ECDSA.
+ exitCodeUnimplemented = true;
+ return false;
+ }
}
if (cfg_.get<std::string>("cert-file") != "") {
cert_ = ReadCertificate(cfg_.get<std::string>("cert-file"));
if (!cert_) return false;
}
if (cfg_.get<bool>("server")) {
// Server
rv = SSL_ConfigServerCert(ssl_fd_, cert_, key_, nullptr, 0);
@@ -140,96 +147,64 @@ class TestAgent {
rv = SSL_GetClientAuthDataHook(ssl_fd_, GetClientAuthDataHook, this);
if (rv != SECSuccess) return false;
}
}
return true;
}
- static bool ConvertFromWireVersion(SSLProtocolVariant variant,
- int wire_version, uint16_t* lib_version) {
- // These default values are used when {min,max}-version isn't given.
- if (wire_version == 0 || wire_version == 0xffff) {
- *lib_version = static_cast<uint16_t>(wire_version);
- return true;
- }
-
-#ifdef TLS_1_3_DRAFT_VERSION
- if (wire_version == (0x7f00 | TLS_1_3_DRAFT_VERSION)) {
- // N.B. SSL_LIBRARY_VERSION_DTLS_1_3_WIRE == SSL_LIBRARY_VERSION_TLS_1_3
- wire_version = SSL_LIBRARY_VERSION_TLS_1_3;
- }
-#endif
-
- if (variant == ssl_variant_datagram) {
- switch (wire_version) {
- case SSL_LIBRARY_VERSION_DTLS_1_0_WIRE:
- *lib_version = SSL_LIBRARY_VERSION_DTLS_1_0;
- break;
- case SSL_LIBRARY_VERSION_DTLS_1_2_WIRE:
- *lib_version = SSL_LIBRARY_VERSION_DTLS_1_2;
- break;
- case SSL_LIBRARY_VERSION_DTLS_1_3_WIRE:
- *lib_version = SSL_LIBRARY_VERSION_DTLS_1_3;
- break;
- default:
- std::cerr << "Unrecognized DTLS version " << wire_version << ".\n";
- return false;
- }
- } else {
- if (wire_version < SSL_LIBRARY_VERSION_3_0 ||
- wire_version > SSL_LIBRARY_VERSION_TLS_1_3) {
- std::cerr << "Unrecognized TLS version " << wire_version << ".\n";
- return false;
- }
- *lib_version = static_cast<uint16_t>(wire_version);
- }
- return true;
- }
-
bool GetVersionRange(SSLVersionRange* range_out, SSLProtocolVariant variant) {
SSLVersionRange supported;
if (SSL_VersionRangeGetSupported(variant, &supported) != SECSuccess) {
return false;
}
- uint16_t min_allowed;
- uint16_t max_allowed;
- if (!ConvertFromWireVersion(variant, cfg_.get<int>("min-version"),
- &min_allowed)) {
- return false;
- }
- if (!ConvertFromWireVersion(variant, cfg_.get<int>("max-version"),
- &max_allowed)) {
- return false;
+ auto max_allowed = static_cast<uint16_t>(cfg_.get<int>("max-version"));
+ if (variant == ssl_variant_datagram) {
+ // For DTLS this is the wire version; adjust if needed.
+ switch (max_allowed) {
+ case SSL_LIBRARY_VERSION_DTLS_1_0_WIRE:
+ max_allowed = SSL_LIBRARY_VERSION_DTLS_1_0;
+ break;
+ case SSL_LIBRARY_VERSION_DTLS_1_2_WIRE:
+ max_allowed = SSL_LIBRARY_VERSION_DTLS_1_2;
+ break;
+ case SSL_LIBRARY_VERSION_DTLS_1_3_WIRE:
+ max_allowed = SSL_LIBRARY_VERSION_DTLS_1_3;
+ break;
+ case 0xffff: // No maximum specified.
+ break;
+ default:
+ // Unrecognized DTLS version.
+ return false;
+ }
}
- min_allowed = std::max(min_allowed, supported.min);
max_allowed = std::min(max_allowed, supported.max);
bool found_min = false;
bool found_max = false;
// Ignore -no-ssl3, because SSLv3 is never supported.
for (size_t i = 1; i < PR_ARRAY_SIZE(kVersionDisableFlags); ++i) {
auto version =
- static_cast<uint16_t>(SSL_LIBRARY_VERSION_TLS_1_0 + (i - 1));
+ static_cast<uint16_t>(SSL_LIBRARY_VERSION_TLS_1_0 + (i - 1));
if (variant == ssl_variant_datagram) {
// In DTLS mode, the -no-tlsN flags refer to DTLS versions,
// but NSS wants the corresponding TLS versions.
if (version == SSL_LIBRARY_VERSION_TLS_1_1) {
// DTLS 1.1 doesn't exist.
continue;
}
if (version == SSL_LIBRARY_VERSION_TLS_1_0) {
version = SSL_LIBRARY_VERSION_DTLS_1_0;
}
}
- if (version < min_allowed) {
+ if (version < supported.min) {
continue;
}
if (version > max_allowed) {
break;
}
const bool allowed = !cfg_.get<bool>(kVersionDisableFlags[i]);
@@ -240,24 +215,22 @@ class TestAgent {
if (found_min && !found_max) {
if (allowed) {
range_out->max = version;
} else {
found_max = true;
}
}
if (found_max && allowed) {
- std::cerr << "Discontiguous version range.\n";
+ // Discontiguous range.
return false;
}
}
- if (!found_min) {
- std::cerr << "All versions disabled.\n";
- }
+ // Iff found_min is still false, no usable version was found.
return found_min;
}
bool SetupOptions() {
SECStatus rv = SSL_OptionSet(ssl_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
if (rv != SECSuccess) return false;
SSLVersionRange vrange;
@@ -334,88 +307,37 @@ class TestAgent {
int32_t len = rv;
for (int32_t i = 0; i < len; ++i) {
block[i] ^= 0xff;
}
rv = PR_Write(ssl_fd_, block, len);
if (rv != len) {
std::cerr << "Write failure\n";
- PORT_SetError(SEC_ERROR_OUTPUT_LEN);
return SECFailure;
}
}
return SECSuccess;
}
- // Write bytes to the other side then read them back and check
- // that they were correctly XORed as in ReadWrite.
- SECStatus WriteRead() {
- static const uint8_t ch = 'E';
-
- // We do 600-byte blocks to provide mis-alignment of the
- // reader and writer.
- uint8_t block[600];
- memset(block, ch, sizeof(block));
- int32_t rv = PR_Write(ssl_fd_, block, sizeof(block));
- if (rv != sizeof(block)) {
- std::cerr << "Write failure\n";
- PORT_SetError(SEC_ERROR_OUTPUT_LEN);
- return SECFailure;
- }
-
- size_t left = sizeof(block);
- while (left) {
- int32_t rv = PR_Read(ssl_fd_, block, left);
- if (rv < 0) {
- std::cerr << "Failure reading\n";
- return SECFailure;
- }
- if (rv == 0) {
- PORT_SetError(SEC_ERROR_INPUT_LEN);
- return SECFailure;
- }
-
- int32_t len = rv;
- for (int32_t i = 0; i < len; ++i) {
- if (block[i] != (ch ^ 0xff)) {
- PORT_SetError(SEC_ERROR_BAD_DATA);
- return SECFailure;
- }
- }
- left -= len;
- }
- return SECSuccess;
- }
-
SECStatus DoExchange() {
SECStatus rv = Handshake();
if (rv != SECSuccess) {
PRErrorCode err = PR_GetError();
std::cerr << "Handshake failed with error=" << err << FormatError(err)
<< std::endl;
return SECFailure;
}
- if (cfg_.get<bool>("write-then-read")) {
- rv = WriteRead();
- if (rv != SECSuccess) {
- PRErrorCode err = PR_GetError();
- std::cerr << "WriteRead failed with error=" << FormatError(err)
- << std::endl;
- return SECFailure;
- }
- } else {
- rv = ReadWrite();
- if (rv != SECSuccess) {
- PRErrorCode err = PR_GetError();
- std::cerr << "ReadWrite failed with error=" << FormatError(err)
- << std::endl;
- return SECFailure;
- }
+ rv = ReadWrite();
+ if (rv != SECSuccess) {
+ PRErrorCode err = PR_GetError();
+ std::cerr << "ReadWrite failed with error=" << FormatError(err)
+ << std::endl;
+ return SECFailure;
}
return SECSuccess;
}
private:
const Config& cfg_;
PRFileDesc* pr_fd_;
@@ -427,37 +349,36 @@ class TestAgent {
std::unique_ptr<const Config> ReadConfig(int argc, char** argv) {
std::unique_ptr<Config> cfg(new Config());
cfg->AddEntry<int>("port", 0);
cfg->AddEntry<bool>("server", false);
cfg->AddEntry<int>("resume-count", 0);
cfg->AddEntry<std::string>("key-file", "");
cfg->AddEntry<std::string>("cert-file", "");
- cfg->AddEntry<int>("min-version", 0);
cfg->AddEntry<int>("max-version", 0xffff);
for (auto flag : kVersionDisableFlags) {
cfg->AddEntry<bool>(flag, false);
}
- cfg->AddEntry<bool>("write-then-read", false);
auto rv = cfg->ParseArgs(argc, argv);
switch (rv) {
case Config::kOK:
break;
case Config::kUnknownFlag:
exitCodeUnimplemented = true;
default:
return nullptr;
}
// Needed to change to std::unique_ptr<const Config>
return std::move(cfg);
}
+
bool RunCycle(std::unique_ptr<const Config>& cfg) {
std::unique_ptr<TestAgent> agent(TestAgent::Create(*cfg));
return agent && agent->DoExchange() == SECSuccess;
}
int GetExitCode(bool success) {
if (exitCodeUnimplemented) {
return 89;
--- a/security/nss/gtests/nss_bogo_shim/nss_bogo_shim.gyp
+++ b/security/nss/gtests/nss_bogo_shim/nss_bogo_shim.gyp
@@ -30,16 +30,19 @@
'<(DEPTH)/lib/cryptohi/cryptohi.gyp:cryptohi',
'<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap',
'<(DEPTH)/lib/softoken/softoken.gyp:softokn',
'<(DEPTH)/lib/certdb/certdb.gyp:certdb',
'<(DEPTH)/lib/pki/pki.gyp:nsspki',
'<(DEPTH)/lib/dev/dev.gyp:nssdev',
'<(DEPTH)/lib/base/base.gyp:nssb',
'<(DEPTH)/lib/freebl/freebl.gyp:freebl',
+ '<(DEPTH)/lib/nss/nss.gyp:nss_static',
+ '<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap',
+ '<(DEPTH)/lib/certhigh/certhigh.gyp:certhi',
'<(DEPTH)/lib/zlib/zlib.gyp:nss_zlib'
],
'conditions': [
[ 'disable_dbm==0', {
'dependencies': [
'<(DEPTH)/lib/dbm/src/src.gyp:dbm',
],
}],
--- a/security/nss/gtests/nss_bogo_shim/nsskeys.cc
+++ b/security/nss/gtests/nss_bogo_shim/nsskeys.cc
@@ -58,16 +58,17 @@ SECKEYPrivateKey* ReadPrivateKey(const s
PK11SlotInfo* slot = PK11_GetInternalSlot();
SECStatus rv = PK11_ImportDERPrivateKeyInfoAndReturnKey(
slot, &item, nullptr, nullptr, PR_FALSE, PR_FALSE,
KU_KEY_ENCIPHERMENT | KU_DATA_ENCIPHERMENT | KU_DIGITAL_SIGNATURE,
&privkey, nullptr);
PK11_FreeSlot(slot);
SECITEM_FreeItem(&item, PR_FALSE);
if (rv != SECSuccess) {
+ // This is probably due to this being an ECDSA key (Bug 1295121).
std::cerr << "Couldn't import key " << PORT_ErrorToString(PORT_GetError())
<< "\n";
return nullptr;
}
return privkey;
}
--- a/security/nss/gtests/pk11_gtest/manifest.mn
+++ b/security/nss/gtests/pk11_gtest/manifest.mn
@@ -4,17 +4,16 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
CORE_DEPTH = ../..
DEPTH = ../..
MODULE = nss
CPPSRCS = \
pk11_aeskeywrap_unittest.cc \
pk11_chacha20poly1305_unittest.cc \
- pk11_ecdsa_unittest.cc \
pk11_export_unittest.cc \
pk11_pbkdf2_unittest.cc \
pk11_prf_unittest.cc \
pk11_prng_unittest.cc \
pk11_rsapss_unittest.cc \
$(NULL)
INCLUDES += -I$(CORE_DEPTH)/gtests/google_test/gtest/include \
deleted file mode 100644
--- a/security/nss/gtests/pk11_gtest/pk11_ecdsa_unittest.cc
+++ /dev/null
@@ -1,156 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <memory>
-#include "nss.h"
-#include "pk11pub.h"
-#include "sechash.h"
-
-#include "gtest/gtest.h"
-#include "scoped_ptrs.h"
-
-#include "pk11_ecdsa_vectors.h"
-#include "pk11_signature_test.h"
-
-namespace nss_test {
-
-class Pkcs11EcdsaTest : public Pk11SignatureTest {
- protected:
- CK_MECHANISM_TYPE mechanism() { return CKM_ECDSA; }
- SECItem* parameters() { return nullptr; }
-};
-
-class Pkcs11EcdsaSha256Test : public Pkcs11EcdsaTest {
- protected:
- SECOidTag hashOID() { return SEC_OID_SHA256; }
-};
-
-class Pkcs11EcdsaSha384Test : public Pkcs11EcdsaTest {
- protected:
- SECOidTag hashOID() { return SEC_OID_SHA384; }
-};
-
-class Pkcs11EcdsaSha512Test : public Pkcs11EcdsaTest {
- protected:
- SECOidTag hashOID() { return SEC_OID_SHA512; }
-};
-
-TEST_F(Pkcs11EcdsaSha256Test, VerifyP256) {
- SIG_TEST_VECTOR_VERIFY(kP256Spki, kP256Data, kP256Signature)
-}
-TEST_F(Pkcs11EcdsaSha256Test, SignAndVerifyP256) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kP256Pkcs8, kP256Spki, kP256Data)
-}
-
-TEST_F(Pkcs11EcdsaSha384Test, VerifyP384) {
- SIG_TEST_VECTOR_VERIFY(kP384Spki, kP384Data, kP384Signature)
-}
-TEST_F(Pkcs11EcdsaSha384Test, SignAndVerifyP384) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kP384Pkcs8, kP384Spki, kP384Data)
-}
-
-TEST_F(Pkcs11EcdsaSha512Test, VerifyP521) {
- SIG_TEST_VECTOR_VERIFY(kP521Spki, kP521Data, kP521Signature)
-}
-TEST_F(Pkcs11EcdsaSha512Test, SignAndVerifyP521) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kP521Pkcs8, kP521Spki, kP521Data)
-}
-
-// Importing a private key in PKCS#8 format must fail when the outer AlgID
-// struct contains neither id-ecPublicKey nor a namedCurve parameter.
-TEST_F(Pkcs11EcdsaSha256Test, ImportNoCurveOIDOrAlgorithmParams) {
- EXPECT_FALSE(ImportPrivateKey(kP256Pkcs8NoCurveOIDOrAlgorithmParams,
- sizeof(kP256Pkcs8NoCurveOIDOrAlgorithmParams)));
-};
-
-// Importing a private key in PKCS#8 format must succeed when only the outer
-// AlgID struct contains the namedCurve parameters.
-TEST_F(Pkcs11EcdsaSha256Test, ImportOnlyAlgorithmParams) {
- EXPECT_TRUE(ImportPrivateKeyAndSignHashedData(
- kP256Pkcs8OnlyAlgorithmParams, sizeof(kP256Pkcs8OnlyAlgorithmParams),
- kP256Data, sizeof(kP256Data)));
-};
-
-// Importing a private key in PKCS#8 format must succeed when the outer AlgID
-// struct and the inner ECPrivateKey contain the same namedCurve parameters.
-// The inner curveOID is always ignored, so only the outer one will be used.
-TEST_F(Pkcs11EcdsaSha256Test, ImportMatchingCurveOIDAndAlgorithmParams) {
- EXPECT_TRUE(ImportPrivateKeyAndSignHashedData(
- kP256Pkcs8MatchingCurveOIDAndAlgorithmParams,
- sizeof(kP256Pkcs8MatchingCurveOIDAndAlgorithmParams), kP256Data,
- sizeof(kP256Data)));
-};
-
-// Importing a private key in PKCS#8 format must succeed when the outer AlgID
-// struct and the inner ECPrivateKey contain dissimilar namedCurve parameters.
-// The inner curveOID is always ignored, so only the outer one will be used.
-TEST_F(Pkcs11EcdsaSha256Test, ImportDissimilarCurveOIDAndAlgorithmParams) {
- EXPECT_TRUE(ImportPrivateKeyAndSignHashedData(
- kP256Pkcs8DissimilarCurveOIDAndAlgorithmParams,
- sizeof(kP256Pkcs8DissimilarCurveOIDAndAlgorithmParams), kP256Data,
- sizeof(kP256Data)));
-};
-
-// Importing a private key in PKCS#8 format must fail when the outer ASN.1
-// AlgorithmID struct contains only id-ecPublicKey but no namedCurve parameter.
-TEST_F(Pkcs11EcdsaSha256Test, ImportNoAlgorithmParams) {
- EXPECT_FALSE(ImportPrivateKey(kP256Pkcs8NoAlgorithmParams,
- sizeof(kP256Pkcs8NoAlgorithmParams)));
-};
-
-// Importing a private key in PKCS#8 format must fail when id-ecPublicKey is
-// given (so we know it's an EC key) but the namedCurve parameter is unknown.
-TEST_F(Pkcs11EcdsaSha256Test, ImportInvalidAlgorithmParams) {
- EXPECT_FALSE(ImportPrivateKey(kP256Pkcs8InvalidAlgorithmParams,
- sizeof(kP256Pkcs8InvalidAlgorithmParams)));
-};
-
-// Importing a private key in PKCS#8 format with a point not on the curve will
-// succeed. Using the contained public key however will fail when trying to
-// import it before using it for any operation.
-TEST_F(Pkcs11EcdsaSha256Test, ImportPointNotOnCurve) {
- ScopedSECKEYPrivateKey privKey(ImportPrivateKey(
- kP256Pkcs8PointNotOnCurve, sizeof(kP256Pkcs8PointNotOnCurve)));
- ASSERT_TRUE(privKey);
-
- ScopedSECKEYPublicKey pubKey(SECKEY_ConvertToPublicKey(privKey.get()));
- ASSERT_TRUE(pubKey);
-
- ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
- ASSERT_TRUE(slot);
-
- auto handle = PK11_ImportPublicKey(slot.get(), pubKey.get(), false);
- EXPECT_EQ(handle, static_cast<decltype(handle)>(CK_INVALID_HANDLE));
-};
-
-// Importing a private key in PKCS#8 format must fail when no point is given.
-// PK11 currently offers no APIs to derive raw public keys from private values.
-TEST_F(Pkcs11EcdsaSha256Test, ImportNoPublicKey) {
- EXPECT_FALSE(
- ImportPrivateKey(kP256Pkcs8NoPublicKey, sizeof(kP256Pkcs8NoPublicKey)));
-};
-
-// Importing a public key in SPKI format must fail when id-ecPublicKey is
-// given (so we know it's an EC key) but the namedCurve parameter is missing.
-TEST_F(Pkcs11EcdsaSha256Test, ImportSpkiNoAlgorithmParams) {
- EXPECT_FALSE(ImportPublicKey(kP256SpkiNoAlgorithmParams,
- sizeof(kP256SpkiNoAlgorithmParams)));
-}
-
-// Importing a public key in SPKI format with a point not on the curve will
-// succeed. Using the public key however will fail when trying to import
-// it before using it for any operation.
-TEST_F(Pkcs11EcdsaSha256Test, ImportSpkiPointNotOnCurve) {
- ScopedSECKEYPublicKey pubKey(ImportPublicKey(
- kP256SpkiPointNotOnCurve, sizeof(kP256SpkiPointNotOnCurve)));
- ASSERT_TRUE(pubKey);
-
- ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
- ASSERT_TRUE(slot);
-
- auto handle = PK11_ImportPublicKey(slot.get(), pubKey.get(), false);
- EXPECT_EQ(handle, static_cast<decltype(handle)>(CK_INVALID_HANDLE));
-}
-
-} // namespace nss_test
deleted file mode 100644
--- a/security/nss/gtests/pk11_gtest/pk11_ecdsa_vectors.h
+++ /dev/null
@@ -1,251 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-namespace nss_test {
-
-// ECDSA test vector, A.2.5. ECDSA, 256 Bits (Prime Field), SHA-256
-// <https://tools.ietf.org/html/rfc6979#appendix-A.2.5>
-const uint8_t kP256Pkcs8[] = {
- 0x30, 0x81, 0x87, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
- 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
- 0x03, 0x01, 0x07, 0x04, 0x6d, 0x30, 0x6b, 0x02, 0x01, 0x01, 0x04, 0x20,
- 0xc9, 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21, 0x57,
- 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12,
- 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, 0xa1, 0x44, 0x03, 0x42,
- 0x00, 0x04, 0x60, 0xfe, 0xd4, 0xba, 0x25, 0x5a, 0x9d, 0x31, 0xc9, 0x61,
- 0xeb, 0x74, 0xc6, 0x35, 0x6d, 0x68, 0xc0, 0x49, 0xb8, 0x92, 0x3b, 0x61,
- 0xfa, 0x6c, 0xe6, 0x69, 0x62, 0x2e, 0x60, 0xf2, 0x9f, 0xb6, 0x79, 0x03,
- 0xfe, 0x10, 0x08, 0xb8, 0xbc, 0x99, 0xa4, 0x1a, 0xe9, 0xe9, 0x56, 0x28,
- 0xbc, 0x64, 0xf2, 0xf1, 0xb2, 0x0c, 0x2d, 0x7e, 0x9f, 0x51, 0x77, 0xa3,
- 0xc2, 0x94, 0xd4, 0x46, 0x22, 0x99};
-const uint8_t kP256Spki[] = {
- 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
- 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
- 0x42, 0x00, 0x04, 0x60, 0xfe, 0xd4, 0xba, 0x25, 0x5a, 0x9d, 0x31, 0xc9,
- 0x61, 0xeb, 0x74, 0xc6, 0x35, 0x6d, 0x68, 0xc0, 0x49, 0xb8, 0x92, 0x3b,
- 0x61, 0xfa, 0x6c, 0xe6, 0x69, 0x62, 0x2e, 0x60, 0xf2, 0x9f, 0xb6, 0x79,
- 0x03, 0xfe, 0x10, 0x08, 0xb8, 0xbc, 0x99, 0xa4, 0x1a, 0xe9, 0xe9, 0x56,
- 0x28, 0xbc, 0x64, 0xf2, 0xf1, 0xb2, 0x0c, 0x2d, 0x7e, 0x9f, 0x51, 0x77,
- 0xa3, 0xc2, 0x94, 0xd4, 0x46, 0x22, 0x99};
-const uint8_t kP256Data[] = {'s', 'a', 'm', 'p', 'l', 'e'};
-const uint8_t kP256Signature[] = {
- 0xef, 0xd4, 0x8b, 0x2a, 0xac, 0xb6, 0xa8, 0xfd, 0x11, 0x40, 0xdd,
- 0x9c, 0xd4, 0x5e, 0x81, 0xd6, 0x9d, 0x2c, 0x87, 0x7b, 0x56, 0xaa,
- 0xf9, 0x91, 0xc3, 0x4d, 0x0e, 0xa8, 0x4e, 0xaf, 0x37, 0x16, 0xf7,
- 0xcb, 0x1c, 0x94, 0x2d, 0x65, 0x7c, 0x41, 0xd4, 0x36, 0xc7, 0xa1,
- 0xb6, 0xe2, 0x9f, 0x65, 0xf3, 0xe9, 0x00, 0xdb, 0xb9, 0xaf, 0xf4,
- 0x06, 0x4d, 0xc4, 0xab, 0x2f, 0x84, 0x3a, 0xcd, 0xa8};
-
-// ECDSA test vector, A.2.6. ECDSA, 384 Bits (Prime Field), SHA-384
-// <https://tools.ietf.org/html/rfc6979#appendix-A.2.6>
-const uint8_t kP384Pkcs8[] = {
- 0x30, 0x81, 0xb6, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86,
- 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22,
- 0x04, 0x81, 0x9e, 0x30, 0x81, 0x9b, 0x02, 0x01, 0x01, 0x04, 0x30, 0x6b,
- 0x9d, 0x3d, 0xad, 0x2e, 0x1b, 0x8c, 0x1c, 0x05, 0xb1, 0x98, 0x75, 0xb6,
- 0x65, 0x9f, 0x4d, 0xe2, 0x3c, 0x3b, 0x66, 0x7b, 0xf2, 0x97, 0xba, 0x9a,
- 0xa4, 0x77, 0x40, 0x78, 0x71, 0x37, 0xd8, 0x96, 0xd5, 0x72, 0x4e, 0x4c,
- 0x70, 0xa8, 0x25, 0xf8, 0x72, 0xc9, 0xea, 0x60, 0xd2, 0xed, 0xf5, 0xa1,
- 0x64, 0x03, 0x62, 0x00, 0x04, 0xec, 0x3a, 0x4e, 0x41, 0x5b, 0x4e, 0x19,
- 0xa4, 0x56, 0x86, 0x18, 0x02, 0x9f, 0x42, 0x7f, 0xa5, 0xda, 0x9a, 0x8b,
- 0xc4, 0xae, 0x92, 0xe0, 0x2e, 0x06, 0xaa, 0xe5, 0x28, 0x6b, 0x30, 0x0c,
- 0x64, 0xde, 0xf8, 0xf0, 0xea, 0x90, 0x55, 0x86, 0x60, 0x64, 0xa2, 0x54,
- 0x51, 0x54, 0x80, 0xbc, 0x13, 0x80, 0x15, 0xd9, 0xb7, 0x2d, 0x7d, 0x57,
- 0x24, 0x4e, 0xa8, 0xef, 0x9a, 0xc0, 0xc6, 0x21, 0x89, 0x67, 0x08, 0xa5,
- 0x93, 0x67, 0xf9, 0xdf, 0xb9, 0xf5, 0x4c, 0xa8, 0x4b, 0x3f, 0x1c, 0x9d,
- 0xb1, 0x28, 0x8b, 0x23, 0x1c, 0x3a, 0xe0, 0xd4, 0xfe, 0x73, 0x44, 0xfd,
- 0x25, 0x33, 0x26, 0x47, 0x20};
-const uint8_t kP384Spki[] = {
- 0x30, 0x76, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
- 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22, 0x03, 0x62, 0x00, 0x04,
- 0xec, 0x3a, 0x4e, 0x41, 0x5b, 0x4e, 0x19, 0xa4, 0x56, 0x86, 0x18, 0x02,
- 0x9f, 0x42, 0x7f, 0xa5, 0xda, 0x9a, 0x8b, 0xc4, 0xae, 0x92, 0xe0, 0x2e,
- 0x06, 0xaa, 0xe5, 0x28, 0x6b, 0x30, 0x0c, 0x64, 0xde, 0xf8, 0xf0, 0xea,
- 0x90, 0x55, 0x86, 0x60, 0x64, 0xa2, 0x54, 0x51, 0x54, 0x80, 0xbc, 0x13,
- 0x80, 0x15, 0xd9, 0xb7, 0x2d, 0x7d, 0x57, 0x24, 0x4e, 0xa8, 0xef, 0x9a,
- 0xc0, 0xc6, 0x21, 0x89, 0x67, 0x08, 0xa5, 0x93, 0x67, 0xf9, 0xdf, 0xb9,
- 0xf5, 0x4c, 0xa8, 0x4b, 0x3f, 0x1c, 0x9d, 0xb1, 0x28, 0x8b, 0x23, 0x1c,
- 0x3a, 0xe0, 0xd4, 0xfe, 0x73, 0x44, 0xfd, 0x25, 0x33, 0x26, 0x47, 0x20};
-const uint8_t kP384Data[] = {'s', 'a', 'm', 'p', 'l', 'e'};
-const uint8_t kP384Signature[] = {
- 0x94, 0xed, 0xbb, 0x92, 0xa5, 0xec, 0xb8, 0xaa, 0xd4, 0x73, 0x6e, 0x56,
- 0xc6, 0x91, 0x91, 0x6b, 0x3f, 0x88, 0x14, 0x06, 0x66, 0xce, 0x9f, 0xa7,
- 0x3d, 0x64, 0xc4, 0xea, 0x95, 0xad, 0x13, 0x3c, 0x81, 0xa6, 0x48, 0x15,
- 0x2e, 0x44, 0xac, 0xf9, 0x6e, 0x36, 0xdd, 0x1e, 0x80, 0xfa, 0xbe, 0x46,
- 0x99, 0xef, 0x4a, 0xeb, 0x15, 0xf1, 0x78, 0xce, 0xa1, 0xfe, 0x40, 0xdb,
- 0x26, 0x03, 0x13, 0x8f, 0x13, 0x0e, 0x74, 0x0a, 0x19, 0x62, 0x45, 0x26,
- 0x20, 0x3b, 0x63, 0x51, 0xd0, 0xa3, 0xa9, 0x4f, 0xa3, 0x29, 0xc1, 0x45,
- 0x78, 0x6e, 0x67, 0x9e, 0x7b, 0x82, 0xc7, 0x1a, 0x38, 0x62, 0x8a, 0xc8};
-
-// ECDSA test vector, A.2.7. ECDSA, 521 Bits (Prime Field), SHA-512
-// <https://tools.ietf.org/html/rfc6979#appendix-A.2.7>
-const uint8_t kP521Pkcs8[] = {
- 0x30, 0x81, 0xed, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86,
- 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23,
- 0x04, 0x81, 0xd5,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0xa0, 0xdb, 0x25, 0x74, 0x1b, 0x5b, 0x34, 0xa8, 0x28,
- 0x00, 0x8b, 0x22, 0xac, 0xc2, 0x3f, 0x92, 0x4f, 0xaa, 0xfb, 0xd4, 0xd3,
- 0x3f, 0x81, 0xea, 0x66, 0x95, 0x6d, 0xfe, 0xaa, 0x2b, 0xfd, 0xfc, 0xf5};
-const uint8_t kP521Spki[] = {
- 0x30, 0x81, 0x9b, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d,
- 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23, 0x03, 0x81, 0x86,
- 0x00, 0x04, 0x01, 0x89, 0x45, 0x50, 0xd0, 0x78, 0x59, 0x32, 0xe0, 0x0e,
- 0xaa, 0x23, 0xb6, 0x94, 0xf2, 0x13, 0xf8, 0xc3, 0x12, 0x1f, 0x86, 0xdc,
- 0x97, 0xa0, 0x4e, 0x5a, 0x71, 0x67, 0xdb, 0x4e, 0x5b, 0xcd, 0x37, 0x11,
- 0x23, 0xd4, 0x6e, 0x45, 0xdb, 0x6b, 0x5d, 0x53, 0x70, 0xa7, 0xf2, 0x0f,
- 0xb6, 0x33, 0x15, 0x5d, 0x38, 0xff, 0xa1, 0x6d, 0x2b, 0xd7, 0x61, 0xdc,
- 0xac, 0x47, 0x4b, 0x9a, 0x2f, 0x50, 0x23, 0xa4, 0x00, 0x49, 0x31, 0x01,
- 0xc9, 0x62, 0xcd, 0x4d, 0x2f, 0xdd, 0xf7, 0x82, 0x28, 0x5e, 0x64, 0x58,
- 0x41, 0x39, 0xc2, 0xf9, 0x1b, 0x47, 0xf8, 0x7f, 0xf8, 0x23, 0x54, 0xd6,
- 0x63, 0x0f, 0x74, 0x6a, 0x28, 0xa0, 0xdb, 0x25, 0x74, 0x1b, 0x5b, 0x34,
- 0xa8, 0x28, 0x00, 0x8b, 0x22, 0xac, 0xc2, 0x3f, 0x92, 0x4f, 0xaa, 0xfb,
- 0xd4, 0xd3, 0x3f, 0x81, 0xea, 0x66, 0x95, 0x6d, 0xfe, 0xaa, 0x2b, 0xfd,
- 0xfc, 0xf5};
-const uint8_t kP521Data[] = {'s', 'a', 'm', 'p', 'l', 'e'};
-const uint8_t kP521Signature[] = {
- 0x00, 0xc3, 0x28, 0xfa, 0xfc, 0xbd, 0x79, 0xdd, 0x77, 0x85, 0x03, 0x70,
- 0xc4, 0x63, 0x25, 0xd9, 0x87, 0xcb, 0x52, 0x55, 0x69, 0xfb, 0x63, 0xc5,
- 0xd3, 0xbc, 0x53, 0x95, 0x0e, 0x6d, 0x4c, 0x5f, 0x17, 0x4e, 0x25, 0xa1,
- 0xee, 0x90, 0x17, 0xb5, 0xd4, 0x50, 0x60, 0x6a, 0xdd, 0x15, 0x2b, 0x53,
- 0x49, 0x31, 0xd7, 0xd4, 0xe8, 0x45, 0x5c, 0xc9, 0x1f, 0x9b, 0x15, 0xbf,
- 0x05, 0xec, 0x36, 0xe3, 0x77, 0xfa, 0x00, 0x61, 0x7c, 0xce, 0x7c, 0xf5,
- 0x06, 0x48, 0x06, 0xc4, 0x67, 0xf6, 0x78, 0xd3, 0xb4, 0x08, 0x0d, 0x6f,
- 0x1c, 0xc5, 0x0a, 0xf2, 0x6c, 0xa2, 0x09, 0x41, 0x73, 0x08, 0x28, 0x1b,
- 0x68, 0xaf, 0x28, 0x26, 0x23, 0xea, 0xa6, 0x3e, 0x5b, 0x5c, 0x07, 0x23,
- 0xd8, 0xb8, 0xc3, 0x7f, 0xf0, 0x77, 0x7b, 0x1a, 0x20, 0xf8, 0xcc, 0xb1,
- 0xdc, 0xcc, 0x43, 0x99, 0x7f, 0x1e, 0xe0, 0xe4, 0x4d, 0xa4, 0xa6, 0x7a};
-
-// ECDSA test vectors, SPKI and PKCS#8 edge cases.
-const uint8_t kP256Pkcs8NoCurveOIDOrAlgorithmParams[] = {
- 0x30, 0x7d, 0x02, 0x01, 0x00, 0x30, 0x09, 0x06, 0x07, 0x2a, 0x86, 0x48,
- 0xce, 0x3d, 0x02, 0x01, 0x04, 0x6d, 0x30, 0x6b, 0x02, 0x01, 0x01, 0x04,
- 0x20, 0xc9, 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21,
- 0x57, 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b,
- 0x12, 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, 0xa1, 0x44, 0x03,
- 0x42, 0x00, 0x04, 0x60, 0xfe, 0xd4, 0xba, 0x25, 0x5a, 0x9d, 0x31, 0xc9,
- 0x61, 0xeb, 0x74, 0xc6, 0x35, 0x6d, 0x68, 0xc0, 0x49, 0xb8, 0x92, 0x3b,
- 0x61, 0xfa, 0x6c, 0xe6, 0x69, 0x62, 0x2e, 0x60, 0xf2, 0x9f, 0xb6, 0x79,
- 0x03, 0xfe, 0x10, 0x08, 0xb8, 0xbc, 0x99, 0xa4, 0x1a, 0xe9, 0xe9, 0x56,
- 0x28, 0xbc, 0x64, 0xf2, 0xf1, 0xb2, 0x0c, 0x2d, 0x7e, 0x9f, 0x51, 0x77,
- 0xa3, 0xc2, 0x94, 0xd4, 0x46, 0x22, 0x99};
-const uint8_t kP256Pkcs8OnlyAlgorithmParams[] = {
- 0x30, 0x81, 0x87, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
- 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
- 0x03, 0x01, 0x07, 0x04, 0x6d, 0x30, 0x6b, 0x02, 0x01, 0x01, 0x04, 0x20,
- 0xc9, 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21, 0x57,
- 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12,
- 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, 0xa1, 0x44, 0x03, 0x42,
- 0x00, 0x04, 0x60, 0xfe, 0xd4, 0xba, 0x25, 0x5a, 0x9d, 0x31, 0xc9, 0x61,
- 0xeb, 0x74, 0xc6, 0x35, 0x6d, 0x68, 0xc0, 0x49, 0xb8, 0x92, 0x3b, 0x61,
- 0xfa, 0x6c, 0xe6, 0x69, 0x62, 0x2e, 0x60, 0xf2, 0x9f, 0xb6, 0x79, 0x03,
- 0xfe, 0x10, 0x08, 0xb8, 0xbc, 0x99, 0xa4, 0x1a, 0xe9, 0xe9, 0x56, 0x28,
- 0xbc, 0x64, 0xf2, 0xf1, 0xb2, 0x0c, 0x2d, 0x7e, 0x9f, 0x51, 0x77, 0xa3,
- 0xc2, 0x94, 0xd4, 0x46, 0x22, 0x99};
-const uint8_t kP256Pkcs8NoAlgorithmParams[] = {
- 0x30, 0x81, 0x89, 0x02, 0x01, 0x00, 0x30, 0x09, 0x06, 0x07, 0x2a, 0x86,
- 0x48, 0xce, 0x3d, 0x02, 0x01, 0x04, 0x79, 0x30, 0x77, 0x02, 0x01, 0x01,
- 0x04, 0x20, 0xc9, 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c,
- 0x21, 0x57, 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8,
- 0x9b, 0x12, 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, 0xa0, 0x0a,
- 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0xa1, 0x44,
- 0x03, 0x42, 0x00, 0x04, 0x60, 0xfe, 0xd4, 0xba, 0x25, 0x5a, 0x9d, 0x31,
- 0xc9, 0x61, 0xeb, 0x74, 0xc6, 0x35, 0x6d, 0x68, 0xc0, 0x49, 0xb8, 0x92,
- 0x3b, 0x61, 0xfa, 0x6c, 0xe6, 0x69, 0x62, 0x2e, 0x60, 0xf2, 0x9f, 0xb6,
- 0x79, 0x03, 0xfe, 0x10, 0x08, 0xb8, 0xbc, 0x99, 0xa4, 0x1a, 0xe9, 0xe9,
- 0x56, 0x28, 0xbc, 0x64, 0xf2, 0xf1, 0xb2, 0x0c, 0x2d, 0x7e, 0x9f, 0x51,
- 0x77, 0xa3, 0xc2, 0x94, 0xd4, 0x46, 0x22, 0x99};
-const uint8_t kP256Pkcs8MatchingCurveOIDAndAlgorithmParams[] = {
- 0x30, 0x81, 0x93, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
- 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
- 0x03, 0x01, 0x07, 0x04, 0x79, 0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20,
- 0xc9, 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21, 0x57,
- 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12,
- 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, 0xa0, 0x0a, 0x06, 0x08,
- 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42,
- 0x00, 0x04, 0x60, 0xfe, 0xd4, 0xba, 0x25, 0x5a, 0x9d, 0x31, 0xc9, 0x61,
- 0xeb, 0x74, 0xc6, 0x35, 0x6d, 0x68, 0xc0, 0x49, 0xb8, 0x92, 0x3b, 0x61,
- 0xfa, 0x6c, 0xe6, 0x69, 0x62, 0x2e, 0x60, 0xf2, 0x9f, 0xb6, 0x79, 0x03,
- 0xfe, 0x10, 0x08, 0xb8, 0xbc, 0x99, 0xa4, 0x1a, 0xe9, 0xe9, 0x56, 0x28,
- 0xbc, 0x64, 0xf2, 0xf1, 0xb2, 0x0c, 0x2d, 0x7e, 0x9f, 0x51, 0x77, 0xa3,
- 0xc2, 0x94, 0xd4, 0x46, 0x22, 0x99};
-const uint8_t kP256Pkcs8DissimilarCurveOIDAndAlgorithmParams[] = {
- 0x30, 0x81, 0x90, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
- 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
- 0x03, 0x01, 0x07, 0x04, 0x76, 0x30, 0x74, 0x02, 0x01, 0x01, 0x04, 0x20,
- 0xc9, 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21, 0x57,
- 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12,
- 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, 0xa0, 0x07, 0x06, 0x05,
- 0x2b, 0x81, 0x04, 0x00, 0x22, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0x60,
- 0xfe, 0xd4, 0xba, 0x25, 0x5a, 0x9d, 0x31, 0xc9, 0x61, 0xeb, 0x74, 0xc6,
- 0x35, 0x6d, 0x68, 0xc0, 0x49, 0xb8, 0x92, 0x3b, 0x61, 0xfa, 0x6c, 0xe6,
- 0x69, 0x62, 0x2e, 0x60, 0xf2, 0x9f, 0xb6, 0x79, 0x03, 0xfe, 0x10, 0x08,
- 0xb8, 0xbc, 0x99, 0xa4, 0x1a, 0xe9, 0xe9, 0x56, 0x28, 0xbc, 0x64, 0xf2,
- 0xf1, 0xb2, 0x0c, 0x2d, 0x7e, 0x9f, 0x51, 0x77, 0xa3, 0xc2, 0x94, 0xd4,
- 0x46, 0x22, 0x99};
-const uint8_t kP256Pkcs8InvalidAlgorithmParams[] = {
- 0x30, 0x81, 0x82, 0x02, 0x01, 0x00, 0x30, 0x0e, 0x06, 0x07, 0x2a, 0x86,
- 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x03, 0x2a, 0x03, 0x04, 0x04, 0x6d,
- 0x30, 0x6b, 0x02, 0x01, 0x01, 0x04, 0x20, 0xc9, 0xaf, 0xa9, 0xd8, 0x45,
- 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21, 0x57, 0x67, 0xb1, 0xd6, 0x93, 0x4e,
- 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12, 0x7b, 0x8a, 0x62, 0x2b, 0x12,
- 0x0f, 0x67, 0x21, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0x60, 0xfe, 0xd4,
- 0xba, 0x25, 0x5a, 0x9d, 0x31, 0xc9, 0x61, 0xeb, 0x74, 0xc6, 0x35, 0x6d,
- 0x68, 0xc0, 0x49, 0xb8, 0x92, 0x3b, 0x61, 0xfa, 0x6c, 0xe6, 0x69, 0x62,
- 0x2e, 0x60, 0xf2, 0x9f, 0xb6, 0x79, 0x03, 0xfe, 0x10, 0x08, 0xb8, 0xbc,
- 0x99, 0xa4, 0x1a, 0xe9, 0xe9, 0x56, 0x28, 0xbc, 0x64, 0xf2, 0xf1, 0xb2,
- 0x0c, 0x2d, 0x7e, 0x9f, 0x51, 0x77, 0xa3, 0xc2, 0x94, 0xd4, 0x46, 0x22,
- 0x99};
-const uint8_t kP256Pkcs8PointNotOnCurve[] = {
- 0x30, 0x81, 0x87, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
- 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
- 0x03, 0x01, 0x07, 0x04, 0x6d, 0x30, 0x6b, 0x02, 0x01, 0x01, 0x04, 0x20,
- 0xc9, 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21, 0x57,
- 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12,
- 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, 0xa1, 0x44, 0x03, 0x42,
- 0x00, 0x04, 0x60, 0xfe, 0xd4, 0xba, 0x25, 0x5a, 0x9d, 0x31, 0xc9, 0x61,
- 0xeb, 0x74, 0xc6, 0x35, 0x6d, 0x68, 0xc0, 0x49, 0xb8, 0x92, 0x3b, 0x61,
- 0xfa, 0x6c, 0xe6, 0x69, 0x62, 0x2e, 0x60, 0xf2, 0x9f, 0xb6, 0x79, 0x03,
- 0xfe, 0x10, 0x08, 0xb8, 0xbc, 0x99, 0xa4, 0x1a, 0xe9, 0xe9, 0x56, 0x28,
- 0xbc, 0x64, 0xf2, 0xf1, 0xb2, 0x0c, 0x2d, 0x7e, 0x9f, 0x51, 0x77, 0xa3,
- 0xc2, 0x94, 0xd4, 0x33, 0x11, 0x77};
-const uint8_t kP256Pkcs8NoPublicKey[] = {
- 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,
- 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,
- 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20, 0xc9,
- 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21, 0x57, 0x67,
- 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12, 0x7b,
- 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21};
-const uint8_t kP256SpkiNoAlgorithmParams[] = {
- 0x30, 0x4f, 0x30, 0x09, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
- 0x01, 0x03, 0x42, 0x00, 0x04, 0x60, 0xfe, 0xd4, 0xba, 0x25, 0x5a, 0x9d,
- 0x31, 0xc9, 0x61, 0xeb, 0x74, 0xc6, 0x35, 0x6d, 0x68, 0xc0, 0x49, 0xb8,
- 0x92, 0x3b, 0x61, 0xfa, 0x6c, 0xe6, 0x69, 0x62, 0x2e, 0x60, 0xf2, 0x9f,
- 0xb6, 0x79, 0x03, 0xfe, 0x10, 0x08, 0xb8, 0xbc, 0x99, 0xa4, 0x1a, 0xe9,
- 0xe9, 0x56, 0x28, 0xbc, 0x64, 0xf2, 0xf1, 0xb2, 0x0c, 0x2d, 0x7e, 0x9f,
- 0x51, 0x77, 0xa3, 0xc2, 0x94, 0xd4, 0x46, 0x22, 0x99};
-const uint8_t kP256SpkiPointNotOnCurve[] = {
- 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
- 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
- 0x42, 0x00, 0x04, 0x60, 0xfe, 0xd4, 0xba, 0x25, 0x5a, 0x9d, 0x31, 0xc9,
- 0x61, 0xeb, 0x74, 0xc6, 0x35, 0x6d, 0x68, 0xc0, 0x49, 0xb8, 0x92, 0x3b,
- 0x61, 0xfa, 0x6c, 0xe6, 0x69, 0x62, 0x2e, 0x60, 0xf2, 0x9f, 0xb6, 0x79,
- 0x03, 0xfe, 0x10, 0x08, 0xb8, 0xbc, 0x99, 0xa4, 0x1a, 0xe9, 0xe9, 0x56,
- 0x28, 0xbc, 0x64, 0xf2, 0xf1, 0xb2, 0x0c, 0x2d, 0x7e, 0x9f, 0x51, 0x77,
- 0xa3, 0xc2, 0x94, 0x00, 0x33, 0x11, 0x77};
-
-} // namespace nss_test
--- a/security/nss/gtests/pk11_gtest/pk11_gtest.gyp
+++ b/security/nss/gtests/pk11_gtest/pk11_gtest.gyp
@@ -8,48 +8,27 @@
],
'targets': [
{
'target_name': 'pk11_gtest',
'type': 'executable',
'sources': [
'pk11_aeskeywrap_unittest.cc',
'pk11_chacha20poly1305_unittest.cc',
- 'pk11_ecdsa_unittest.cc',
'pk11_pbkdf2_unittest.cc',
'pk11_prf_unittest.cc',
'pk11_prng_unittest.cc',
'pk11_rsapss_unittest.cc',
'<(DEPTH)/gtests/common/gtests.cc'
],
'dependencies': [
'<(DEPTH)/exports.gyp:nss_exports',
- '<(DEPTH)/lib/util/util.gyp:nssutil3',
+ '<(DEPTH)/lib/freebl/freebl.gyp:<(freebl_name)',
'<(DEPTH)/gtests/google_test/google_test.gyp:gtest',
],
- 'conditions': [
- [ 'test_build==1', {
- 'dependencies': [
- '<(DEPTH)/lib/nss/nss.gyp:nss_static',
- '<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap_static',
- '<(DEPTH)/lib/cryptohi/cryptohi.gyp:cryptohi',
- '<(DEPTH)/lib/certhigh/certhigh.gyp:certhi',
- '<(DEPTH)/lib/certdb/certdb.gyp:certdb',
- '<(DEPTH)/lib/base/base.gyp:nssb',
- '<(DEPTH)/lib/dev/dev.gyp:nssdev',
- '<(DEPTH)/lib/pki/pki.gyp:nsspki',
- '<(DEPTH)/lib/ssl/ssl.gyp:ssl',
- ],
- }, {
- 'dependencies': [
- '<(DEPTH)/lib/nss/nss.gyp:nss3',
- '<(DEPTH)/lib/ssl/ssl.gyp:ssl3',
- ],
- }],
- ],
}
],
'target_defaults': {
'include_dirs': [
'../../gtests/google_test/gtest/include',
'../../gtests/common'
]
},
--- a/security/nss/gtests/pk11_gtest/pk11_rsapss_unittest.cc
+++ b/security/nss/gtests/pk11_gtest/pk11_rsapss_unittest.cc
@@ -7,44 +7,175 @@
#include <memory>
#include "nss.h"
#include "pk11pub.h"
#include "sechash.h"
#include "gtest/gtest.h"
#include "scoped_ptrs.h"
-#include "pk11_rsapss_vectors.h"
-#include "pk11_signature_test.h"
-
namespace nss_test {
-class Pkcs11RsaPssVectorTest : public Pk11SignatureTest {
- public:
- Pkcs11RsaPssVectorTest() {
- rsaPssParams_.hashAlg = CKM_SHA_1;
- rsaPssParams_.mgf = CKG_MGF1_SHA1;
- rsaPssParams_.sLen = HASH_ResultLenByOidTag(SEC_OID_SHA1);
+// RSA-PSS test vectors, pss-vect.txt, Example 1: A 1024-bit RSA Key Pair
+// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
+const uint8_t kTestVector1Spki[] = {
+ 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
+ 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81,
+ 0x89, 0x02, 0x81, 0x81, 0x00, 0xa5, 0x6e, 0x4a, 0x0e, 0x70, 0x10, 0x17,
+ 0x58, 0x9a, 0x51, 0x87, 0xdc, 0x7e, 0xa8, 0x41, 0xd1, 0x56, 0xf2, 0xec,
+ 0x0e, 0x36, 0xad, 0x52, 0xa4, 0x4d, 0xfe, 0xb1, 0xe6, 0x1f, 0x7a, 0xd9,
+ 0x91, 0xd8, 0xc5, 0x10, 0x56, 0xff, 0xed, 0xb1, 0x62, 0xb4, 0xc0, 0xf2,
+ 0x83, 0xa1, 0x2a, 0x88, 0xa3, 0x94, 0xdf, 0xf5, 0x26, 0xab, 0x72, 0x91,
+ 0xcb, 0xb3, 0x07, 0xce, 0xab, 0xfc, 0xe0, 0xb1, 0xdf, 0xd5, 0xcd, 0x95,
+ 0x08, 0x09, 0x6d, 0x5b, 0x2b, 0x8b, 0x6d, 0xf5, 0xd6, 0x71, 0xef, 0x63,
+ 0x77, 0xc0, 0x92, 0x1c, 0xb2, 0x3c, 0x27, 0x0a, 0x70, 0xe2, 0x59, 0x8e,
+ 0x6f, 0xf8, 0x9d, 0x19, 0xf1, 0x05, 0xac, 0xc2, 0xd3, 0xf0, 0xcb, 0x35,
+ 0xf2, 0x92, 0x80, 0xe1, 0x38, 0x6b, 0x6f, 0x64, 0xc4, 0x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xb2, 0x8d, 0xeb, 0x27, 0xdc, 0xa1,
+ 0x2c, 0x82, 0xc2, 0xd4, 0xc3, 0xf6, 0x6c, 0xd5, 0x00, 0xf1, 0xff, 0x2b,
+ 0x99, 0x4d, 0x8a, 0x4e, 0x30, 0xcb, 0xb3, 0x3c};
- params_.type = siBuffer;
- params_.data = reinterpret_cast<unsigned char*>(&rsaPssParams_);
- params_.len = sizeof(rsaPssParams_);
- }
+// RSA-PSS test vectors, pss-vect.txt, Example 10: A 2048-bit RSA Key Pair
+// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
+const uint8_t kTestVector2Spki[] = {
+ 0x30, 0x82, 0x01, 0x21, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
+ 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0e, 0x00,
+ 0x30, 0x82, 0x01, 0x09, 0x02, 0x82, 0x01, 0x00, 0xa5, 0xdd, 0x86, 0x7a,
+ 0xc4, 0xcb, 0x02, 0xf9, 0x0b, 0x94, 0x57, 0xd4, 0x8c, 0x14, 0xa7, 0x70,
+ 0xef, 0x99, 0x1c, 0x56, 0xc3, 0x9c, 0x0e, 0xc6, 0x5f, 0xd1, 0x1a, 0xfa,
+ 0x89, 0x37, 0xce, 0xa5, 0x7b, 0x9b, 0xe7, 0xac, 0x73, 0xb4, 0x5c, 0x00,
+ 0x17, 0x61, 0x5b, 0x82, 0xd6, 0x22, 0xe3, 0x18, 0x75, 0x3b, 0x60, 0x27,
+ 0xc0, 0xfd, 0x15, 0x7b, 0xe1, 0x2f, 0x80, 0x90, 0xfe, 0xe2, 0xa7, 0xad,
+ 0xcd, 0x0e, 0xef, 0x75, 0x9f, 0x88, 0xba, 0x49, 0x97, 0xc7, 0xa4, 0x2d,
+ 0x58, 0xc9, 0xaa, 0x12, 0xcb, 0x99, 0xae, 0x00, 0x1f, 0xe5, 0x21, 0x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Example 10.1
+const uint8_t kTestVector2Data[] = {
+ 0x88, 0x31, 0x77, 0xe5, 0x12, 0x6b, 0x9b, 0xe2, 0xd9, 0xa9,
+ 0x68, 0x03, 0x27, 0xd5, 0x37, 0x0c, 0x6f, 0x26, 0x86, 0x1f,
+ 0x58, 0x20, 0xc4, 0x3d, 0xa6, 0x7a, 0x3a, 0xd6, 0x09};
+const uint8_t kTestVector2Sig[] = {
+ 0x82, 0xc2, 0xb1, 0x60, 0x09, 0x3b, 0x8a, 0xa3, 0xc0, 0xf7, 0x52, 0x2b,
+ 0x19, 0xf8, 0x73, 0x54, 0x06, 0x6c, 0x77, 0x84, 0x7a, 0xbf, 0x2a, 0x9f,
+ 0xce, 0x54, 0x2d, 0x0e, 0x84, 0xe9, 0x20, 0xc5, 0xaf, 0xb4, 0x9f, 0xfd,
+ 0xfd, 0xac, 0xe1, 0x65, 0x60, 0xee, 0x94, 0xa1, 0x36, 0x96, 0x01, 0x14,
+ 0x8e, 0xba, 0xd7, 0xa0, 0xe1, 0x51, 0xcf, 0x16, 0x33, 0x17, 0x91, 0xa5,
+ 0x72, 0x7d, 0x05, 0xf2, 0x1e, 0x74, 0xe7, 0xeb, 0x81, 0x14, 0x40, 0x20,
+ 0x69, 0x35, 0xd7, 0x44, 0x76, 0x5a, 0x15, 0xe7, 0x9f, 0x01, 0x5c, 0xb6,
+ 0x6c, 0x53, 0x2c, 0x87, 0xa6, 0xa0, 0x59, 0x61, 0xc8, 0xbf, 0xad, 0x74,
+ 0x1a, 0x9a, 0x66, 0x57, 0x02, 0x28, 0x94, 0x39, 0x3e, 0x72, 0x23, 0x73,
+ 0x97, 0x96, 0xc0, 0x2a, 0x77, 0x45, 0x5d, 0x0f, 0x55, 0x5b, 0x0e, 0xc0,
+ 0x1d, 0xdf, 0x25, 0x9b, 0x62, 0x07, 0xfd, 0x0f, 0xd5, 0x76, 0x14, 0xce,
+ 0xf1, 0xa5, 0x57, 0x3b, 0xaa, 0xff, 0x4e, 0xc0, 0x00, 0x69, 0x95, 0x16,
+ 0x59, 0xb8, 0x5f, 0x24, 0x30, 0x0a, 0x25, 0x16, 0x0c, 0xa8, 0x52, 0x2d,
+ 0xc6, 0xe6, 0x72, 0x7e, 0x57, 0xd0, 0x19, 0xd7, 0xe6, 0x36, 0x29, 0xb8,
+ 0xfe, 0x5e, 0x89, 0xe2, 0x5c, 0xc1, 0x5b, 0xeb, 0x3a, 0x64, 0x75, 0x77,
+ 0x55, 0x92, 0x99, 0x28, 0x0b, 0x9b, 0x28, 0xf7, 0x9b, 0x04, 0x09, 0x00,
+ 0x0b, 0xe2, 0x5b, 0xbd, 0x96, 0x40, 0x8b, 0xa3, 0xb4, 0x3c, 0xc4, 0x86,
+ 0x18, 0x4d, 0xd1, 0xc8, 0xe6, 0x25, 0x53, 0xfa, 0x1a, 0xf4, 0x04, 0x0f,
+ 0x60, 0x66, 0x3d, 0xe7, 0xf5, 0xe4, 0x9c, 0x04, 0x38, 0x8e, 0x25, 0x7f,
+ 0x1c, 0xe8, 0x9c, 0x95, 0xda, 0xb4, 0x8a, 0x31, 0x5d, 0x9b, 0x66, 0xb1,
+ 0xb7, 0x62, 0x82, 0x33, 0x87, 0x6f, 0xf2, 0x38, 0x52, 0x30, 0xd0, 0x70,
+ 0xd0, 0x7e, 0x16, 0x66};
- protected:
- CK_MECHANISM_TYPE mechanism() { return CKM_RSA_PKCS_PSS; }
- SECItem* parameters() { return ¶ms_; }
- SECOidTag hashOID() { return SEC_OID_SHA1; }
+static unsigned char* toUcharPtr(const uint8_t* v) {
+ return const_cast<unsigned char*>(static_cast<const unsigned char*>(v));
+}
+
+class Pkcs11RsaPssTest : public ::testing::Test {};
+
+class Pkcs11RsaPssVectorTest : public Pkcs11RsaPssTest {
+ public:
+ void Verify(const uint8_t* spki, size_t spki_len, const uint8_t* data,
+ size_t data_len, const uint8_t* sig, size_t sig_len) {
+ // Verify data signed with PSS/SHA-1.
+ SECOidTag hashOid = SEC_OID_SHA1;
+ CK_MECHANISM_TYPE hashMech = CKM_SHA_1;
+ CK_RSA_PKCS_MGF_TYPE mgf = CKG_MGF1_SHA1;
+
+ // Set up PSS parameters.
+ unsigned int hLen = HASH_ResultLenByOidTag(hashOid);
+ CK_RSA_PKCS_PSS_PARAMS rsaPssParams = {hashMech, mgf, hLen};
+ SECItem params = {siBuffer, reinterpret_cast<unsigned char*>(&rsaPssParams),
+ sizeof(rsaPssParams)};
- private:
- CK_RSA_PKCS_PSS_PARAMS rsaPssParams_;
- SECItem params_;
+ // Import public key.
+ SECItem spkiItem = {siBuffer, toUcharPtr(spki),
+ static_cast<unsigned int>(spki_len)};
+ ScopedCERTSubjectPublicKeyInfo certSpki(
+ SECKEY_DecodeDERSubjectPublicKeyInfo(&spkiItem));
+ ScopedSECKEYPublicKey pubKey(SECKEY_ExtractPublicKey(certSpki.get()));
+
+ // Hash the data.
+ std::vector<uint8_t> hashBuf(hLen);
+ SECItem hash = {siBuffer, &hashBuf[0],
+ static_cast<unsigned int>(hashBuf.size())};
+ SECStatus rv = PK11_HashBuf(hashOid, hash.data, toUcharPtr(data), data_len);
+ EXPECT_EQ(rv, SECSuccess);
+
+ // Verify.
+ CK_MECHANISM_TYPE mech = CKM_RSA_PKCS_PSS;
+ SECItem sigItem = {siBuffer, toUcharPtr(sig),
+ static_cast<unsigned int>(sig_len)};
+ rv = PK11_VerifyWithMechanism(pubKey.get(), mech, ¶ms, &sigItem, &hash,
+ nullptr);
+ EXPECT_EQ(rv, SECSuccess);
+ }
};
-TEST_F(Pkcs11RsaPssVectorTest, GenerateAndSignAndVerify) {
+#define PSS_TEST_VECTOR_VERIFY(spki, data, sig) \
+ Verify(spki, sizeof(spki), data, sizeof(data), sig, sizeof(sig));
+
+TEST_F(Pkcs11RsaPssTest, GenerateAndSignAndVerify) {
// Sign data with a 1024-bit RSA key, using PSS/SHA-256.
SECOidTag hashOid = SEC_OID_SHA256;
CK_MECHANISM_TYPE hashMech = CKM_SHA256;
CK_RSA_PKCS_MGF_TYPE mgf = CKG_MGF1_SHA256;
PK11RSAGenParams rsaGenParams = {1024, 0x10001};
// Generate RSA key pair.
ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
@@ -68,132 +199,44 @@ TEST_F(Pkcs11RsaPssVectorTest, GenerateA
static_cast<unsigned int>(sigBuf.size())};
// Set up PSS parameters.
CK_RSA_PKCS_PSS_PARAMS rsaPssParams = {hashMech, mgf, hLen};
SECItem params = {siBuffer, reinterpret_cast<unsigned char*>(&rsaPssParams),
sizeof(rsaPssParams)};
// Sign.
- rv = PK11_SignWithMechanism(privKey.get(), mechanism(), ¶ms, &sig, &data);
+ CK_MECHANISM_TYPE mech = CKM_RSA_PKCS_PSS;
+ rv = PK11_SignWithMechanism(privKey.get(), mech, ¶ms, &sig, &data);
EXPECT_EQ(rv, SECSuccess);
// Verify.
- rv = PK11_VerifyWithMechanism(pubKey.get(), mechanism(), ¶ms, &sig, &data,
+ rv = PK11_VerifyWithMechanism(pubKey.get(), mech, ¶ms, &sig, &data,
nullptr);
EXPECT_EQ(rv, SECSuccess);
// Verification with modified data must fail.
data.data[0] ^= 0xff;
- rv = PK11_VerifyWithMechanism(pubKey.get(), mechanism(), ¶ms, &sig, &data,
+ rv = PK11_VerifyWithMechanism(pubKey.get(), mech, ¶ms, &sig, &data,
nullptr);
EXPECT_EQ(rv, SECFailure);
// Verification with original data but the wrong signature must fail.
data.data[0] ^= 0xff; // Revert previous changes.
sig.data[0] ^= 0xff;
- rv = PK11_VerifyWithMechanism(pubKey.get(), mechanism(), ¶ms, &sig, &data,
+ rv = PK11_VerifyWithMechanism(pubKey.get(), mech, ¶ms, &sig, &data,
nullptr);
EXPECT_EQ(rv, SECFailure);
}
// RSA-PSS test vectors, pss-vect.txt, Example 1.1: A 1024-bit RSA Key Pair
// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature1) {
- SIG_TEST_VECTOR_VERIFY(kTestVector1Spki, kTestVector1Data, kTestVector1Sig);
-}
-TEST_F(Pkcs11RsaPssVectorTest, SignAndVerify1) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kTestVector1Pkcs8, kTestVector1Spki,
- kTestVector1Data);
-}
-
-// RSA-PSS test vectors, pss-vect.txt, Example 2.1: A 1025-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature2) {
- SIG_TEST_VECTOR_VERIFY(kTestVector2Spki, kTestVector2Data, kTestVector2Sig);
-}
-TEST_F(Pkcs11RsaPssVectorTest, SignAndVerify2) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kTestVector2Pkcs8, kTestVector2Spki,
- kTestVector2Data);
-}
-
-// RSA-PSS test vectors, pss-vect.txt, Example 3.1: A 1026-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature3) {
- SIG_TEST_VECTOR_VERIFY(kTestVector3Spki, kTestVector3Data, kTestVector3Sig);
-}
-TEST_F(Pkcs11RsaPssVectorTest, SignAndVerify3) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kTestVector3Pkcs8, kTestVector3Spki,
- kTestVector3Data);
-}
-
-// RSA-PSS test vectors, pss-vect.txt, Example 4.1: A 1027-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature4) {
- SIG_TEST_VECTOR_VERIFY(kTestVector4Spki, kTestVector4Data, kTestVector4Sig);
-}
-TEST_F(Pkcs11RsaPssVectorTest, SignAndVerify4) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kTestVector4Pkcs8, kTestVector4Spki,
- kTestVector4Data);
-}
-
-// RSA-PSS test vectors, pss-vect.txt, Example 5.1: A 1028-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature5) {
- SIG_TEST_VECTOR_VERIFY(kTestVector5Spki, kTestVector5Data, kTestVector5Sig);
-}
-TEST_F(Pkcs11RsaPssVectorTest, SignAndVerify5) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kTestVector5Pkcs8, kTestVector5Spki,
- kTestVector5Data);
-}
-
-// RSA-PSS test vectors, pss-vect.txt, Example 6.1: A 1029-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature6) {
- SIG_TEST_VECTOR_VERIFY(kTestVector6Spki, kTestVector6Data, kTestVector6Sig);
-}
-TEST_F(Pkcs11RsaPssVectorTest, SignAndVerify6) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kTestVector6Pkcs8, kTestVector6Spki,
- kTestVector6Data);
-}
-
-// RSA-PSS test vectors, pss-vect.txt, Example 7.1: A 1030-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature7) {
- SIG_TEST_VECTOR_VERIFY(kTestVector7Spki, kTestVector7Data, kTestVector7Sig);
-}
-TEST_F(Pkcs11RsaPssVectorTest, SignAndVerify7) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kTestVector7Pkcs8, kTestVector7Spki,
- kTestVector7Data);
-}
-
-// RSA-PSS test vectors, pss-vect.txt, Example 8.1: A 1031-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature8) {
- SIG_TEST_VECTOR_VERIFY(kTestVector8Spki, kTestVector8Data, kTestVector8Sig);
-}
-TEST_F(Pkcs11RsaPssVectorTest, SignAndVerify8) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kTestVector8Pkcs8, kTestVector8Spki,
- kTestVector8Data);
-}
-
-// RSA-PSS test vectors, pss-vect.txt, Example 9.1: A 1536-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature9) {
- SIG_TEST_VECTOR_VERIFY(kTestVector9Spki, kTestVector9Data, kTestVector9Sig);
-}
-TEST_F(Pkcs11RsaPssVectorTest, SignAndVerify9) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kTestVector9Pkcs8, kTestVector9Spki,
- kTestVector9Data);
+ PSS_TEST_VECTOR_VERIFY(kTestVector1Spki, kTestVector1Data, kTestVector1Sig);
}
// RSA-PSS test vectors, pss-vect.txt, Example 10.1: A 2048-bit RSA Key Pair
// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature10) {
- SIG_TEST_VECTOR_VERIFY(kTestVector10Spki, kTestVector10Data,
- kTestVector10Sig);
-}
-TEST_F(Pkcs11RsaPssVectorTest, SignAndVerify10) {
- SIG_TEST_VECTOR_SIGN_VERIFY(kTestVector10Pkcs8, kTestVector10Spki,
- kTestVector10Data);
+TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature2) {
+ PSS_TEST_VECTOR_VERIFY(kTestVector2Spki, kTestVector2Data, kTestVector2Sig);
}
} // namespace nss_test
deleted file mode 100644
--- a/security/nss/gtests/pk11_gtest/pk11_rsapss_vectors.h
+++ /dev/null
@@ -1,1083 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-namespace nss_test {
-
-// RSA-PSS test vectors, pss-vect.txt, Example 1: A 1024-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-const uint8_t kTestVector1Pkcs8[] = {
- 0x30, 0x82, 0x02, 0x72, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
- 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
- 0x02, 0x5c, 0x30, 0x82, 0x02, 0x58, 0x02, 0x01, 0x00, 0x02, 0x81, 0x80,
- 0xa5, 0x6e, 0x4a, 0x0e, 0x70, 0x10, 0x17, 0x58, 0x9a, 0x51, 0x87, 0xdc,
- 0x7e, 0xa8, 0x41, 0xd1, 0x56, 0xf2, 0xec, 0x0e, 0x36, 0xad, 0x52, 0xa4,
- 0x4d, 0xfe, 0xb1, 0xe6, 0x1f, 0x7a, 0xd9, 0x91, 0xd8, 0xc5, 0x10, 0x56,
- 0xff, 0xed, 0xb1, 0x62, 0xb4, 0xc0, 0xf2, 0x83, 0xa1, 0x2a, 0x88, 0xa3,
- 0x94, 0xdf, 0xf5, 0x26, 0xab, 0x72, 0x91, 0xcb, 0xb3, 0x07, 0xce, 0xab,
- 0xfc, 0xe0, 0xb1, 0xdf, 0xd5, 0xcd, 0x95, 0x08, 0x09, 0x6d, 0x5b, 0x2b,
- 0x8b, 0x6d, 0xf5, 0xd6, 0x71, 0xef, 0x63, 0x77, 0xc0, 0x92, 0x1c, 0xb2,
- 0x3c, 0x27, 0x0a, 0x70, 0xe2, 0x59, 0x8e, 0x6f, 0xf8, 0x9d, 0x19, 0xf1,
- 0x05, 0xac, 0xc2, 0xd3, 0xf0, 0xcb, 0x35, 0xf2, 0x92, 0x80, 0xe1, 0x38,
- 0x6b, 0x6f, 0x64, 0xc4, 0xef, 0x22, 0xe1, 0xe1, 0xf2, 0x0d, 0x0c, 0xe8,
- 0xcf, 0xfb, 0x22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0xfa, 0x09, 0xef, 0xc0, 0xe5, 0x07,
- 0xac, 0xb2, 0x1e, 0xd7, 0x43, 0x01, 0xef, 0x5b, 0xfd, 0x48, 0xbe, 0x45,
- 0x5e, 0xae, 0xb6, 0xe1, 0x67, 0x82, 0x55, 0x82, 0x75, 0x80, 0xa8, 0xe4,
- 0xe8, 0xe1, 0x41, 0x51, 0xd1, 0x51, 0x0a, 0x82, 0xa3, 0xf2, 0xe7, 0x29,
- 0x02, 0x40, 0x27, 0x15, 0x6a, 0xba, 0x41, 0x26, 0xd2, 0x4a, 0x81, 0xf3,
- 0xa5, 0x28, 0xcb, 0xfb, 0x27, 0xf5, 0x68, 0x86, 0xf8, 0x40, 0xa9, 0xf6,
- 0xe8, 0x6e, 0x17, 0xa4, 0x4b, 0x94, 0xfe, 0x93, 0x19, 0x58, 0x4b, 0x8e,
- 0x22, 0xfd, 0xde, 0x1e, 0x5a, 0x2e, 0x3b, 0xd8, 0xaa, 0x5b, 0xa8, 0xd8,
- 0x58, 0x41, 0x94, 0xeb, 0x21, 0x90, 0xac, 0xf8, 0x32, 0xb8, 0x47, 0xf1,
- 0x3a, 0x3d, 0x24, 0xa7, 0x9f, 0x4d};
-const uint8_t kTestVector1Spki[] = {
- 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
- 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81,
- 0x89, 0x02, 0x81, 0x81, 0x00, 0xa5, 0x6e, 0x4a, 0x0e, 0x70, 0x10, 0x17,
- 0x58, 0x9a, 0x51, 0x87, 0xdc, 0x7e, 0xa8, 0x41, 0xd1, 0x56, 0xf2, 0xec,
- 0x0e, 0x36, 0xad, 0x52, 0xa4, 0x4d, 0xfe, 0xb1, 0xe6, 0x1f, 0x7a, 0xd9,
- 0x91, 0xd8, 0xc5, 0x10, 0x56, 0xff, 0xed, 0xb1, 0x62, 0xb4, 0xc0, 0xf2,
- 0x83, 0xa1, 0x2a, 0x88, 0xa3, 0x94, 0xdf, 0xf5, 0x26, 0xab, 0x72, 0x91,
- 0xcb, 0xb3, 0x07, 0xce, 0xab, 0xfc, 0xe0, 0xb1, 0xdf, 0xd5, 0xcd, 0x95,
- 0x08, 0x09, 0x6d, 0x5b, 0x2b, 0x8b, 0x6d, 0xf5, 0xd6, 0x71, 0xef, 0x63,
- 0x77, 0xc0, 0x92, 0x1c, 0xb2, 0x3c, 0x27, 0x0a, 0x70, 0xe2, 0x59, 0x8e,
- 0x6f, 0xf8, 0x9d, 0x19, 0xf1, 0x05, 0xac, 0xc2, 0xd3, 0xf0, 0xcb, 0x35,
- 0xf2, 0x92, 0x80, 0xe1, 0x38, 0x6b, 0x6f, 0x64, 0xc4, 0xef, 0x22, 0xe1,
- 0xe1, 0xf2, 0x0d, 0x0c, 0xe8, 0xcf, 0xfb, 0x22, 0x49, 0xbd, 0x9a, 0x21,
- 0x37, 0x02, 0x03, 0x01, 0x00, 0x01};
-// RSA-PSS test vectors, pss-vect.txt, Example 1.1
-const uint8_t kTestVector1Data[] = {
- 0xcd, 0xc8, 0x7d, 0xa2, 0x23, 0xd7, 0x86, 0xdf, 0x3b, 0x45, 0xe0, 0xbb,
- 0xbc, 0x72, 0x13, 0x26, 0xd1, 0xee, 0x2a, 0xf8, 0x06, 0xcc, 0x31, 0x54,
- 0x75, 0xcc, 0x6f, 0x0d, 0x9c, 0x66, 0xe1, 0xb6, 0x23, 0x71, 0xd4, 0x5c,
- 0xe2, 0x39, 0x2e, 0x1a, 0xc9, 0x28, 0x44, 0xc3, 0x10, 0x10, 0x2f, 0x15,
- 0x6a, 0x0d, 0x8d, 0x52, 0xc1, 0xf4, 0xc4, 0x0b, 0xa3, 0xaa, 0x65, 0x09,
- 0x57, 0x86, 0xcb, 0x76, 0x97, 0x57, 0xa6, 0x56, 0x3b, 0xa9, 0x58, 0xfe,
- 0xd0, 0xbc, 0xc9, 0x84, 0xe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xfd,
- 0x44, 0xdc, 0x86, 0x34, 0xe4, 0x07, 0xc8, 0xe0, 0xe4, 0x36, 0x0b, 0xc2,
- 0x26, 0xf3, 0xec, 0x22, 0x7f, 0x9d, 0x9e, 0x54, 0x63, 0x8e, 0x8d, 0x31,
- 0xf5, 0x05, 0x12, 0x15, 0xdf, 0x6e, 0xbb, 0x9c, 0x2f, 0x95, 0x79, 0xaa,
- 0x77, 0x59, 0x8a, 0x38, 0xf9, 0x14, 0xb5, 0xb9, 0xc1, 0xbd, 0x83, 0xc4,
- 0xe2, 0xf9, 0xf3, 0x82, 0xa0, 0xd0, 0xaa, 0x35, 0x42, 0xff, 0xee, 0x65,
- 0x98, 0x4a, 0x60, 0x1b, 0xc6, 0x9e, 0xb2, 0x8d, 0xeb, 0x27, 0xdc, 0xa1,
- 0x2c, 0x82, 0xc2, 0xd4, 0xc3, 0xf6, 0x6c, 0xd5, 0x00, 0xf1, 0xff, 0x2b,
- 0x99, 0x4d, 0x8a, 0x4e, 0x30, 0xcb, 0xb3, 0x3c};
-
-// RSA-PSS test vectors, pss-vect.txt, Example 2: A 1025-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-const uint8_t kTestVector2Pkcs8[] = {
- 0x30, 0x82, 0x02, 0x75, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
- 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
- 0x02, 0x5f, 0x30, 0x82, 0x02, 0x5b, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81,
- 0x01, 0xd4, 0x0c, 0x1b, 0xcf, 0x97, 0xa6, 0x8a, 0xe7, 0xcd, 0xbd, 0x8a,
- 0x7b, 0xf3, 0xe3, 0x4f, 0xa1, 0x9d, 0xcc, 0xa4, 0xef, 0x75, 0xa4, 0x74,
- 0x54, 0x37, 0x5f, 0x94, 0x51, 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6a, 0x01, 0x7e, 0xdc, 0x61, 0xfd, 0x32, 0x6c, 0x4b, 0x33,
- 0xc9, 0x02, 0x03, 0x01, 0x00, 0x01};
-// RSA-PSS test vectors, pss-vect.txt, Example 2.1
-const uint8_t kTestVector2Data[] = {
- 0xda, 0xba, 0x03, 0x20, 0x66, 0x26, 0x3f, 0xae, 0xdb, 0x65, 0x98,
- 0x48, 0x11, 0x52, 0x78, 0xa5, 0x2c, 0x44, 0xfa, 0xa3, 0xa7, 0x6f,
- 0x37, 0x51, 0x5e, 0xd3, 0x36, 0x32, 0x10, 0x72, 0xc4, 0x0a, 0x9d,
- 0x9b, 0x53, 0xbc, 0x05, 0x01, 0x40, 0x78, 0xad, 0xf5, 0x20, 0x87,
- 0x51, 0x46, 0xaa, 0xe7, 0x0f, 0xf0, 0x60, 0x22, 0x6d, 0xcb, 0x7b,
- 0x1f, 0x1f, 0xc2, 0x7e, 0x93, 0x60};
-const uint8_t kTestVector2Sig[] = {
- 0x01, 0x4c, 0x5b, 0xa5, 0x33, 0x83, 0x28, 0xcc, 0xc6, 0xe7, 0xa9, 0x0b,
- 0xf1, 0xc0, 0xab, 0x3f, 0xd6, 0x06, 0xff, 0x47, 0x96, 0xd3, 0xc1, 0x2e,
- 0x4b, 0x63, 0x9e, 0xd9, 0x13, 0x6a, 0x5f, 0xec, 0x6c, 0x16, 0xd8, 0x88,
- 0x4b, 0xdd, 0x99, 0xcf, 0xdc, 0x52, 0x14, 0x56, 0xb0, 0x74, 0x2b, 0x73,
- 0x68, 0x68, 0xcf, 0x90, 0xde, 0x09, 0x9a, 0xdb, 0x8d, 0x5f, 0xfd, 0x1d,
- 0xef, 0xf3, 0x9b, 0xa4, 0x00, 0x7a, 0xb7, 0x46, 0xce, 0xfd, 0xb2, 0x2d,
- 0x7d, 0xf0, 0xe2, 0x25, 0xf5, 0x46, 0x27, 0xdc, 0x65, 0x46, 0x61, 0x31,
- 0x72, 0x1b, 0x90, 0xaf, 0x44, 0x53, 0x63, 0xa8, 0x35, 0x8b, 0x9f, 0x60,
- 0x76, 0x42, 0xf7, 0x8f, 0xab, 0x0a, 0xb0, 0xf4, 0x3b, 0x71, 0x68, 0xd6,
- 0x4b, 0xae, 0x70, 0xd8, 0x82, 0x78, 0x48, 0xd8, 0xef, 0x1e, 0x42, 0x1c,
- 0x57, 0x54, 0xdd, 0xf4, 0x2c, 0x25, 0x89, 0xb5, 0xb3};
-
-// RSA-PSS test vectors, pss-vect.txt, Example 3: A 1026-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-const uint8_t kTestVector3Pkcs8[] = {
- 0x30, 0x82, 0x02, 0x76, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
- 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
- 0x02, 0x60, 0x30, 0x82, 0x02, 0x5c, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81,
- 0x02, 0xf2, 0x46, 0xef, 0x45, 0x1e, 0xd3, 0xee, 0xbb, 0x9a, 0x31, 0x02,
- 0x00, 0xcc, 0x25, 0x85, 0x9c, 0x04, 0x8e, 0x4b, 0xe7, 0x98, 0x30, 0x29,
- 0x91, 0x11, 0x2e, 0xb6, 0x8c, 0xe6, 0xdb, 0x67, 0x4e, 0x28, 0x0d, 0xa2,
- 0x1f, 0xed, 0xed, 0x1a, 0xe7, 0x48, 0x80, 0xca, 0x52, 0x2b, 0x18, 0xdb,
- 0x24, 0x93, 0x85, 0x01, 0x28, 0x27, 0xc5, 0x15, 0xf0, 0xe4, 0x66, 0xa1,
- 0xff, 0xa6, 0x91, 0xd9, 0x81, 0x70, 0x57, 0x4e, 0x9d, 0x0e, 0xad, 0xb0,
- 0x87, 0x58, 0x6c, 0xa4, 0x89, 0x33, 0xda, 0x3c, 0xc9, 0x53, 0xd9, 0x5b,
- 0xd0, 0xed, 0x50, 0xde,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0xe2, 0xf9, 0xd0, 0x26, 0x1d, 0x51, 0x65, 0x01, 0xc6,
- 0xae, 0x39, 0xf1, 0x4a, 0x47, 0x6c, 0xe2, 0xcc, 0xf5, 0x02, 0x41, 0x01,
- 0x1a, 0x0d, 0x36, 0x79, 0x4b, 0x04, 0xa8, 0x54, 0xaa, 0xb4, 0xb2, 0x46,
- 0x2d, 0x43, 0x9a, 0x50, 0x46, 0xc9, 0x1d, 0x94, 0x0b, 0x2b, 0xc6, 0xf7,
- 0x5b, 0x62, 0x95, 0x6f, 0xef, 0x35, 0xa2, 0xa6, 0xe6, 0x3c, 0x53, 0x09,
- 0x81, 0x7f, 0x30, 0x7b, 0xbf, 0xf9, 0xd5, 0x9e, 0x7e, 0x33, 0x1b, 0xd3,
- 0x63, 0xf6, 0xd6, 0x68, 0x49, 0xb1, 0x83, 0x46, 0xad, 0xea, 0x16, 0x9f,
- 0x0a, 0xe9, 0xae, 0xc1, 0x02, 0x40, 0x0b, 0x30, 0xf0, 0xec, 0xf5, 0x58,
- 0x75, 0x2f, 0xb3, 0xa6, 0xce, 0x4b, 0xa2, 0xb8, 0xc6, 0x75, 0xf6, 0x59,
- 0xeb, 0xa6, 0xc3, 0x76, 0x58, 0x5a, 0x1b, 0x39, 0x71, 0x2d, 0x03, 0x8a,
- 0xe3, 0xd2, 0xb4, 0x6f, 0xcb, 0x41, 0x8a, 0xe1, 0x5d, 0x09, 0x05, 0xda,
- 0x64, 0x40, 0xe1, 0x51, 0x3a, 0x30, 0xb9, 0xb7, 0xd6, 0x66, 0x8f, 0xbc,
- 0x5e, 0x88, 0xe5, 0xab, 0x7a, 0x17, 0x5e, 0x73, 0xba, 0x35};
-const uint8_t kTestVector3Spki[] = {
- 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
- 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81,
- 0x89, 0x02, 0x81, 0x81, 0x02, 0xf2, 0x46, 0xef, 0x45, 0x1e, 0xd3, 0xee,
- 0xbb, 0x9a, 0x31, 0x02, 0x00, 0xcc, 0x25, 0x85, 0x9c, 0x04, 0x8e, 0x4b,
- 0xe7, 0x98, 0x30, 0x29, 0x91, 0x11, 0x2e, 0xb6, 0x8c, 0xe6, 0xdb, 0x67,
- 0x4e, 0x28, 0x0d, 0xa2, 0x1f, 0xed, 0xed, 0x1a, 0xe7, 0x48, 0x80, 0xca,
- 0x52, 0x2b, 0x18, 0xdb, 0x24, 0x93, 0x85, 0x01, 0x28, 0x27, 0xc5, 0x15,
- 0xf0, 0xe4, 0x66, 0xa1, 0xff, 0xa6, 0x91, 0xd9, 0x81, 0x70, 0x57, 0x4e,
- 0x9d, 0x0e, 0xad, 0xb0, 0x87, 0x58, 0x6c, 0xa4, 0x89, 0x33, 0xda, 0x3c,
- 0xc9, 0x53, 0xd9, 0x5b, 0xd0, 0xed, 0x50, 0xde, 0x10, 0xdd, 0xcb, 0x67,
- 0x36, 0x10, 0x7d, 0x6c, 0x83, 0x1c, 0x7f, 0x66, 0x3e, 0x83, 0x3c, 0xa4,
- 0xc0, 0x97, 0xe7, 0x00, 0xce, 0x0f, 0xb9, 0x45, 0xf8, 0x8f, 0xb8, 0x5f,
- 0xe8, 0xe5, 0xa7, 0x73, 0x17, 0x25, 0x65, 0xb9, 0x14, 0xa4, 0x71, 0xa4,
- 0x43, 0x02, 0x03, 0x01, 0x00, 0x01};
-// RSA-PSS test vectors, pss-vect.txt, Example 3.1
-const uint8_t kTestVector3Data[] = {
- 0x59, 0x4b, 0x37, 0x33, 0x3b, 0xbb, 0x2c, 0x84, 0x52, 0x4a,
- 0x87, 0xc1, 0xa0, 0x1f, 0x75, 0xfc, 0xec, 0x0e, 0x32, 0x56,
- 0xf1, 0x08, 0xe3, 0x8d, 0xca, 0x36, 0xd7, 0x0d, 0x00, 0x57};
-const uint8_t kTestVector3Sig[] = {
- 0x00, 0x88, 0xb1, 0x35, 0xfb, 0x17, 0x94, 0xb6, 0xb9, 0x6c, 0x4a, 0x3e,
- 0x67, 0x81, 0x97, 0xf8, 0xca, 0xc5, 0x2b, 0x64, 0xb2, 0xfe, 0x90, 0x7d,
- 0x6f, 0x27, 0xde, 0x76, 0x11, 0x24, 0x96, 0x4a, 0x99, 0xa0, 0x1a, 0x88,
- 0x27, 0x40, 0xec, 0xfa, 0xed, 0x6c, 0x01, 0xa4, 0x74, 0x64, 0xbb, 0x05,
- 0x18, 0x23, 0x13, 0xc0, 0x13, 0x38, 0xa8, 0xcd, 0x09, 0x72, 0x14, 0xcd,
- 0x68, 0xca, 0x10, 0x3b, 0xd5, 0x7d, 0x3b, 0xc9, 0xe8, 0x16, 0x21, 0x3e,
- 0x61, 0xd7, 0x84, 0xf1, 0x82, 0x46, 0x7a, 0xbf, 0x8a, 0x01, 0xcf, 0x25,
- 0x3e, 0x99, 0xa1, 0x56, 0xea, 0xa8, 0xe3, 0xe1, 0xf9, 0x0e, 0x3c, 0x6e,
- 0x4e, 0x3a, 0xa2, 0xd8, 0x3e, 0xd0, 0x34, 0x5b, 0x89, 0xfa, 0xfc, 0x9c,
- 0x26, 0x07, 0x7c, 0x14, 0xb6, 0xac, 0x51, 0x45, 0x4f, 0xa2, 0x6e, 0x44,
- 0x6e, 0x3a, 0x2f, 0x15, 0x3b, 0x2b, 0x16, 0x79, 0x7f};
-
-// RSA-PSS test vectors, pss-vect.txt, Example 4: A 1027-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-const uint8_t kTestVector4Pkcs8[] = {
- 0x30, 0x82, 0x02, 0x78, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
- 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
- 0x02, 0x62, 0x30, 0x82, 0x02, 0x5e, 0x02, 0x01, 0x00, 0x02,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06, 0x00, 0xc4, 0xc2,
- 0x18, 0x47, 0x45, 0x9f, 0xe5, 0x76, 0x70, 0x3e, 0x2e, 0xbe, 0xca, 0xe8,
- 0xa5, 0x09, 0x4e, 0xe6, 0x3f, 0x53, 0x6b, 0xf4, 0xac, 0x68, 0xd3, 0xc1,
- 0x3e, 0x5e, 0x4f, 0x12, 0xac, 0x5c, 0xc1, 0x0a, 0xb6, 0xa2, 0xd0, 0x5a,
- 0x19, 0x92, 0x14, 0xd1, 0x82, 0x47, 0x47, 0xd5, 0x51, 0x90, 0x96, 0x36,
- 0xb7, 0x74, 0xc2, 0x2c, 0xac, 0x0b, 0x83, 0x75, 0x99, 0xab, 0xcc, 0x75};
-const uint8_t kTestVector4Spki[] = {
- 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
- 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81,
- 0x89, 0x02, 0x81, 0x81, 0x05, 0x4a, 0xdb, 0x78, 0x86, 0x44, 0x7e, 0xfe,
- 0x6f, 0x57, 0xe0, 0x36, 0x8f, 0x06, 0xcf, 0x52, 0xb0, 0xa3, 0x37, 0x07,
- 0x60, 0xd1, 0x61, 0xce, 0xf1, 0x26, 0xb9, 0x1b, 0xe7, 0xf8, 0x9c, 0x42,
- 0x1b, 0x62, 0xa6, 0xec, 0x1d, 0xa3, 0xc3, 0x11, 0xd7, 0x5e, 0xd5, 0x0e,
- 0x0a, 0xb5, 0xff, 0xf3, 0xfd, 0x33, 0x8a, 0xcc, 0x3a, 0xa8, 0xa4, 0xe7,
- 0x7e, 0xe2, 0x63, 0x69, 0xac, 0xb8, 0x1b, 0xa9, 0x00, 0xfa, 0x83, 0xf5,
- 0x30, 0x0c, 0xf9, 0xbb, 0x6c, 0x53, 0xad, 0x1d, 0xc8, 0xa1, 0x78, 0xb8,
- 0x15, 0xdb, 0x42, 0x35, 0xa9, 0xa9, 0xda, 0x0c, 0x06, 0xde, 0x4e, 0x61,
- 0x5e, 0xa1, 0x27, 0x7c, 0xe5, 0x59, 0xe9, 0xc1, 0x08, 0xde, 0x58, 0xc1,
- 0x4a, 0x81, 0xaa, 0x77, 0xf5, 0xa6, 0xf8, 0xd1, 0x33, 0x54, 0x94, 0x49,
- 0x88, 0x48, 0xc8, 0xb9, 0x59, 0x40, 0x74, 0x0b, 0xe7, 0xbf, 0x7c, 0x37,
- 0x05, 0x02, 0x03, 0x01, 0x00, 0x01};
-// RSA-PSS test vectors, pss-vect.txt, Example 4.1
-const uint8_t kTestVector4Data[] = {0x9f, 0xb0, 0x3b, 0x82,
- 0x7c, 0x82, 0x17, 0xd9};
-const uint8_t kTestVector4Sig[] = {
- 0x03, 0x23, 0xd5, 0xb7, 0xbf, 0x20, 0xba, 0x45, 0x39, 0x28, 0x9a, 0xe4,
- 0x52, 0xae, 0x42, 0x97, 0x08, 0x0f, 0xef, 0xf4, 0x51, 0x84, 0x23, 0xff,
- 0x48, 0x11, 0xa8, 0x17, 0x83, 0x7e, 0x7d, 0x82, 0xf1, 0x83, 0x6c, 0xdf,
- 0xab, 0x54, 0x51, 0x4f, 0xf0, 0x88, 0x7b, 0xdd, 0xee, 0xbf, 0x40, 0xbf,
- 0x99, 0xb0, 0x47, 0xab, 0xc3, 0xec, 0xfa, 0x6a, 0x37, 0xa3, 0xef, 0x00,
- 0xf4, 0xa0, 0xc4, 0xa8, 0x8a, 0xae, 0x09, 0x04, 0xb7, 0x45, 0xc8, 0x46,
- 0xc4, 0x10, 0x7e, 0x87, 0x97, 0x72, 0x3e, 0x8a, 0xc8, 0x10, 0xd9, 0xe3,
- 0xd9, 0x5d, 0xfa, 0x30, 0xff, 0x49, 0x66, 0xf4, 0xd7, 0x5d, 0x13, 0x76,
- 0x8d, 0x20, 0x85, 0x7f, 0x2b, 0x14, 0x06, 0xf2, 0x64, 0xcf, 0xe7, 0x5e,
- 0x27, 0xd7, 0x65, 0x2f, 0x4b, 0x5e, 0xd3, 0x57, 0x5f, 0x28, 0xa7, 0x02,
- 0xf8, 0xc4, 0xed, 0x9c, 0xf9, 0xb2, 0xd4, 0x49, 0x48};
-
-// RSA-PSS test vectors, pss-vect.txt, Example 5: A 1028-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-const uint8_t kTestVector5Pkcs8[] = {
- 0x30, 0x82, 0x02, 0x78, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
- 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
- 0x02, 0x62, 0x30, 0x82, 0x02, 0x5e, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81,
- 0x0d, 0x10, 0xf6, 0x61, 0xf2, 0x99, 0x40, 0xf5, 0xed, 0x39, 0xaa, 0x26,
- 0x09, 0x66, 0xde, 0xb4, 0x78, 0x43, 0x67, 0x9d, 0x2b, 0x6f, 0xb2, 0x5b,
- 0x3d, 0xe3, 0x70, 0xf3, 0xac, 0x7c, 0x19, 0x91, 0x63, 0x91, 0xfd, 0x25,
- 0xfb, 0x52, 0x7e, 0xbf, 0xa6, 0xa4, 0xb4, 0xdf, 0x45, 0xa1, 0x75, 0x9d,
- 0x99, 0x6c, 0x4b, 0xb4, 0xeb, 0xd1, 0x88, 0x28, 0xc4, 0x4f, 0xc5, 0x2d,
- 0x01, 0x91, 0x87, 0x17, 0x40, 0x52, 0x5f, 0x47, 0xa4, 0xb0, 0xcc, 0x8d,
- 0xa3, 0x25, 0xed, 0x8a, 0xa6, 0x76, 0xb0, 0xd0, 0xf6, 0x26, 0xe0, 0xa7,
- 0x7f, 0x07, 0x69, 0x21, 0x70, 0xac, 0xac, 0x80, 0x82, 0xf4, 0x2f, 0xaa,
- 0x7d, 0xc7, 0xcd, 0x12, 0x3e, 0x73, 0x0e, 0x31, 0xa8, 0x79, 0x85,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0x02,
- 0x41, 0x02, 0xbb, 0xe7, 0x06, 0x07, 0x8b, 0x5c, 0x0b, 0x39, 0x15, 0x12,
- 0xd4, 0x11, 0xdb, 0x1b, 0x19, 0x9b, 0x5a, 0x56, 0x64, 0xb8, 0x40, 0x42,
- 0xea, 0xd3, 0x7f, 0xe9, 0x94, 0xae, 0x72, 0xb9, 0x53, 0x2d, 0xfb, 0xfb,
- 0x3e, 0x9e, 0x69, 0x81, 0xa0, 0xfb, 0xb8, 0x06, 0x51, 0x31, 0x41, 0xb7,
- 0xc2, 0x16, 0x3f, 0xe5, 0x6c, 0x39, 0x5e, 0x4b, 0xfa, 0xee, 0x57, 0xe3,
- 0x83, 0x3f, 0x9b, 0x91, 0x8d, 0xf9, 0x02, 0x40, 0x02, 0x42, 0xb6, 0xcd,
- 0x00, 0xd3, 0x0a, 0x76, 0x7a, 0xee, 0x9a, 0x89, 0x8e, 0xad, 0x45, 0x3c,
- 0x8e, 0xae, 0xa6, 0x3d, 0x50, 0x0b, 0x7d, 0x1e, 0x00, 0x71, 0x3e, 0xda,
- 0xe5, 0x1c, 0xe3, 0x6b, 0x23, 0xb6, 0x64, 0xdf, 0x26, 0xe6, 0x3e, 0x26,
- 0x6e, 0xc8, 0xf7, 0x6e, 0x6e, 0x63, 0xed, 0x1b, 0xa4, 0x1e, 0xb0, 0x33,
- 0xb1, 0x20, 0xf7, 0xea, 0x52, 0x12, 0xae, 0x21, 0xa9, 0x8f, 0xbc, 0x16};
-const uint8_t kTestVector5Spki[] = {
- 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
- 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81,
- 0x89, 0x02, 0x81, 0x81, 0x0d, 0x10, 0xf6, 0x61, 0xf2, 0x99, 0x40, 0xf5,
- 0xed, 0x39, 0xaa, 0x26, 0x09, 0x66, 0xde, 0xb4, 0x78, 0x43, 0x67, 0x9d,
- 0x2b, 0x6f, 0xb2, 0x5b, 0x3d, 0xe3, 0x70, 0xf3, 0xac, 0x7c, 0x19, 0x91,
- 0x63, 0x91, 0xfd, 0x25, 0xfb, 0x52, 0x7e, 0xbf, 0xa6, 0xa4, 0xb4, 0xdf,
- 0x45, 0xa1, 0x75, 0x9d, 0x99, 0x6c, 0x4b, 0xb4, 0xeb, 0xd1, 0x88, 0x28,
- 0xc4, 0x4f, 0xc5, 0x2d, 0x01, 0x91, 0x87, 0x17, 0x40, 0x52, 0x5f, 0x47,
- 0xa4, 0xb0, 0xcc, 0x8d, 0xa3, 0x25, 0xed, 0x8a, 0xa6, 0x76, 0xb0, 0xd0,
- 0xf6, 0x26, 0xe0, 0xa7, 0x7f, 0x07, 0x69, 0x21, 0x70, 0xac, 0xac, 0x80,
- 0x82, 0xf4, 0x2f, 0xaa, 0x7d, 0xc7, 0xcd, 0x12, 0x3e, 0x73, 0x0e, 0x31,
- 0xa8, 0x79, 0x85, 0x20, 0x4c, 0xab, 0xcb, 0xe6, 0x67, 0x0d, 0x43, 0xa2,
- 0xdd, 0x2b, 0x2d, 0xde, 0xf5, 0xe0, 0x53, 0x92, 0xfc, 0x21, 0x3b, 0xc5,
- 0x07, 0x02, 0x03, 0x01, 0x00, 0x01};
-// RSA-PSS test vectors, pss-vect.txt, Example 5.1
-const uint8_t kTestVector5Data[] = {
- 0x30, 0xc7, 0xd5, 0x57, 0x45, 0x8b, 0x43, 0x6d, 0xec, 0xfd, 0xc1, 0x4d,
- 0x06, 0xcb, 0x7b, 0x96, 0xb0, 0x67, 0x18, 0xc4, 0x8d, 0x7d, 0xe5, 0x74,
- 0x82, 0xa8, 0x68, 0xae, 0x7f, 0x06, 0x58, 0x70, 0xa6, 0x21, 0x65, 0x06,
- 0xd1, 0x1b, 0x77, 0x93, 0x23, 0xdf, 0xdf, 0x04, 0x6c, 0xf5, 0x77, 0x51,
- 0x29, 0x13, 0x4b, 0x4d, 0x56, 0x89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 0x11, 0xb2, 0x57, 0x52, 0x15, 0xda, 0x6c, 0x16, 0x15, 0x90, 0xc7,
- 0x45, 0xbe, 0x61, 0x24, 0x76, 0xee, 0x57, 0x8e, 0xd3, 0x84, 0xab, 0x33,
- 0xe3, 0xec, 0xe9, 0x74, 0x81, 0xa2, 0x52, 0xf5, 0xc7, 0x9a, 0x98, 0xb5,
- 0x53, 0x2a, 0xe0, 0x0c, 0xdd, 0x62, 0xf2, 0xec, 0xc0, 0xcd, 0x1b, 0xae,
- 0xfe, 0x80, 0xd8, 0x0b, 0x96, 0x21, 0x93, 0xec, 0x1d};
-
-// RSA-PSS test vectors, pss-vect.txt, Example 6: A 1029-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-const uint8_t kTestVector6Pkcs8[] = {
- 0x30, 0x82, 0x02, 0x79, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
- 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
- 0x02, 0x63, 0x30, 0x82, 0x02, 0x5f, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81,
- 0x16, 0x4c, 0xa3, 0x1c, 0xff, 0x60, 0x9f, 0x3a, 0x0e, 0x71, 0x01, 0xb0,
- 0x39, 0xf2, 0xe4, 0xfe, 0x6d, 0xd3, 0x75, 0x19, 0xab, 0x98, 0x59, 0x8d,
- 0x17, 0x9e, 0x17, 0x49, 0x96, 0x59, 0x80, 0x71, 0xf4, 0x7d, 0x3a, 0x04,
- 0x55, 0x91, 0x58, 0xd7, 0xbe, 0x37, 0x3c, 0xf1, 0xaa, 0x53, 0xf0, 0xaa,
- 0x6e, 0xf0, 0x90, 0x39, 0xe5, 0x67, 0x8c, 0x2a, 0x4c, 0x63, 0x90, 0x05,
- 0x14, 0xc8, 0xc4, 0xf8, 0xaa, 0xed, 0x5d, 0xe1, 0x2a, 0x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0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
- 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81,
- 0x89, 0x02, 0x81, 0x81, 0x16, 0x4c, 0xa3, 0x1c, 0xff, 0x60, 0x9f, 0x3a,
- 0x0e, 0x71, 0x01, 0xb0, 0x39, 0xf2, 0xe4, 0xfe, 0x6d, 0xd3, 0x75, 0x19,
- 0xab, 0x98, 0x59, 0x8d, 0x17, 0x9e, 0x17, 0x49, 0x96, 0x59, 0x80, 0x71,
- 0xf4, 0x7d, 0x3a, 0x04, 0x55, 0x91, 0x58, 0xd7, 0xbe, 0x37, 0x3c, 0xf1,
- 0xaa, 0x53, 0xf0, 0xaa, 0x6e, 0xf0, 0x90, 0x39, 0xe5, 0x67, 0x8c, 0x2a,
- 0x4c, 0x63, 0x90, 0x05, 0x14, 0xc8, 0xc4, 0xf8, 0xaa, 0xed, 0x5d, 0xe1,
- 0x2a, 0x5f, 0x10, 0xb0, 0x9c, 0x31, 0x1a, 0xf8, 0xc0, 0xff, 0xb5, 0xb7,
- 0xa2, 0x97, 0xf2, 0xef, 0xc6, 0x3b, 0x8d, 0x6b, 0x05, 0x10, 0x93, 0x1f,
- 0x0b, 0x98, 0xe4, 0x8b, 0xf5, 0xfc, 0x6e, 0xc4, 0xe7, 0xb8, 0xdb, 0x1f,
- 0xfa, 0xeb, 0x08, 0xc3, 0x8e, 0x02, 0xad, 0xb8, 0xf0, 0x3a, 0x48, 0x22,
- 0x9c, 0x99, 0xe9, 0x69, 0x43, 0x1f, 0x61, 0xcb, 0x8c, 0x4d, 0xc6, 0x98,
- 0xd1, 0x02, 0x03, 0x01, 0x00, 0x01};
-// RSA-PSS test vectors, pss-vect.txt, Example 6.1
-const uint8_t kTestVector6Data[] = {
- 0x0a, 0x20, 0xb7, 0x74, 0xad, 0xdc, 0x2f, 0xa5, 0x12, 0x45, 0xed,
- 0x7c, 0xb9, 0xda, 0x60, 0x9e, 0x50, 0xca, 0xc6, 0x63, 0x6a, 0x52,
- 0x54, 0x3f, 0x97, 0x45, 0x8e, 0xed, 0x73, 0x40, 0xf8, 0xd5, 0x3f,
- 0xfc, 0x64, 0x91, 0x8f, 0x94, 0x90, 0x78, 0xee, 0x03, 0xef, 0x60,
- 0xd4, 0x2b, 0x5f, 0xec, 0x24, 0x60, 0x50, 0xbd, 0x55, 0x05, 0xcd,
- 0x8c, 0xb5, 0x97, 0xba, 0xd3, 0xc4, 0xe7, 0x13, 0xb0, 0xef, 0x30,
- 0x64, 0x4e, 0x76, 0xad, 0xab, 0xb0, 0xde, 0x01, 0xa1, 0x56, 0x1e,
- 0xfb, 0x25, 0x51, 0x58, 0xc7, 0x4f, 0xc8, 0x01, 0xe6, 0xe9, 0x19,
- 0xe5, 0x81, 0xb4, 0x6f, 0x0f, 0x0d, 0xdd, 0x08, 0xe4, 0xf3, 0x4c,
- 0x78, 0x10, 0xb5, 0xed, 0x83, 0x18, 0xf9, 0x1d, 0x7c, 0x8c};
-const uint8_t kTestVector6Sig[] = {
- 0x04, 0xc0, 0xcf, 0xac, 0xec, 0x04, 0xe5, 0xba, 0xdb, 0xec, 0xe1, 0x59,
- 0xa5, 0xa1, 0x10, 0x3f, 0x69, 0xb3, 0xf3, 0x2b, 0xa5, 0x93, 0xcb, 0x4c,
- 0xc4, 0xb1, 0xb7, 0xab, 0x45, 0x59, 0x16, 0xa9, 0x6a, 0x27, 0xcd, 0x26,
- 0x78, 0xea, 0x0f, 0x46, 0xba, 0x37, 0xf7, 0xfc, 0x9c, 0x86, 0x32, 0x5f,
- 0x29, 0x73, 0x3b, 0x38, 0x9f, 0x1d, 0x97, 0xf4, 0x3e, 0x72, 0x01, 0xc0,
- 0xf3, 0x48, 0xfc, 0x45, 0xfe, 0x42, 0x89, 0x23, 0x35, 0x36, 0x2e, 0xee,
- 0x01, 0x8b, 0x5b, 0x16, 0x1f, 0x2f, 0x93, 0x93, 0x03, 0x12, 0x25, 0xc7,
- 0x13, 0x01, 0x2a, 0x57, 0x6b, 0xc8, 0x8e, 0x23, 0x05, 0x24, 0x89, 0x86,
- 0x8d, 0x90, 0x10, 0xcb, 0xf0, 0x33, 0xec, 0xc5, 0x68, 0xe8, 0xbc, 0x15,
- 0x2b, 0xdc, 0x59, 0xd5, 0x60, 0xe4, 0x12, 0x91, 0x91, 0x5d, 0x28, 0x56,
- 0x52, 0x08, 0xe2, 0x2a, 0xee, 0xc9, 0xef, 0x85, 0xd1};
-
-// RSA-PSS test vectors, pss-vect.txt, Example 7: A 1030-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-const uint8_t kTestVector7Pkcs8[] = {
- 0x30, 0x82, 0x02, 0x77, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
- 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
- 0x02, 0x61, 0x30, 0x82, 0x02, 0x5d, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81,
- 0x37, 0xc9, 0xda, 0x4a, 0x66, 0xc8, 0xc4, 0x08, 0xb8, 0xda, 0x27, 0xd0,
- 0xc9, 0xd7, 0x9f, 0x8c, 0xcb, 0x1e, 0xaf, 0xc1, 0xd2, 0xfe, 0x48, 0x74,
- 0x6d, 0x94, 0x0b, 0x7c, 0x4e, 0xf5, 0xde, 0xe1, 0x8a, 0xd1, 0x26, 0x47,
- 0xce, 0xfa, 0xa0, 0xc4, 0xb3, 0x18, 0x8b, 0x22, 0x1c, 0x51, 0x53, 0x86,
- 0x75, 0x9b, 0x93, 0xf0, 0x20, 0x24, 0xb2, 0x5a, 0xb9, 0x24, 0x2f, 0x83,
- 0x57, 0xd8, 0xf3, 0xfd, 0x49, 0x64, 0x0e, 0xe5, 0xe6, 0x43, 0xea, 0xf6,
- 0xc6, 0x4d, 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 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81,
- 0x89, 0x02, 0x81, 0x81, 0x37, 0xc9, 0xda, 0x4a, 0x66, 0xc8, 0xc4, 0x08,
- 0xb8, 0xda, 0x27, 0xd0, 0xc9, 0xd7, 0x9f, 0x8c, 0xcb, 0x1e, 0xaf, 0xc1,
- 0xd2, 0xfe, 0x48, 0x74, 0x6d, 0x94, 0x0b, 0x7c, 0x4e, 0xf5, 0xde, 0xe1,
- 0x8a, 0xd1, 0x26, 0x47, 0xce, 0xfa, 0xa0, 0xc4, 0xb3, 0x18, 0x8b, 0x22,
- 0x1c, 0x51, 0x53, 0x86, 0x75, 0x9b, 0x93, 0xf0, 0x20, 0x24, 0xb2, 0x5a,
- 0xb9, 0x24, 0x2f, 0x83, 0x57, 0xd8, 0xf3, 0xfd, 0x49, 0x64, 0x0e, 0xe5,
- 0xe6, 0x43, 0xea, 0xf6, 0xc6, 0x4d, 0xee, 0xfa, 0x70, 0x89, 0x72, 0x7c,
- 0x8f, 0xf0, 0x39, 0x93, 0x33, 0x39, 0x15, 0xc6, 0xef, 0x21, 0xbf, 0x59,
- 0x75, 0xb6, 0xe5, 0x0d, 0x11, 0x8b, 0x51, 0x00, 0x8e, 0xc3, 0x3e, 0x9f,
- 0x01, 0xa0, 0xa5, 0x45, 0xa1, 0x0a, 0x83, 0x6a, 0x43, 0xdd, 0xbc, 0xa9,
- 0xd8, 0xb5, 0xc5, 0xd3, 0x54, 0x80, 0x22, 0xd7, 0x06, 0x4e, 0xa2, 0x9a,
- 0xb3, 0x02, 0x03, 0x01, 0x00, 0x01};
-// RSA-PSS test vectors, pss-vect.txt, Example 7.1
-const uint8_t kTestVector7Data[] = {
- 0x9e, 0xad, 0x0e, 0x01, 0x94, 0x56, 0x40, 0x67, 0x4e, 0xb4, 0x1c, 0xad,
- 0x43, 0x5e, 0x23, 0x74, 0xea, 0xef, 0xa8, 0xad, 0x71, 0x97, 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- 0xc4, 0x79, 0x4b, 0x29, 0x4c, 0x60, 0x55, 0x58, 0x23};
-
-// RSA-PSS test vectors, pss-vect.txt, Example 8: A 1031-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-const uint8_t kTestVector8Pkcs8[] = {
- 0x30, 0x82, 0x02, 0x78, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
- 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
- 0x02, 0x62, 0x30, 0x82, 0x02, 0x5e, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81,
- 0x49, 0x53, 0x70, 0xa1, 0xfb, 0x18, 0x54, 0x3c, 0x16, 0xd3, 0x63, 0x1e,
- 0x31, 0x63, 0x25, 0x5d, 0xf6, 0x2b, 0xe6, 0xee, 0xe8, 0x90, 0xd5, 0xf2,
- 0x55, 0x09, 0xe4, 0xf7, 0x78, 0xa8, 0xea, 0x6f, 0xbb, 0xbc, 0xdf, 0x85,
- 0xdf, 0xf6, 0x4e, 0x0d, 0x97, 0x20, 0x03, 0xab, 0x36, 0x81, 0xfb, 0xba,
- 0x6d, 0xd4, 0x1f, 0xd5, 0x41, 0x82, 0x9b, 0x2e, 0x58, 0x2d, 0xe9, 0xf2,
- 0xa4, 0xa4, 0xe0, 0xa2, 0xd0, 0x90, 0x0b, 0xef, 0x47, 0x53, 0xdb, 0x3c,
- 0xee, 0x0e, 0xe0, 0x6c, 0x7d, 0xfa, 0xe8, 0xb1, 0xd5, 0x3b, 0x59, 0x53,
- 0x21, 0x8f, 0x9c, 0xce, 0xea, 0x69, 0x5b, 0x08, 0x66, 0x8e, 0xde, 0xaa,
- 0xdc, 0xed, 0x94, 0x63, 0xb1, 0xd7, 0x90, 0xd5, 0xeb, 0xf2, 0x7e, 0x91,
- 0x15, 0xb4, 0x6c, 0xad, 0x4d, 0x9a, 0x2b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xaa, 0x16, 0x5c, 0x87, 0xb6, 0x82,
- 0xec, 0x14, 0x0b, 0x8e, 0xd3, 0xb5, 0x0b, 0x24, 0x59, 0x4b, 0x7a, 0x3b,
- 0x2c, 0x22, 0x0b, 0x36, 0x69, 0xbb, 0x81, 0x9f, 0x98, 0x4f, 0x55, 0x31,
- 0x0a, 0x1a, 0xe7, 0x82, 0x36, 0x51, 0xd4, 0xa0, 0x2e, 0x99, 0x44, 0x79,
- 0x72, 0x59, 0x51, 0x39, 0x36, 0x34, 0x34, 0xe5, 0xe3, 0x0a, 0x7e, 0x7d,
- 0x24, 0x15, 0x51, 0xe1, 0xb9, 0x02, 0x41, 0x07, 0xd3, 0xe4, 0x7b, 0xf6,
- 0x86, 0x60, 0x0b, 0x11, 0xac, 0x28, 0x3c, 0xe8, 0x8d, 0xbb, 0x3f, 0x60,
- 0x51, 0xe8, 0xef, 0xd0, 0x46, 0x80, 0xe4, 0x4c, 0x17, 0x1e, 0xf5, 0x31,
- 0xb8, 0x0b, 0x2b, 0x7c, 0x39, 0xfc, 0x76, 0x63, 0x20, 0xe2, 0xcf, 0x15,
- 0xd8, 0xd9, 0x98, 0x20, 0xe9, 0x6f, 0xf3, 0x0d, 0xc6, 0x96, 0x91, 0x83,
- 0x9c, 0x4b, 0x40, 0xd7, 0xb0, 0x6e, 0x45, 0x30, 0x7d, 0xc9, 0x1f, 0x3f};
-const uint8_t kTestVector8Spki[] = {
- 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
- 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81,
- 0x89, 0x02, 0x81, 0x81, 0x49, 0x53, 0x70, 0xa1, 0xfb, 0x18, 0x54, 0x3c,
- 0x16, 0xd3, 0x63, 0x1e, 0x31, 0x63, 0x25, 0x5d, 0xf6, 0x2b, 0xe6, 0xee,
- 0xe8, 0x90, 0xd5, 0xf2, 0x55, 0x09, 0xe4, 0xf7, 0x78, 0xa8, 0xea, 0x6f,
- 0xbb, 0xbc, 0xdf, 0x85, 0xdf, 0xf6, 0x4e, 0x0d, 0x97, 0x20, 0x03, 0xab,
- 0x36, 0x81, 0xfb, 0xba, 0x6d, 0xd4, 0x1f, 0xd5, 0x41, 0x82, 0x9b, 0x2e,
- 0x58, 0x2d, 0xe9, 0xf2, 0xa4, 0xa4, 0xe0, 0xa2, 0xd0, 0x90, 0x0b, 0xef,
- 0x47, 0x53, 0xdb, 0x3c, 0xee, 0x0e, 0xe0, 0x6c, 0x7d, 0xfa, 0xe8, 0xb1,
- 0xd5, 0x3b, 0x59, 0x53, 0x21, 0x8f, 0x9c, 0xce, 0xea, 0x69, 0x5b, 0x08,
- 0x66, 0x8e, 0xde, 0xaa, 0xdc, 0xed, 0x94, 0x63, 0xb1, 0xd7, 0x90, 0xd5,
- 0xeb, 0xf2, 0x7e, 0x91, 0x15, 0xb4, 0x6c, 0xad, 0x4d, 0x9a, 0x2b, 0x8e,
- 0xfa, 0xb0, 0x56, 0x1b, 0x08, 0x10, 0x34, 0x47, 0x39, 0xad, 0xa0, 0x73,
- 0x3f, 0x02, 0x03, 0x01, 0x00, 0x01};
-// RSA-PSS test vectors, pss-vect.txt, Example 8.1
-const uint8_t kTestVector8Data[] = {
- 0x81, 0x33, 0x2f, 0x4b, 0xe6, 0x29, 0x48, 0x41, 0x5e, 0xa1, 0xd8, 0x99,
- 0x79, 0x2e, 0xea, 0xcf, 0x6c, 0x6e, 0x1d, 0xb1, 0xda, 0x8b, 0xe1, 0x3b,
- 0x5c, 0xea, 0x41, 0xdb, 0x2f, 0xed, 0x46, 0x70, 0x92, 0xe1, 0xff, 0x39,
- 0x89, 0x14, 0xc7, 0x14, 0x25, 0x97, 0x75, 0xf5, 0x95, 0xf8, 0x54, 0x7f,
- 0x73, 0x56, 0x92, 0xa5, 0x75, 0xe6, 0x92, 0x3a, 0xf7, 0x8f, 0x22, 0xc6,
- 0x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23, 0x10, 0x6d, 0x78, 0x45, 0xaa, 0xf0, 0x11,
- 0x25, 0xb6, 0x98, 0xe7, 0xa4, 0xdf, 0xe9, 0x2d, 0x39, 0x67, 0xbb, 0x00,
- 0xc4, 0xd0, 0xd3, 0x5b, 0xa3, 0x55, 0x2a, 0xb9, 0xa8, 0xb3, 0xee, 0xf0,
- 0x7c, 0x7f, 0xec, 0xdb, 0xc5, 0x42, 0x4a, 0xc4, 0xdb, 0x1e, 0x20, 0xcb,
- 0x37, 0xd0, 0xb2, 0x74, 0x47, 0x69, 0x94, 0x0e, 0xa9, 0x07, 0xe1, 0x7f,
- 0xbb, 0xca, 0x67, 0x3b, 0x20, 0x52, 0x23, 0x80, 0xc5};
-
-// RSA-PSS test vectors, pss-vect.txt, Example 9: A 1536-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-const uint8_t kTestVector9Pkcs8[] = {
- 0x30, 0x82, 0x03, 0x92, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
- 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
- 0x03, 0x7c, 0x30, 0x82, 0x03, 0x78, 0x02, 0x01, 0x00, 0x02, 0x81, 0xc0,
- 0xe6, 0xbd, 0x69, 0x2a, 0xc9, 0x66, 0x45, 0x79, 0x04, 0x03, 0xfd, 0xd0,
- 0xf5, 0xbe, 0xb8, 0xb9, 0xbf, 0x92, 0xed, 0x10, 0x00, 0x7f, 0xc3, 0x65,
- 0x04, 0x64, 0x19, 0xdd, 0x06, 0xc0, 0x5c, 0x5b, 0x5b, 0x2f, 0x48, 0xec,
- 0xf9, 0x89, 0xe4, 0xce, 0x26, 0x91, 0x09, 0x97, 0x9c, 0xbb, 0x40, 0xb4,
- 0xa0, 0xad, 0x24, 0xd2, 0x24, 0x83, 0xd1, 0xee, 0x31, 0x5a, 0xd4, 0xcc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x42, 0xc5, 0xfd, 0xb6,
- 0x1a, 0xec, 0x26, 0x69, 0x02, 0x60, 0x77, 0xb9, 0xd1, 0x13, 0x7b, 0x50,
- 0x40, 0x4a, 0x98, 0x27, 0x29, 0x31, 0x6e, 0xfa, 0xfc, 0x7d, 0xfe, 0x66,
- 0xd3, 0x4e, 0x5a, 0x18, 0x26, 0x00, 0xd5, 0xf3, 0x0a, 0x0a, 0x85, 0x12,
- 0x05, 0x1c, 0x56, 0x0d, 0x08, 0x1d, 0x4d, 0x0a, 0x18, 0x35, 0xec, 0x3d,
- 0x25, 0xa6, 0x0f, 0x4e, 0x4d, 0x6a, 0xa9, 0x48, 0xb2, 0xbf, 0x3d, 0xbb,
- 0x5b, 0x12, 0x4c, 0xbb, 0xc3, 0x48, 0x92, 0x55, 0xa3, 0xa9, 0x48, 0x37,
- 0x2f, 0x69, 0x78, 0x49, 0x67, 0x45, 0xf9, 0x43, 0xe1, 0xdb, 0x4f, 0x18,
- 0x38, 0x2c, 0xea, 0xa5, 0x05, 0xdf, 0xc6, 0x57, 0x57, 0xbb, 0x3f, 0x85,
- 0x7a, 0x58, 0xdc, 0xe5, 0x21, 0x56};
-const uint8_t kTestVector9Spki[] = {
- 0x30, 0x81, 0xdf, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
- 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0xcd, 0x00, 0x30, 0x81,
- 0xc9, 0x02, 0x81, 0xc1, 0x00, 0xe6, 0xbd, 0x69, 0x2a, 0xc9, 0x66, 0x45,
- 0x79, 0x04, 0x03, 0xfd, 0xd0, 0xf5, 0xbe, 0xb8, 0xb9, 0xbf, 0x92, 0xed,
- 0x10, 0x00, 0x7f, 0xc3, 0x65, 0x04, 0x64, 0x19, 0xdd, 0x06, 0xc0, 0x5c,
- 0x5b, 0x5b, 0x2f, 0x48, 0xec, 0xf9, 0x89, 0xe4, 0xce, 0x26, 0x91, 0x09,
- 0x97, 0x9c, 0xbb, 0x40, 0xb4, 0xa0, 0xad, 0x24, 0xd2, 0x24, 0x83, 0xd1,
- 0xee, 0x31, 0x5a, 0xd4, 0xcc, 0xb1, 0x53, 0x42, 0x68, 0x35, 0x26, 0x91,
- 0xc5, 0x24, 0xf6, 0xdd, 0x8e, 0x6c, 0x29, 0xd2, 0x24, 0xcf, 0x24, 0x69,
- 0x73, 0xae, 0xc8, 0x6c, 0x5b, 0xf6, 0xb1, 0x40, 0x1a, 0x85, 0x0d, 0x1b,
- 0x9a, 0xd1, 0xbb, 0x8c, 0xbc, 0xec, 0x47, 0xb0, 0x6f, 0x0f, 0x8c, 0x7f,
- 0x45, 0xd3, 0xfc, 0x8f, 0x31, 0x92, 0x99, 0xc5, 0x43, 0x3d, 0xdb, 0xc2,
- 0xb3, 0x05, 0x3b, 0x47, 0xde, 0xd2, 0xec, 0xd4, 0xa4, 0xca, 0xef, 0xd6,
- 0x14, 0x83, 0x3d, 0xc8, 0xbb, 0x62, 0x2f, 0x31, 0x7e, 0xd0, 0x76, 0xb8,
- 0x05, 0x7f, 0xe8, 0xde, 0x3f, 0x84, 0x48, 0x0a, 0xd5, 0xe8, 0x3e, 0x4a,
- 0x61, 0x90, 0x4a, 0x4f, 0x24, 0x8f, 0xb3, 0x97, 0x02, 0x73, 0x57, 0xe1,
- 0xd3, 0x0e, 0x46, 0x31, 0x39, 0x81, 0x5c, 0x6f, 0xd4, 0xfd, 0x5a, 0xc5,
- 0xb8, 0x17, 0x2a, 0x45, 0x23, 0x0e, 0xcb, 0x63, 0x18, 0xa0, 0x4f, 0x14,
- 0x55, 0xd8, 0x4e, 0x5a, 0x8b, 0x02, 0x03, 0x01, 0x00, 0x01};
-// RSA-PSS test vectors, pss-vect.txt, Example 9.1
-const uint8_t kTestVector9Data[] = {
- 0xa8, 0x8e, 0x26, 0x58, 0x55, 0xe9, 0xd7, 0xca, 0x36, 0xc6, 0x87, 0x95,
- 0xf0, 0xb3, 0x1b, 0x59,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f2, 0x4b, 0xbd, 0x9f, 0xe9, 0x1b, 0x59,
- 0xca, 0xf1, 0x23, 0x5b, 0x2a, 0x93, 0xff, 0x81, 0xfc, 0x40, 0x3a, 0xdd,
- 0xf4, 0xeb, 0xde, 0xa8, 0x49, 0x34, 0xa9, 0xcd, 0xaf, 0x8e, 0x1a, 0x9e};
-
-// RSA-PSS test vectors, pss-vect.txt, Example 10: A 2048-bit RSA Key Pair
-// <ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip>
-const uint8_t kTestVector10Pkcs8[] = {
- 0x30, 0x82, 0x04, 0xb9, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
- 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
- 0x04, 0xa3, 0x30, 0x82, 0x04, 0x9f, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01,
- 0x00, 0xa5, 0xdd, 0x86, 0x7a, 0xc4, 0xcb, 0x02, 0xf9, 0x0b, 0x94, 0x57,
- 0xd4, 0x8c, 0x14, 0xa7, 0x70, 0xef, 0x99, 0x1c, 0x56, 0xc3, 0x9c, 0x0e,
- 0xc6, 0x5f, 0xd1, 0x1a, 0xfa, 0x89, 0x37, 0xce, 0xa5, 0x7b, 0x9b, 0xe7,
- 0xac, 0x73, 0xb4, 0x5c, 0x00, 0x17, 0x61, 0x5b, 0x82, 0xd6, 0x22, 0xe3,
- 0x18, 0x75, 0x3b, 0x60, 0x27, 0xc0, 0xfd, 0x15, 0x7b, 0xe1, 0x2f, 0x80,
- 0x90, 0xfe, 0xe2, 0xa7, 0xad, 0xcd, 0x0e, 0xef, 0x75, 0x9f, 0x88, 0xba,
- 0x49, 0x97, 0xc7, 0xa4, 0x2d, 0x58, 0xc9, 0xaa, 0x12, 0xcb, 0x99, 0xae,
- 0x00, 0x1f, 0xe5, 0x21, 0xc1, 0x3b, 0xb5, 0x43, 0x14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4b, 0xaa, 0xc9, 0x53, 0x0b, 0x4c, 0xe7, 0x08, 0xfc, 0x32,
- 0xb6};
-const uint8_t kTestVector10Spki[] = {
- 0x30, 0x82, 0x01, 0x21, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
- 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0e, 0x00,
- 0x30, 0x82, 0x01, 0x09, 0x02, 0x82, 0x01, 0x00, 0xa5, 0xdd, 0x86, 0x7a,
- 0xc4, 0xcb, 0x02, 0xf9, 0x0b, 0x94, 0x57, 0xd4, 0x8c, 0x14, 0xa7, 0x70,
- 0xef, 0x99, 0x1c, 0x56, 0xc3, 0x9c, 0x0e, 0xc6, 0x5f, 0xd1, 0x1a, 0xfa,
- 0x89, 0x37, 0xce, 0xa5, 0x7b, 0x9b, 0xe7, 0xac, 0x73, 0xb4, 0x5c, 0x00,
- 0x17, 0x61, 0x5b, 0x82, 0xd6, 0x22, 0xe3, 0x18, 0x75, 0x3b, 0x60, 0x27,
- 0xc0, 0xfd, 0x15, 0x7b, 0xe1, 0x2f, 0x80, 0x90, 0xfe, 0xe2, 0xa7, 0xad,
- 0xcd, 0x0e, 0xef, 0x75, 0x9f, 0x88, 0xba, 0x49, 0x97, 0xc7, 0xa4, 0x2d,
- 0x58, 0xc9, 0xaa, 0x12, 0xcb, 0x99, 0xae, 0x00, 0x1f, 0xe5, 0x21, 0xc1,
- 0x3b, 0xb5, 0x43, 0x14, 0x45, 0xa8, 0xd5, 0xae, 0x4f, 0x5e, 0x4c, 0x7e,
- 0x94, 0x8a, 0xc2, 0x27, 0xd3, 0x60, 0x40, 0x71, 0xf2, 0x0e, 0x57, 0x7e,
- 0x90, 0x5f, 0xbe, 0xb1, 0x5d, 0xfa, 0xf0, 0x6d, 0x1d, 0xe5, 0xae, 0x62,
- 0x53, 0xd6, 0x3a, 0x6a, 0x21, 0x20, 0xb3, 0x1a, 0x5d, 0xa5, 0xda, 0xbc,
- 0x95, 0x50, 0x60, 0x0e, 0x20, 0xf2, 0x7d, 0x37, 0x39, 0xe2, 0x62, 0x79,
- 0x25, 0xfe, 0xa3, 0xcc, 0x50, 0x9f, 0x21, 0xdf, 0xf0, 0x4e, 0x6e, 0xea,
- 0x45, 0x49, 0xc5, 0x40, 0xd6, 0x80, 0x9f, 0xf9, 0x30, 0x7e, 0xed, 0xe9,
- 0x1f, 0xff, 0x58, 0x73, 0x3d, 0x83, 0x85, 0xa2, 0x37, 0xd6, 0xd3, 0x70,
- 0x5a, 0x33, 0xe3, 0x91, 0x90, 0x09, 0x92, 0x07, 0x0d, 0xf7, 0xad, 0xf1,
- 0x35, 0x7c, 0xf7, 0xe3, 0x70, 0x0c, 0xe3, 0x66, 0x7d, 0xe8, 0x3f, 0x17,
- 0xb8, 0xdf, 0x17, 0x78, 0xdb, 0x38, 0x1d, 0xce, 0x09, 0xcb, 0x4a, 0xd0,
- 0x58, 0xa5, 0x11, 0x00, 0x1a, 0x73, 0x81, 0x98, 0xee, 0x27, 0xcf, 0x55,
- 0xa1, 0x3b, 0x75, 0x45, 0x39, 0x90, 0x65, 0x82, 0xec, 0x8b, 0x17, 0x4b,
- 0xd5, 0x8d, 0x5d, 0x1f, 0x3d, 0x76, 0x7c, 0x61, 0x37, 0x21, 0xae, 0x05,
- 0x02, 0x03, 0x01, 0x00, 0x01};
-// RSA-PSS test vectors, pss-vect.txt, Example 10.1
-const uint8_t kTestVector10Data[] = {
- 0x88, 0x31, 0x77, 0xe5, 0x12, 0x6b, 0x9b, 0xe2, 0xd9, 0xa9,
- 0x68, 0x03, 0x27, 0xd5, 0x37, 0x0c, 0x6f, 0x26, 0x86, 0x1f,
- 0x58, 0x20, 0xc4, 0x3d, 0xa6, 0x7a, 0x3a, 0xd6, 0x09};
-const uint8_t kTestVector10Sig[] = {
- 0x82, 0xc2, 0xb1, 0x60, 0x09, 0x3b, 0x8a, 0xa3, 0xc0, 0xf7, 0x52, 0x2b,
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 0xe2, 0x5b, 0xbd, 0x96, 0x40, 0x8b, 0xa3, 0xb4, 0x3c, 0xc4, 0x86,
- 0x18, 0x4d, 0xd1, 0xc8, 0xe6, 0x25, 0x53, 0xfa, 0x1a, 0xf4, 0x04, 0x0f,
- 0x60, 0x66, 0x3d, 0xe7, 0xf5, 0xe4, 0x9c, 0x04, 0x38, 0x8e, 0x25, 0x7f,
- 0x1c, 0xe8, 0x9c, 0x95, 0xda, 0xb4, 0x8a, 0x31, 0x5d, 0x9b, 0x66, 0xb1,
- 0xb7, 0x62, 0x82, 0x33, 0x87, 0x6f, 0xf2, 0x38, 0x52, 0x30, 0xd0, 0x70,
- 0xd0, 0x7e, 0x16, 0x66};
-
-} // namespace nss_test
deleted file mode 100644
--- a/security/nss/gtests/pk11_gtest/pk11_signature_test.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <memory>
-#include "nss.h"
-#include "pk11pub.h"
-#include "sechash.h"
-
-#include "gtest/gtest.h"
-#include "scoped_ptrs.h"
-
-namespace nss_test {
-
-static unsigned char* toUcharPtr(const uint8_t* v) {
- return const_cast<unsigned char*>(static_cast<const unsigned char*>(v));
-}
-
-class Pk11SignatureTest : public ::testing::Test {
- protected:
- virtual CK_MECHANISM_TYPE mechanism() = 0;
- virtual SECItem* parameters() = 0;
- virtual SECOidTag hashOID() = 0;
-
- ScopedSECKEYPrivateKey ImportPrivateKey(const uint8_t* pkcs8,
- size_t pkcs8_len) {
- ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
- if (!slot) {
- return nullptr;
- }
-
- SECItem pkcs8Item = {siBuffer, toUcharPtr(pkcs8),
- static_cast<unsigned int>(pkcs8_len)};
-
- SECKEYPrivateKey* key = nullptr;
- SECStatus rv = PK11_ImportDERPrivateKeyInfoAndReturnKey(
- slot.get(), &pkcs8Item, nullptr, nullptr, false, false, KU_ALL, &key,
- nullptr);
-
- if (rv != SECSuccess) {
- return nullptr;
- }
-
- return ScopedSECKEYPrivateKey(key);
- }
-
- ScopedSECKEYPublicKey ImportPublicKey(const uint8_t* spki, size_t spki_len) {
- SECItem spkiItem = {siBuffer, toUcharPtr(spki),
- static_cast<unsigned int>(spki_len)};
-
- ScopedCERTSubjectPublicKeyInfo certSpki(
- SECKEY_DecodeDERSubjectPublicKeyInfo(&spkiItem));
-
- return ScopedSECKEYPublicKey(SECKEY_ExtractPublicKey(certSpki.get()));
- }
-
- ScopedSECItem ComputeHash(const uint8_t* data, size_t len) {
- unsigned int hLen = HASH_ResultLenByOidTag(hashOID());
- ScopedSECItem hash(SECITEM_AllocItem(nullptr, nullptr, hLen));
- if (!hash) {
- return nullptr;
- }
-
- SECStatus rv = PK11_HashBuf(hashOID(), hash->data, data, len);
- if (rv != SECSuccess) {
- return nullptr;
- }
-
- return hash;
- }
-
- ScopedSECItem SignHashedData(ScopedSECKEYPrivateKey& privKey,
- ScopedSECItem& hash) {
- unsigned int sLen = PK11_SignatureLen(privKey.get());
- ScopedSECItem sig(SECITEM_AllocItem(nullptr, nullptr, sLen));
- if (!sig) {
- return nullptr;
- }
-
- SECStatus rv = PK11_SignWithMechanism(privKey.get(), mechanism(),
- parameters(), sig.get(), hash.get());
- if (rv != SECSuccess) {
- return nullptr;
- }
-
- return sig;
- }
-
- ScopedSECItem ImportPrivateKeyAndSignHashedData(const uint8_t* pkcs8,
- size_t pkcs8_len,
- const uint8_t* data,
- size_t data_len) {
- ScopedSECKEYPrivateKey privKey(ImportPrivateKey(pkcs8, pkcs8_len));
- if (!privKey) {
- return nullptr;
- }
-
- ScopedSECItem hash(ComputeHash(data, data_len));
- if (!hash) {
- return nullptr;
- }
-
- return ScopedSECItem(SignHashedData(privKey, hash));
- }
-
- void Verify(const uint8_t* spki, size_t spki_len, const uint8_t* data,
- size_t data_len, const uint8_t* sig, size_t sig_len) {
- ScopedSECKEYPublicKey pubKey(ImportPublicKey(spki, spki_len));
- ASSERT_TRUE(pubKey);
-
- ScopedSECItem hash(ComputeHash(data, data_len));
- ASSERT_TRUE(hash);
-
- SECItem sigItem = {siBuffer, toUcharPtr(sig),
- static_cast<unsigned int>(sig_len)};
-
- // Verify.
- SECStatus rv = PK11_VerifyWithMechanism(
- pubKey.get(), mechanism(), parameters(), &sigItem, hash.get(), nullptr);
- EXPECT_EQ(rv, SECSuccess);
- }
-
- void SignAndVerify(const uint8_t* pkcs8, size_t pkcs8_len,
- const uint8_t* spki, size_t spki_len, const uint8_t* data,
- size_t data_len) {
- ScopedSECItem sig(
- ImportPrivateKeyAndSignHashedData(pkcs8, pkcs8_len, data, data_len));
- ASSERT_TRUE(sig);
-
- Verify(spki, spki_len, data, data_len, sig->data, sig->len);
- }
-};
-
-#define SIG_TEST_VECTOR_VERIFY(spki, data, sig) \
- Verify(spki, sizeof(spki), data, sizeof(data), sig, sizeof(sig));
-
-#define SIG_TEST_VECTOR_SIGN_VERIFY(pkcs8, spki, data) \
- SignAndVerify(pkcs8, sizeof(pkcs8), spki, sizeof(spki), data, sizeof(data));
-
-} // namespace nss_test
--- a/security/nss/gtests/ssl_gtest/Makefile
+++ b/security/nss/gtests/ssl_gtest/Makefile
@@ -28,18 +28,21 @@ include $(CORE_DEPTH)/coreconf/config.mk
include ../common/gtest.mk
CFLAGS += -I$(CORE_DEPTH)/lib/ssl
ifdef NSS_SSL_ENABLE_ZLIB
include $(CORE_DEPTH)/coreconf/zlib.mk
endif
+ifndef NSS_ENABLE_TLS_1_3
+NSS_DISABLE_TLS_1_3=1
+endif
+
ifdef NSS_DISABLE_TLS_1_3
-NSS_DISABLE_TLS_1_3=1
# Run parameterized tests only, for which we can easily exclude TLS 1.3
CPPSRCS := $(filter-out $(shell grep -l '^TEST_F' $(CPPSRCS)), $(CPPSRCS))
CFLAGS += -DNSS_DISABLE_TLS_1_3
endif
#######################################################################
# (5) Execute "global" rules. (OPTIONAL) #
#######################################################################
--- a/security/nss/gtests/ssl_gtest/libssl_internals.c
+++ b/security/nss/gtests/ssl_gtest/libssl_internals.c
@@ -5,16 +5,18 @@
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/* This file contains functions for frobbing the internals of libssl */
#include "libssl_internals.h"
#include "nss.h"
#include "pk11pub.h"
#include "seccomon.h"
+#include "ssl.h"
+#include "sslimpl.h"
SECStatus SSLInt_IncrementClientHandshakeVersion(PRFileDesc *fd) {
sslSocket *ss = ssl_FindSocket(fd);
if (!ss) {
return SECFailure;
}
++ss->clientHelloVersion;
@@ -57,17 +59,20 @@ SECStatus SSLInt_UpdateSSLv2ClientRandom
return ssl3_UpdateHandshakeHashes(ss, msg, msg_len);
}
PRBool SSLInt_ExtensionNegotiated(PRFileDesc *fd, PRUint16 ext) {
sslSocket *ss = ssl_FindSocket(fd);
return (PRBool)(ss && ssl3_ExtensionNegotiated(ss, ext));
}
-void SSLInt_ClearSessionTicketKey() { ssl_ResetSessionTicketKeys(); }
+void SSLInt_ClearSessionTicketKey() {
+ ssl3_SessionTicketShutdown(NULL, NULL);
+ NSS_UnregisterShutdown(ssl3_SessionTicketShutdown, NULL);
+}
SECStatus SSLInt_SetMTU(PRFileDesc *fd, PRUint16 mtu) {
sslSocket *ss = ssl_FindSocket(fd);
if (ss) {
ss->ssl3.mtu = mtu;
return SECSuccess;
}
return SECFailure;
@@ -201,17 +206,17 @@ SECStatus SSLInt_Set0RttAlpn(PRFileDesc
}
PRBool SSLInt_HasCertWithAuthType(PRFileDesc *fd, SSLAuthType authType) {
sslSocket *ss = ssl_FindSocket(fd);
if (!ss) {
return PR_FALSE;
}
- return (PRBool)(!!ssl_FindServerCert(ss, authType, NULL));
+ return (PRBool)(!!ssl_FindServerCertByAuthType(ss, authType));
}
PRBool SSLInt_SendAlert(PRFileDesc *fd, uint8_t level, uint8_t type) {
sslSocket *ss = ssl_FindSocket(fd);
if (!ss) {
return PR_FALSE;
}
@@ -304,50 +309,16 @@ SECStatus SSLInt_AdvanceWriteSeqByAWindo
SSLKEAType SSLInt_GetKEAType(SSLNamedGroup group) {
const sslNamedGroupDef *groupDef = ssl_LookupNamedGroup(group);
if (!groupDef) return ssl_kea_null;
return groupDef->keaType;
}
-SECStatus SSLInt_SetCipherSpecChangeFunc(PRFileDesc *fd,
- sslCipherSpecChangedFunc func,
- void *arg) {
- sslSocket *ss;
-
- ss = ssl_FindSocket(fd);
- if (!ss) {
- return SECFailure;
- }
-
- ss->ssl3.changedCipherSpecFunc = func;
- ss->ssl3.changedCipherSpecArg = arg;
-
- return SECSuccess;
-}
-
-static ssl3KeyMaterial *GetKeyingMaterial(PRBool isServer,
- ssl3CipherSpec *spec) {
- return isServer ? &spec->server : &spec->client;
-}
-
-PK11SymKey *SSLInt_CipherSpecToKey(PRBool isServer, ssl3CipherSpec *spec) {
- return GetKeyingMaterial(isServer, spec)->write_key;
-}
-
-SSLCipherAlgorithm SSLInt_CipherSpecToAlgorithm(PRBool isServer,
- ssl3CipherSpec *spec) {
- return spec->cipher_def->calg;
-}
-
-unsigned char *SSLInt_CipherSpecToIv(PRBool isServer, ssl3CipherSpec *spec) {
- return GetKeyingMaterial(isServer, spec)->write_iv;
-}
-
SECStatus SSLInt_EnableShortHeaders(PRFileDesc *fd) {
sslSocket *ss;
ss = ssl_FindSocket(fd);
if (!ss) {
return SECFailure;
}
--- a/security/nss/gtests/ssl_gtest/libssl_internals.h
+++ b/security/nss/gtests/ssl_gtest/libssl_internals.h
@@ -6,18 +6,16 @@
#ifndef libssl_internals_h_
#define libssl_internals_h_
#include <stdint.h>
#include "prio.h"
#include "seccomon.h"
-#include "ssl.h"
-#include "sslimpl.h"
#include "sslt.h"
SECStatus SSLInt_IncrementClientHandshakeVersion(PRFileDesc *fd);
SECStatus SSLInt_UpdateSSLv2ClientRandom(PRFileDesc *fd, uint8_t *rnd,
size_t rnd_len, uint8_t *msg,
size_t msg_len);
@@ -34,20 +32,12 @@ PRBool SSLInt_DamageEarlyTrafficSecret(P
SECStatus SSLInt_Set0RttAlpn(PRFileDesc *fd, PRUint8 *data, unsigned int len);
PRBool SSLInt_HasCertWithAuthType(PRFileDesc *fd, SSLAuthType authType);
PRBool SSLInt_SendAlert(PRFileDesc *fd, uint8_t level, uint8_t type);
PRBool SSLInt_SendNewSessionTicket(PRFileDesc *fd);
SECStatus SSLInt_AdvanceWriteSeqNum(PRFileDesc *fd, PRUint64 to);
SECStatus SSLInt_AdvanceReadSeqNum(PRFileDesc *fd, PRUint64 to);
SECStatus SSLInt_AdvanceWriteSeqByAWindow(PRFileDesc *fd, PRInt32 extra);
SSLKEAType SSLInt_GetKEAType(SSLNamedGroup group);
-
-SECStatus SSLInt_SetCipherSpecChangeFunc(PRFileDesc *fd,
- sslCipherSpecChangedFunc func,
- void *arg);
-PK11SymKey *SSLInt_CipherSpecToKey(PRBool isServer, ssl3CipherSpec *spec);
-SSLCipherAlgorithm SSLInt_CipherSpecToAlgorithm(PRBool isServer,
- ssl3CipherSpec *spec);
-unsigned char *SSLInt_CipherSpecToIv(PRBool isServer, ssl3CipherSpec *spec);
SECStatus SSLInt_EnableShortHeaders(PRFileDesc *fd);
SECStatus SSLInt_UsingShortHeaders(PRFileDesc *fd, PRBool *result);
#endif // ndef libssl_internals_h_
--- a/security/nss/gtests/ssl_gtest/manifest.mn
+++ b/security/nss/gtests/ssl_gtest/manifest.mn
@@ -19,38 +19,36 @@ CPPSRCS = \
ssl_ciphersuite_unittest.cc \
ssl_damage_unittest.cc \
ssl_dhe_unittest.cc \
ssl_drop_unittest.cc \
ssl_ecdh_unittest.cc \
ssl_ems_unittest.cc \
ssl_exporter_unittest.cc \
ssl_extension_unittest.cc \
- ssl_fragment_unittest.cc \
ssl_fuzz_unittest.cc \
- ssl_gather_unittest.cc \
ssl_gtest.cc \
ssl_hrr_unittest.cc \
ssl_loopback_unittest.cc \
ssl_record_unittest.cc \
ssl_resumption_unittest.cc \
ssl_skip_unittest.cc \
ssl_staticrsa_unittest.cc \
ssl_v2_client_hello_unittest.cc \
ssl_version_unittest.cc \
test_io.cc \
tls_agent.cc \
tls_connect.cc \
tls_hkdf_unittest.cc \
tls_filter.cc \
tls_parser.cc \
- tls_protect.cc \
$(NULL)
INCLUDES += -I$(CORE_DEPTH)/gtests/google_test/gtest/include \
-I$(CORE_DEPTH)/gtests/common
REQUIRES = nspr nss libdbm gtest
PROGRAM = ssl_gtest
-EXTRA_LIBS = $(DIST)/lib/$(LIB_PREFIX)gtest.$(LIB_SUFFIX)
+EXTRA_LIBS = $(DIST)/lib/$(LIB_PREFIX)gtest.$(LIB_SUFFIX) \
+ $(DIST)/lib/$(LIB_PREFIX)softokn.$(LIB_SUFFIX)
USE_STATIC_LIBS = 1
--- a/security/nss/gtests/ssl_gtest/ssl_0rtt_unittest.cc
+++ b/security/nss/gtests/ssl_gtest/ssl_0rtt_unittest.cc
@@ -195,87 +195,9 @@ TEST_P(TlsConnectTls13, TestTls13ZeroRtt
return false;
});
Handshake();
CheckConnected();
SendReceive();
CheckAlpn("b");
}
-// The client should abort the connection when sending a 0-rtt handshake but
-// the servers responds with a TLS 1.2 ServerHello. (no app data sent)
-TEST_P(TlsConnectTls13, TestTls13ZeroRttDowngrade) {
- ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET);
- server_->Set0RttEnabled(true); // set ticket_allow_early_data
- Connect();
-
- SendReceive(); // Need to read so that we absorb the session tickets.
- CheckKeys();
-
- Reset();
- ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET);
- client_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_2,
- SSL_LIBRARY_VERSION_TLS_1_3);
- server_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_2,
- SSL_LIBRARY_VERSION_TLS_1_2);
- client_->StartConnect();
- server_->StartConnect();
-
- // We will send the early data xtn without sending actual early data. Thus
- // a 1.2 server shouldn't fail until the client sends an alert because the
- // client sends end_of_early_data only after reading the server's flight.
- client_->Set0RttEnabled(true);
-
- client_->Handshake();
- server_->Handshake();
- ASSERT_TRUE_WAIT(
- (client_->error_code() == SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA), 2000);
-
- // DTLS will timeout as we bump the epoch when installing the early app data
- // cipher suite. Thus the encrypted alert will be ignored.
- if (mode_ == STREAM) {
- // The client sends an encrypted alert message.
- ASSERT_TRUE_WAIT(
- (server_->error_code() == SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA),
- 2000);
- }
-}
-
-// The client should abort the connection when sending a 0-rtt handshake but
-// the servers responds with a TLS 1.2 ServerHello. (with app data)
-TEST_P(TlsConnectTls13, TestTls13ZeroRttDowngradeEarlyData) {
- ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET);
- server_->Set0RttEnabled(true); // set ticket_allow_early_data
- Connect();
-
- SendReceive(); // Need to read so that we absorb the session tickets.
- CheckKeys();
-
- Reset();
- ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET);
- client_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_2,
- SSL_LIBRARY_VERSION_TLS_1_3);
- server_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_2,
- SSL_LIBRARY_VERSION_TLS_1_2);
- client_->StartConnect();
- server_->StartConnect();
-
- // Send the early data xtn in the CH, followed by early app data. The server
- // will fail right after sending its flight, when receiving the early data.
- client_->Set0RttEnabled(true);
- ZeroRttSendReceive(true, false);
-
- client_->Handshake();
- server_->Handshake();
- ASSERT_TRUE_WAIT(
- (client_->error_code() == SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA), 2000);
-
- // DTLS will timeout as we bump the epoch when installing the early app data
- // cipher suite. Thus the encrypted alert will be ignored.
- if (mode_ == STREAM) {
- // The server sends an alert when receiving the early app data record.
- ASSERT_TRUE_WAIT(
- (server_->error_code() == SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA),
- 2000);
- }
-}
-
} // namespace nss_test
--- a/security/nss/gtests/ssl_gtest/ssl_auth_unittest.cc
+++ b/security/nss/gtests/ssl_gtest/ssl_auth_unittest.cc
@@ -131,85 +131,16 @@ TEST_P(TlsConnectTls12, ClientAuthBigRsa
client_->SetPacketFilter(capture_cert_verify);
client_->SetupClientAuth();
server_->RequestClientAuth(true);
Connect();
CheckKeys();
CheckSigScheme(capture_cert_verify, 0, server_, ssl_sig_rsa_pss_sha256, 2048);
}
-class TlsZeroCertificateRequestSigAlgsFilter : public TlsHandshakeFilter {
- public:
- virtual PacketFilter::Action FilterHandshake(
- const TlsHandshakeFilter::HandshakeHeader& header,
- const DataBuffer& input, DataBuffer* output) {
- if (header.handshake_type() != kTlsHandshakeCertificateRequest) {
- return KEEP;
- }
-
- TlsParser parser(input);
- std::cerr << "Zeroing CertReq.supported_signature_algorithms" << std::endl;
-
- DataBuffer cert_types;
- if (!parser.ReadVariable(&cert_types, 1)) {
- ADD_FAILURE();
- return KEEP;
- }
-
- if (!parser.SkipVariable(2)) {
- ADD_FAILURE();
- return KEEP;
- }
-
- DataBuffer cas;
- if (!parser.ReadVariable(&cas, 2)) {
- ADD_FAILURE();
- return KEEP;
- }
-
- size_t idx = 0;
-
- // Write certificate types.
- idx = output->Write(idx, cert_types.len(), 1);
- idx = output->Write(idx, cert_types);
-
- // Write zero signature algorithms.
- idx = output->Write(idx, 0U, 2);
-
- // Write certificate authorities.
- idx = output->Write(idx, cas.len(), 2);
- idx = output->Write(idx, cas);
-
- return CHANGE;
- }
-};
-
-// Check that we fall back to SHA-1 when the server doesn't provide any
-// supported_signature_algorithms in the CertificateRequest message.
-TEST_P(TlsConnectTls12, ClientAuthNoSigAlgsFallback) {
- EnsureTlsSetup();
- auto filter = new TlsZeroCertificateRequestSigAlgsFilter();
- server_->SetPacketFilter(filter);
- auto capture_cert_verify =
- new TlsInspectorRecordHandshakeMessage(kTlsHandshakeCertificateVerify);
- client_->SetPacketFilter(capture_cert_verify);
- client_->SetupClientAuth();
- server_->RequestClientAuth(true);
-
- ConnectExpectFail();
-
- // We're expecting a bad signature here because we tampered with a handshake
- // message (CertReq). Previously, without the SHA-1 fallback, we would've
- // seen a malformed record alert.
- server_->CheckErrorCode(SEC_ERROR_BAD_SIGNATURE);
- client_->CheckErrorCode(SSL_ERROR_DECRYPT_ERROR_ALERT);
-
- CheckSigScheme(capture_cert_verify, 0, server_, ssl_sig_rsa_pkcs1_sha1, 1024);
-}
-
static const SSLSignatureScheme SignatureSchemeEcdsaSha384[] = {
ssl_sig_ecdsa_secp384r1_sha384};
static const SSLSignatureScheme SignatureSchemeEcdsaSha256[] = {
ssl_sig_ecdsa_secp256r1_sha256};
static const SSLSignatureScheme SignatureSchemeRsaSha384[] = {
ssl_sig_rsa_pkcs1_sha384};
static const SSLSignatureScheme SignatureSchemeRsaSha256[] = {
ssl_sig_rsa_pkcs1_sha256};
@@ -371,17 +302,17 @@ class BeforeFinished : public TlsRecordF
VoidFunction before_finished)
: client_(client),
server_(server),
before_ccs_(before_ccs),
before_finished_(before_finished),
state_(BEFORE_CCS) {}
protected:
- virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+ virtual PacketFilter::Action FilterRecord(const RecordHeader& header,
const DataBuffer& body,
DataBuffer* out) {
switch (state_) {
case BEFORE_CCS:
// Awaken when we see the CCS.
if (header.content_type() == kTlsChangeCipherSpecType) {
before_ccs_();
@@ -589,17 +520,17 @@ TEST_P(TlsConnectGenericPre13, AuthCompl
// This should allow the handshake to complete now.
EXPECT_EQ(SECSuccess, SSL_AuthCertificateComplete(client_->ssl_fd(), 0));
client_->Handshake(); // Transition to connected
EXPECT_EQ(TlsAgent::STATE_CONNECTED, client_->state());
EXPECT_EQ(TlsAgent::STATE_CONNECTED, server_->state());
// Remove this before closing or the close_notify alert will trigger it.
- client_->DeletePacketFilter();
+ client_->SetPacketFilter(nullptr);
}
// TLS 1.3 handles a delayed AuthComplete callback differently since the
// shape of the handshake is different.
TEST_P(TlsConnectTls13, AuthCompleteDelayed) {
client_->SetAuthCertificateCallback(AuthCompleteBlock);
server_->StartConnect();
@@ -610,17 +541,17 @@ TEST_P(TlsConnectTls13, AuthCompleteDela
EXPECT_EQ(TlsAgent::STATE_CONNECTING, server_->state());
// The client will send nothing until AuthCertificateComplete is called.
client_->SetPacketFilter(new EnforceNoActivity());
client_->Handshake();
EXPECT_EQ(TlsAgent::STATE_CONNECTING, client_->state());
// This should allow the handshake to complete now.
- client_->DeletePacketFilter();
+ client_->SetPacketFilter(nullptr);
EXPECT_EQ(SECSuccess, SSL_AuthCertificateComplete(client_->ssl_fd(), 0));
client_->Handshake(); // Send Finished
server_->Handshake(); // Transition to connected and send NewSessionTicket
EXPECT_EQ(TlsAgent::STATE_CONNECTED, client_->state());
EXPECT_EQ(TlsAgent::STATE_CONNECTED, server_->state());
}
static const SSLExtraServerCertData ServerCertDataRsaPkcs1Decrypt = {
--- a/security/nss/gtests/ssl_gtest/ssl_cert_ext_unittest.cc
+++ b/security/nss/gtests/ssl_gtest/ssl_cert_ext_unittest.cc
@@ -57,64 +57,55 @@ class SignedCertificateTimestampsExtract
std::unique_ptr<DataBuffer> auth_timestamps_;
std::unique_ptr<DataBuffer> handshake_timestamps_;
};
static const uint8_t kSctValue[] = {0x01, 0x23, 0x45, 0x67, 0x89};
static const SECItem kSctItem = {siBuffer, const_cast<uint8_t*>(kSctValue),
sizeof(kSctValue)};
static const DataBuffer kSctBuffer(kSctValue, sizeof(kSctValue));
-static const SSLExtraServerCertData kExtraSctData = {ssl_auth_null, nullptr,
- nullptr, &kSctItem};
// Test timestamps extraction during a successful handshake.
-TEST_P(TlsConnectGenericPre13, SignedCertificateTimestampsLegacy) {
+TEST_P(TlsConnectGeneric, SignedCertificateTimestampsHandshake) {
EnsureTlsSetup();
-
- // We have to use the legacy API consistently here for configuring certs.
- // Also, this doesn't work in TLS 1.3 because this only configures the SCT for
- // RSA decrypt and PKCS#1 signing, not PSS.
- ScopedCERTCertificate cert;
- ScopedSECKEYPrivateKey priv;
- ASSERT_TRUE(TlsAgent::LoadCertificate(TlsAgent::kServerRsa, &cert, &priv));
- EXPECT_EQ(SECSuccess, SSL_ConfigSecureServerWithCertChain(
- server_->ssl_fd(), cert.get(), nullptr, priv.get(),
- ssl_kea_rsa));
EXPECT_EQ(SECSuccess, SSL_SetSignedCertTimestamps(server_->ssl_fd(),
&kSctItem, ssl_kea_rsa));
EXPECT_EQ(SECSuccess,
SSL_OptionSet(client_->ssl_fd(), SSL_ENABLE_SIGNED_CERT_TIMESTAMPS,
PR_TRUE));
SignedCertificateTimestampsExtractor timestamps_extractor(client_);
Connect();
timestamps_extractor.assertTimestamps(kSctBuffer);
}
-TEST_P(TlsConnectGeneric, SignedCertificateTimestampsSuccess) {
+TEST_P(TlsConnectGeneric, SignedCertificateTimestampsConfig) {
+ static const SSLExtraServerCertData kExtraData = {ssl_auth_rsa_sign, nullptr,
+ nullptr, &kSctItem};
+
EnsureTlsSetup();
EXPECT_TRUE(
- server_->ConfigServerCert(TlsAgent::kServerRsa, true, &kExtraSctData));
+ server_->ConfigServerCert(TlsAgent::kServerRsa, true, &kExtraData));
EXPECT_EQ(SECSuccess,
SSL_OptionSet(client_->ssl_fd(), SSL_ENABLE_SIGNED_CERT_TIMESTAMPS,
PR_TRUE));
SignedCertificateTimestampsExtractor timestamps_extractor(client_);
Connect();
timestamps_extractor.assertTimestamps(kSctBuffer);
}
// Test SSL_PeerSignedCertTimestamps returning zero-length SECItem
// when the client / the server / both have not enabled the feature.
TEST_P(TlsConnectGeneric, SignedCertificateTimestampsInactiveClient) {
EnsureTlsSetup();
- EXPECT_TRUE(
- server_->ConfigServerCert(TlsAgent::kServerRsa, true, &kExtraSctData));
+ EXPECT_EQ(SECSuccess, SSL_SetSignedCertTimestamps(server_->ssl_fd(),
+ &kSctItem, ssl_kea_rsa));
SignedCertificateTimestampsExtractor timestamps_extractor(client_);
Connect();
timestamps_extractor.assertTimestamps(DataBuffer());
}
TEST_P(TlsConnectGeneric, SignedCertificateTimestampsInactiveServer) {
EnsureTlsSetup();
@@ -145,18 +136,18 @@ static SECStatus CheckNoOCSP(TlsAgent* a
static const uint8_t kOcspValue1[] = {1, 2, 3, 4, 5, 6};
static const uint8_t kOcspValue2[] = {7, 8, 9};
static const SECItem kOcspItems[] = {
{siBuffer, const_cast<uint8_t*>(kOcspValue1), sizeof(kOcspValue1)},
{siBuffer, const_cast<uint8_t*>(kOcspValue2), sizeof(kOcspValue2)}};
static const SECItemArray kOcspResponses = {const_cast<SECItem*>(kOcspItems),
PR_ARRAY_SIZE(kOcspItems)};
-const static SSLExtraServerCertData kOcspExtraData = {ssl_auth_null, nullptr,
- &kOcspResponses, nullptr};
+const static SSLExtraServerCertData kOcspExtraData = {
+ ssl_auth_rsa_sign, nullptr, &kOcspResponses, nullptr};
TEST_P(TlsConnectGeneric, NoOcsp) {
EnsureTlsSetup();
client_->SetAuthCertificateCallback(CheckNoOCSP);
Connect();
}
// The client doesn't get OCSP stapling unless it asks.
--- a/security/nss/gtests/ssl_gtest/ssl_ciphersuite_unittest.cc
+++ b/security/nss/gtests/ssl_gtest/ssl_ciphersuite_unittest.cc
@@ -123,32 +123,26 @@ class TlsCipherSuiteTestBase : public Tl
}
}
}
void ConnectAndCheckCipherSuite() {
Connect();
SendReceive();
- // Check that we used the right cipher suite, auth type and kea type.
+ // Check that we used the right cipher suite.
uint16_t actual;
- EXPECT_TRUE(client_->cipher_suite(&actual));
- EXPECT_EQ(cipher_suite_, actual);
- EXPECT_TRUE(server_->cipher_suite(&actual));
- EXPECT_EQ(cipher_suite_, actual);
+ EXPECT_TRUE(client_->cipher_suite(&actual) && actual == cipher_suite_);
+ EXPECT_TRUE(server_->cipher_suite(&actual) && actual == cipher_suite_);
SSLAuthType auth;
- EXPECT_TRUE(client_->auth_type(&auth));
- EXPECT_EQ(auth_type_, auth);
- EXPECT_TRUE(server_->auth_type(&auth));
- EXPECT_EQ(auth_type_, auth);
+ EXPECT_TRUE(client_->auth_type(&auth) && auth == auth_type_);
+ EXPECT_TRUE(server_->auth_type(&auth) && auth == auth_type_);
SSLKEAType kea;
- EXPECT_TRUE(client_->kea_type(&kea));
- EXPECT_EQ(kea_type_, kea);
- EXPECT_TRUE(server_->kea_type(&kea));
- EXPECT_EQ(kea_type_, kea);
+ EXPECT_TRUE(client_->kea_type(&kea) && kea == kea_type_);
+ EXPECT_TRUE(server_->kea_type(&kea) && kea == kea_type_);
}
// Get the expected limit on the number of records that can be sent for the
// cipher suite.
uint64_t record_limit() const {
switch (csinfo_.symCipher) {
case ssl_calg_rc4:
case ssl_calg_3des:
deleted file mode 100644
--- a/security/nss/gtests/ssl_gtest/ssl_fragment_unittest.cc
+++ /dev/null
@@ -1,157 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "secerr.h"
-#include "ssl.h"
-#include "sslerr.h"
-#include "sslproto.h"
-
-#include "gtest_utils.h"
-#include "scoped_ptrs.h"
-#include "tls_connect.h"
-#include "tls_filter.h"
-#include "tls_parser.h"
-
-namespace nss_test {
-
-// This class cuts every unencrypted handshake record into two parts.
-class RecordFragmenter : public PacketFilter {
- public:
- RecordFragmenter() : sequence_number_(0), splitting_(true) {}
-
- private:
- class HandshakeSplitter {
- public:
- HandshakeSplitter(const DataBuffer& input, DataBuffer* output,
- uint64_t* sequence_number)
- : input_(input),
- output_(output),
- cursor_(0),
- sequence_number_(sequence_number) {}
-
- private:
- void WriteRecord(TlsRecordHeader& record_header,
- DataBuffer& record_fragment) {
- TlsRecordHeader fragment_header(record_header.version(),
- record_header.content_type(),
- *sequence_number_);
- ++*sequence_number_;
- if (::g_ssl_gtest_verbose) {
- std::cerr << "Fragment: " << fragment_header << ' ' << record_fragment
- << std::endl;
- }
- cursor_ = fragment_header.Write(output_, cursor_, record_fragment);
- }
-
- bool SplitRecord(TlsRecordHeader& record_header, DataBuffer& record) {
- TlsParser parser(record);
- while (parser.remaining()) {
- TlsHandshakeFilter::HandshakeHeader handshake_header;
- DataBuffer handshake_body;
- if (!handshake_header.Parse(&parser, record_header, &handshake_body)) {
- ADD_FAILURE() << "couldn't parse handshake header";
- return false;
- }
-
- DataBuffer record_fragment;
- // We can't fragment handshake records that are too small.
- if (handshake_body.len() < 2) {
- handshake_header.Write(&record_fragment, 0U, handshake_body);
- WriteRecord(record_header, record_fragment);
- continue;
- }
-
- size_t cut = handshake_body.len() / 2;
- handshake_header.WriteFragment(&record_fragment, 0U, handshake_body, 0U,
- cut);
- WriteRecord(record_header, record_fragment);
-
- handshake_header.WriteFragment(&record_fragment, 0U, handshake_body,
- cut, handshake_body.len() - cut);
- WriteRecord(record_header, record_fragment);
- }
- return true;
- }
-
- public:
- bool Split() {
- TlsParser parser(input_);
- while (parser.remaining()) {
- TlsRecordHeader header;
- DataBuffer record;
- if (!header.Parse(&parser, &record)) {
- ADD_FAILURE() << "bad record header";
- return false;
- }
-
- if (::g_ssl_gtest_verbose) {
- std::cerr << "Record: " << header << ' ' << record << std::endl;
- }
-
- // Don't touch packets from a non-zero epoch. Leave these unmodified.
- if ((header.sequence_number() >> 48) != 0ULL) {
- cursor_ = header.Write(output_, cursor_, record);
- continue;
- }
-
- // Just rewrite the sequence number (CCS only).
- if (header.content_type() != kTlsHandshakeType) {
- EXPECT_EQ(kTlsChangeCipherSpecType, header.content_type());
- WriteRecord(header, record);
- continue;
- }
-
- if (!SplitRecord(header, record)) {
- return false;
- }
- }
- return true;
- }
-
- private:
- const DataBuffer& input_;
- DataBuffer* output_;
- size_t cursor_;
- uint64_t* sequence_number_;
- };
-
- protected:
- virtual PacketFilter::Action Filter(const DataBuffer& input,
- DataBuffer* output) override {
- if (!splitting_) {
- return KEEP;
- }
-
- output->Allocate(input.len());
- HandshakeSplitter splitter(input, output, &sequence_number_);
- if (!splitter.Split()) {
- // If splitting fails, we obviously reached encrypted packets.
- // Stop splitting from that point onward.
- splitting_ = false;
- return KEEP;
- }
-
- return CHANGE;
- }
-
- private:
- uint64_t sequence_number_;
- bool splitting_;
-};
-
-TEST_P(TlsConnectDatagram, FragmentClientPackets) {
- client_->SetPacketFilter(new RecordFragmenter());
- Connect();
- SendReceive();
-}
-
-TEST_P(TlsConnectDatagram, FragmentServerPackets) {
- server_->SetPacketFilter(new RecordFragmenter());
- Connect();
- SendReceive();
-}
-
-} // namespace nss_test
--- a/security/nss/gtests/ssl_gtest/ssl_fuzz_unittest.cc
+++ b/security/nss/gtests/ssl_gtest/ssl_fuzz_unittest.cc
@@ -7,37 +7,28 @@
#include "sslimpl.h"
#include "tls_connect.h"
#include "gtest/gtest.h"
namespace nss_test {
#ifdef UNSAFE_FUZZER_MODE
-#define FUZZ_F(c, f) TEST_F(c, Fuzz_##f)
-#define FUZZ_P(c, f) TEST_P(c, Fuzz_##f)
-#else
-#define FUZZ_F(c, f) TEST_F(c, DISABLED_Fuzz_##f)
-#define FUZZ_P(c, f) TEST_P(c, DISABLED_Fuzz_##f)
-// RNG_ResetForFuzzing() isn't exported from the shared libraries, rather than
-// fail to link to it, make it fail (we're not running it anyway).
-#define RNG_ResetForFuzzing() SECFailure
-#endif
const uint8_t kShortEmptyFinished[8] = {0};
const uint8_t kLongEmptyFinished[128] = {0};
class TlsFuzzTest : public ::testing::Test {};
// Record the application data stream.
class TlsApplicationDataRecorder : public TlsRecordFilter {
public:
TlsApplicationDataRecorder() : buffer_() {}
- virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+ virtual PacketFilter::Action FilterRecord(const RecordHeader& header,
const DataBuffer& input,
DataBuffer* output) {
if (header.content_type() == kTlsApplicationDataType) {
buffer_.Append(input);
}
return KEEP;
}
@@ -65,101 +56,102 @@ class TlsSignatureDamager : public TlsHa
output->data()[output->len() - 1]++;
return CHANGE;
}
private:
uint8_t type_;
};
+void ResetState() {
+ // Clear the list of RSA blinding params.
+ BL_Cleanup();
+
+ // Reinit the list of RSA blinding params.
+ EXPECT_EQ(SECSuccess, BL_Init());
+
+ // Reset the RNG state.
+ EXPECT_EQ(SECSuccess, RNG_ResetForFuzzing());
+}
+
// Ensure that ssl_Time() returns a constant value.
-FUZZ_F(TlsFuzzTest, SSL_Time_Constant) {
- PRUint32 now = ssl_Time();
+TEST_F(TlsFuzzTest, Fuzz_SSL_Time_Constant) {
+ PRInt32 now = ssl_Time();
PR_Sleep(PR_SecondsToInterval(2));
EXPECT_EQ(ssl_Time(), now);
}
// Check that due to the deterministic PRNG we derive
// the same master secret in two consecutive TLS sessions.
-FUZZ_P(TlsConnectGeneric, DeterministicExporter) {
+TEST_P(TlsConnectGeneric, Fuzz_DeterministicExporter) {
const char kLabel[] = "label";
std::vector<unsigned char> out1(32), out2(32);
- // Make sure we have RSA blinding params.
- Connect();
-
- Reset();
ConfigureSessionCache(RESUME_NONE, RESUME_NONE);
DisableECDHEServerKeyReuse();
- // Reset the RNG state.
- EXPECT_EQ(SECSuccess, RNG_ResetForFuzzing());
+ ResetState();
Connect();
// Export a key derived from the MS and nonces.
SECStatus rv =
SSL_ExportKeyingMaterial(client_->ssl_fd(), kLabel, strlen(kLabel), false,
NULL, 0, out1.data(), out1.size());
EXPECT_EQ(SECSuccess, rv);
Reset();
ConfigureSessionCache(RESUME_NONE, RESUME_NONE);
DisableECDHEServerKeyReuse();
- // Reset the RNG state.
- EXPECT_EQ(SECSuccess, RNG_ResetForFuzzing());
+ ResetState();
Connect();
// Export another key derived from the MS and nonces.
rv = SSL_ExportKeyingMaterial(client_->ssl_fd(), kLabel, strlen(kLabel),
false, NULL, 0, out2.data(), out2.size());
EXPECT_EQ(SECSuccess, rv);
// The two exported keys should be the same.
EXPECT_EQ(out1, out2);
}
// Check that due to the deterministic RNG two consecutive
// TLS sessions will have the exact same transcript.
-FUZZ_P(TlsConnectGeneric, DeterministicTranscript) {
- // Make sure we have RSA blinding params.
- Connect();
-
+TEST_P(TlsConnectGeneric, Fuzz_DeterministicTranscript) {
// Connect a few times and compare the transcripts byte-by-byte.
DataBuffer last;
for (size_t i = 0; i < 5; i++) {
Reset();
ConfigureSessionCache(RESUME_NONE, RESUME_NONE);
DisableECDHEServerKeyReuse();
DataBuffer buffer;
client_->SetPacketFilter(new TlsConversationRecorder(buffer));
server_->SetPacketFilter(new TlsConversationRecorder(buffer));
- // Reset the RNG state.
- EXPECT_EQ(SECSuccess, RNG_ResetForFuzzing());
+ ResetState();
Connect();
// Ensure the filters go away before |buffer| does.
- client_->DeletePacketFilter();
- server_->DeletePacketFilter();
+ client_->SetPacketFilter(nullptr);
+ server_->SetPacketFilter(nullptr);
if (last.len() > 0) {
EXPECT_EQ(last, buffer);
}
last = buffer;
}
}
// Check that we can establish and use a connection
// with all supported TLS versions, STREAM and DGRAM.
// Check that records are NOT encrypted.
// Check that records don't have a MAC.
-FUZZ_P(TlsConnectGeneric, ConnectSendReceive_NullCipher) {
+TEST_P(TlsConnectGeneric, Fuzz_ConnectSendReceive_NullCipher) {
EnsureTlsSetup();
// Set up app data filters.
auto client_recorder = new TlsApplicationDataRecorder();
client_->SetPacketFilter(client_recorder);
auto server_recorder = new TlsApplicationDataRecorder();
server_->SetPacketFilter(server_recorder);
@@ -178,52 +170,54 @@ FUZZ_P(TlsConnectGeneric, ConnectSendRec
Receive(buf.len());
// Check for plaintext on the wire.
EXPECT_EQ(buf, client_recorder->buffer());
EXPECT_EQ(buf, server_recorder->buffer());
}
// Check that an invalid Finished message doesn't abort the connection.
-FUZZ_P(TlsConnectGeneric, BogusClientFinished) {
+TEST_P(TlsConnectGeneric, Fuzz_BogusClientFinished) {
EnsureTlsSetup();
auto i1 = new TlsInspectorReplaceHandshakeMessage(
kTlsHandshakeFinished,
DataBuffer(kShortEmptyFinished, sizeof(kShortEmptyFinished)));
client_->SetPacketFilter(i1);
Connect();
SendReceive();
}
// Check that an invalid Finished message doesn't abort the connection.
-FUZZ_P(TlsConnectGeneric, BogusServerFinished) {
+TEST_P(TlsConnectGeneric, Fuzz_BogusServerFinished) {
EnsureTlsSetup();
auto i1 = new TlsInspectorReplaceHandshakeMessage(
kTlsHandshakeFinished,
DataBuffer(kLongEmptyFinished, sizeof(kLongEmptyFinished)));
server_->SetPacketFilter(i1);
Connect();
SendReceive();
}
// Check that an invalid server auth signature doesn't abort the connection.
-FUZZ_P(TlsConnectGeneric, BogusServerAuthSignature) {
+TEST_P(TlsConnectGeneric, Fuzz_BogusServerAuthSignature) {
EnsureTlsSetup();
uint8_t msg_type = version_ == SSL_LIBRARY_VERSION_TLS_1_3
? kTlsHandshakeCertificateVerify
: kTlsHandshakeServerKeyExchange;
server_->SetPacketFilter(new TlsSignatureDamager(msg_type));
Connect();
SendReceive();
}
// Check that an invalid client auth signature doesn't abort the connection.
-FUZZ_P(TlsConnectGeneric, BogusClientAuthSignature) {
+TEST_P(TlsConnectGeneric, Fuzz_BogusClientAuthSignature) {
EnsureTlsSetup();
client_->SetupClientAuth();
server_->RequestClientAuth(true);
client_->SetPacketFilter(
new TlsSignatureDamager(kTlsHandshakeCertificateVerify));
Connect();
}
+
+#endif
}
deleted file mode 100644
--- a/security/nss/gtests/ssl_gtest/ssl_gather_unittest.cc
+++ /dev/null
@@ -1,153 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "gtest_utils.h"
-#include "tls_connect.h"
-
-namespace nss_test {
-
-class GatherV2ClientHelloTest : public TlsConnectTestBase {
- public:
- GatherV2ClientHelloTest() : TlsConnectTestBase(STREAM, 0) {}
-
- void ConnectExpectMalformedClientHello(const DataBuffer &data) {
- EnsureTlsSetup();
-
- auto alert_recorder = new TlsAlertRecorder();
- server_->SetPacketFilter(alert_recorder);
-
- client_->SendDirect(data);
- server_->StartConnect();
- server_->Handshake();
- ASSERT_TRUE_WAIT(
- (server_->error_code() == SSL_ERROR_RX_MALFORMED_CLIENT_HELLO), 2000);
-
- EXPECT_EQ(kTlsAlertFatal, alert_recorder->level());
- EXPECT_EQ(illegal_parameter, alert_recorder->description());
- }
-};
-
-// Gather a 5-byte v3 record, with a zero fragment length. The empty handshake
-// message should be ignored, and the connection will succeed afterwards.
-TEST_F(TlsConnectTest, GatherEmptyV3Record) {
- DataBuffer buffer;
-
- size_t idx = 0;
- idx = buffer.Write(idx, 0x16, 1); // handshake
- idx = buffer.Write(idx, 0x0301, 2); // record_version
- (void)buffer.Write(idx, 0U, 2); // length=0
-
- EnsureTlsSetup();
- client_->SendDirect(buffer);
- Connect();
-}
-
-// Gather a 5-byte v3 record, with a fragment length exceeding the maximum.
-TEST_F(TlsConnectTest, GatherExcessiveV3Record) {
- DataBuffer buffer;
-
- size_t idx = 0;
- idx = buffer.Write(idx, 0x16, 1); // handshake
- idx = buffer.Write(idx, 0x0301, 2); // record_version
- (void)buffer.Write(idx, MAX_FRAGMENT_LENGTH + 2048 + 1, 2); // length=max+1
-
- EnsureTlsSetup();
- auto alert_recorder = new TlsAlertRecorder();
- server_->SetPacketFilter(alert_recorder);
- client_->SendDirect(buffer);
- server_->StartConnect();
- server_->Handshake();
- ASSERT_TRUE_WAIT((server_->error_code() == SSL_ERROR_RX_RECORD_TOO_LONG),
- 2000);
-
- EXPECT_EQ(kTlsAlertFatal, alert_recorder->level());
- EXPECT_EQ(record_overflow, alert_recorder->description());
-}
-
-// Gather a 3-byte v2 header, with a fragment length of 2.
-TEST_F(GatherV2ClientHelloTest, GatherV2RecordLongHeader) {
- DataBuffer buffer;
-
- size_t idx = 0;
- idx = buffer.Write(idx, 0x0002, 2); // length=2 (long header)
- idx = buffer.Write(idx, 0U, 1); // padding=0
- (void)buffer.Write(idx, 0U, 2); // data
-
- ConnectExpectMalformedClientHello(buffer);
-}
-
-// Gather a 3-byte v2 header, with a fragment length of 1.
-TEST_F(GatherV2ClientHelloTest, GatherV2RecordLongHeader2) {
- DataBuffer buffer;
-
- size_t idx = 0;
- idx = buffer.Write(idx, 0x0001, 2); // length=1 (long header)
- idx = buffer.Write(idx, 0U, 1); // padding=0
- idx = buffer.Write(idx, 0U, 1); // data
- (void)buffer.Write(idx, 0U, 1); // surplus (need 5 bytes total)
-
- ConnectExpectMalformedClientHello(buffer);
-}
-
-// Gather a 3-byte v2 header, with a zero fragment length.
-TEST_F(GatherV2ClientHelloTest, GatherEmptyV2RecordLongHeader) {
- DataBuffer buffer;
-
- size_t idx = 0;
- idx = buffer.Write(idx, 0U, 2); // length=0 (long header)
- idx = buffer.Write(idx, 0U, 1); // padding=0
- (void)buffer.Write(idx, 0U, 2); // surplus (need 5 bytes total)
-
- ConnectExpectMalformedClientHello(buffer);
-}
-
-// Gather a 2-byte v2 header, with a fragment length of 3.
-TEST_F(GatherV2ClientHelloTest, GatherV2RecordShortHeader) {
- DataBuffer buffer;
-
- size_t idx = 0;
- idx = buffer.Write(idx, 0x8003, 2); // length=3 (short header)
- (void)buffer.Write(idx, 0U, 3); // data
-
- ConnectExpectMalformedClientHello(buffer);
-}
-
-// Gather a 2-byte v2 header, with a fragment length of 2.
-TEST_F(GatherV2ClientHelloTest, GatherEmptyV2RecordShortHeader2) {
- DataBuffer buffer;
-
- size_t idx = 0;
- idx = buffer.Write(idx, 0x8002, 2); // length=2 (short header)
- idx = buffer.Write(idx, 0U, 2); // data
- (void)buffer.Write(idx, 0U, 1); // surplus (need 5 bytes total)
-
- ConnectExpectMalformedClientHello(buffer);
-}
-
-// Gather a 2-byte v2 header, with a fragment length of 1.
-TEST_F(GatherV2ClientHelloTest, GatherEmptyV2RecordShortHeader3) {
- DataBuffer buffer;
-
- size_t idx = 0;
- idx = buffer.Write(idx, 0x8001, 2); // length=1 (short header)
- idx = buffer.Write(idx, 0U, 1); // data
- (void)buffer.Write(idx, 0U, 2); // surplus (need 5 bytes total)
-
- ConnectExpectMalformedClientHello(buffer);
-}
-
-// Gather a 2-byte v2 header, with a zero fragment length.
-TEST_F(GatherV2ClientHelloTest, GatherEmptyV2RecordShortHeader) {
- DataBuffer buffer;
-
- size_t idx = 0;
- idx = buffer.Write(idx, 0x8000, 2); // length=0 (short header)
- (void)buffer.Write(idx, 0U, 3); // surplus (need 5 bytes total)
-
- ConnectExpectMalformedClientHello(buffer);
-}
-
-} // namespace nss_test
--- a/security/nss/gtests/ssl_gtest/ssl_gtest.gyp
+++ b/security/nss/gtests/ssl_gtest/ssl_gtest.gyp
@@ -20,65 +20,56 @@
'ssl_damage_unittest.cc',
'ssl_dhe_unittest.cc',
'ssl_drop_unittest.cc',
'ssl_ecdh_unittest.cc',
'ssl_ems_unittest.cc',
'ssl_exporter_unittest.cc',
'ssl_extension_unittest.cc',
'ssl_fuzz_unittest.cc',
- 'ssl_fragment_unittest.cc',
- 'ssl_gather_unittest.cc',
'ssl_gtest.cc',
'ssl_hrr_unittest.cc',
'ssl_loopback_unittest.cc',
'ssl_record_unittest.cc',
'ssl_resumption_unittest.cc',
'ssl_skip_unittest.cc',
'ssl_staticrsa_unittest.cc',
'ssl_v2_client_hello_unittest.cc',
'ssl_version_unittest.cc',
'test_io.cc',
'tls_agent.cc',
'tls_connect.cc',
'tls_filter.cc',
'tls_hkdf_unittest.cc',
- 'tls_parser.cc',
- 'tls_protect.cc'
+ 'tls_parser.cc'
],
'dependencies': [
'<(DEPTH)/exports.gyp:nss_exports',
'<(DEPTH)/lib/util/util.gyp:nssutil3',
+ '<(DEPTH)/lib/sqlite/sqlite.gyp:sqlite3',
'<(DEPTH)/gtests/google_test/google_test.gyp:gtest',
+ '<(DEPTH)/lib/softoken/softoken.gyp:softokn',
'<(DEPTH)/lib/smime/smime.gyp:smime',
'<(DEPTH)/lib/ssl/ssl.gyp:ssl',
'<(DEPTH)/lib/nss/nss.gyp:nss_static',
+ '<(DEPTH)/cmd/lib/lib.gyp:sectool',
'<(DEPTH)/lib/pkcs12/pkcs12.gyp:pkcs12',
'<(DEPTH)/lib/pkcs7/pkcs7.gyp:pkcs7',
'<(DEPTH)/lib/certhigh/certhigh.gyp:certhi',
'<(DEPTH)/lib/cryptohi/cryptohi.gyp:cryptohi',
+ '<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap',
+ '<(DEPTH)/lib/softoken/softoken.gyp:softokn',
'<(DEPTH)/lib/certdb/certdb.gyp:certdb',
'<(DEPTH)/lib/pki/pki.gyp:nsspki',
'<(DEPTH)/lib/dev/dev.gyp:nssdev',
'<(DEPTH)/lib/base/base.gyp:nssb',
+ '<(DEPTH)/lib/freebl/freebl.gyp:<(freebl_name)',
'<(DEPTH)/lib/zlib/zlib.gyp:nss_zlib'
],
'conditions': [
- [ 'test_build==1', {
- 'dependencies': [
- '<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap_static',
- ],
- }, {
- 'dependencies': [
- '<(DEPTH)/lib/sqlite/sqlite.gyp:sqlite3',
- '<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap',
- '<(DEPTH)/lib/softoken/softoken.gyp:softokn',
- '<(DEPTH)/lib/freebl/freebl.gyp:freebl',
- ],
- }],
[ 'disable_dbm==0', {
'dependencies': [
'<(DEPTH)/lib/dbm/src/src.gyp:dbm',
],
}],
[ 'disable_libpkix==0', {
'dependencies': [
'<(DEPTH)/lib/libpkix/pkix/certsel/certsel.gyp:pkixcertsel',
@@ -98,16 +89,13 @@
}
],
'target_defaults': {
'include_dirs': [
'../../gtests/google_test/gtest/include',
'../../gtests/common',
'../../lib/ssl'
],
- 'defines': [
- 'NSS_USE_STATIC_LIBS'
- ],
},
'variables': {
'module': 'nss',
}
}
--- a/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc
+++ b/security/nss/gtests/ssl_gtest/ssl_loopback_unittest.cc
@@ -156,25 +156,26 @@ TEST_P(TlsConnectDatagram, TestDtlsHoldd
// One for send, one for receive.
EXPECT_EQ(2, SSLInt_CountTls13CipherSpecs(client_->ssl_fd()));
}
}
class TlsPreCCSHeaderInjector : public TlsRecordFilter {
public:
TlsPreCCSHeaderInjector() {}
- virtual PacketFilter::Action FilterRecord(
- const TlsRecordHeader& record_header, const DataBuffer& input,
- size_t* offset, DataBuffer* output) override {
+ virtual PacketFilter::Action FilterRecord(const RecordHeader& record_header,
+ const DataBuffer& input,
+ size_t* offset,
+ DataBuffer* output) override {
if (record_header.content_type() != kTlsChangeCipherSpecType) return KEEP;
std::cerr << "Injecting Finished header before CCS\n";
const uint8_t hhdr[] = {kTlsHandshakeFinished, 0x00, 0x00, 0x0c};
DataBuffer hhdr_buf(hhdr, sizeof(hhdr));
- TlsRecordHeader nhdr(record_header.version(), kTlsHandshakeType, 0);
+ RecordHeader nhdr(record_header.version(), kTlsHandshakeType, 0);
*offset = nhdr.Write(output, *offset, hhdr_buf);
*offset = record_header.Write(output, *offset, input);
return CHANGE;
}
};
TEST_P(TlsConnectStreamPre13, ClientFinishedHeaderBeforeCCS) {
client_->SetPacketFilter(new TlsPreCCSHeaderInjector());
@@ -204,35 +205,35 @@ TEST_P(TlsConnectTls13, UnknownAlert) {
TEST_P(TlsConnectTls13, AlertWrongLevel) {
Connect();
SSLInt_SendAlert(server_->ssl_fd(), kTlsAlertWarning,
kTlsAlertUnexpectedMessage);
client_->ExpectReadWriteError();
client_->WaitForErrorCode(SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT, 2000);
}
+TEST_F(TlsConnectStreamTls13, NegotiateShortHeaders) {
+ client_->SetShortHeadersEnabled();
+ server_->SetShortHeadersEnabled();
+ client_->ExpectShortHeaders();
+ server_->ExpectShortHeaders();
+ Connect();
+}
+
TEST_F(TlsConnectStreamTls13, Tls13FailedWriteSecondFlight) {
EnsureTlsSetup();
client_->StartConnect();
server_->StartConnect();
client_->Handshake();
server_->Handshake(); // Send first flight.
client_->adapter()->CloseWrites();
client_->Handshake(); // This will get an error, but shouldn't crash.
client_->CheckErrorCode(SSL_ERROR_SOCKET_WRITE_FAILURE);
}
-TEST_F(TlsConnectStreamTls13, NegotiateShortHeaders) {
- client_->SetShortHeadersEnabled();
- server_->SetShortHeadersEnabled();
- client_->ExpectShortHeaders();
- server_->ExpectShortHeaders();
- Connect();
-}
-
INSTANTIATE_TEST_CASE_P(GenericStream, TlsConnectGeneric,
::testing::Combine(TlsConnectTestBase::kTlsModesStream,
TlsConnectTestBase::kTlsVAll));
INSTANTIATE_TEST_CASE_P(
GenericDatagram, TlsConnectGeneric,
::testing::Combine(TlsConnectTestBase::kTlsModesDatagram,
TlsConnectTestBase::kTlsV11Plus));
--- a/security/nss/gtests/ssl_gtest/ssl_resumption_unittest.cc
+++ b/security/nss/gtests/ssl_gtest/ssl_resumption_unittest.cc
@@ -16,17 +16,16 @@ extern "C" {
#include "libssl_internals.h"
}
#include "gtest_utils.h"
#include "scoped_ptrs.h"
#include "tls_connect.h"
#include "tls_filter.h"
#include "tls_parser.h"
-#include "tls_protect.h"
namespace nss_test {
class TlsServerKeyExchangeEcdhe {
public:
bool Parse(const DataBuffer& buffer) {
TlsParser parser(buffer);
@@ -575,68 +574,9 @@ TEST_F(TlsConnectTest, TestTls13Resumpti
Reset();
ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET);
ConfigureVersion(SSL_LIBRARY_VERSION_TLS_1_3);
ExpectResumption(RESUME_TICKET);
Connect();
SendReceive();
}
-TEST_F(TlsConnectTest, TestTls13ResumptionDowngrade) {
- ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET);
- ConfigureVersion(SSL_LIBRARY_VERSION_TLS_1_3);
- Connect();
-
- SendReceive(); // Need to read so that we absorb the session tickets.
- CheckKeys();
-
- // Try resuming the connection. This will fail resuming the 1.3 session
- // from before, but will successfully establish a 1.2 connection.
- Reset();
- ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET);
- client_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_2,
- SSL_LIBRARY_VERSION_TLS_1_3);
- server_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_2,
- SSL_LIBRARY_VERSION_TLS_1_2);
- Connect();
-
- // Renegotiate to ensure we don't carryover any state
- // from the 1.3 resumption attempt.
- client_->SetExpectedVersion(SSL_LIBRARY_VERSION_TLS_1_2);
- client_->PrepareForRenegotiate();
- server_->StartRenegotiate();
- Handshake();
-
- SendReceive();
- CheckKeys();
-}
-
-TEST_F(TlsConnectTest, TestTls13ResumptionForcedDowngrade) {
- ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET);
- ConfigureVersion(SSL_LIBRARY_VERSION_TLS_1_3);
- Connect();
-
- SendReceive(); // Need to read so that we absorb the session tickets.
- CheckKeys();
-
- // Try resuming the connection.
- Reset();
- ConfigureVersion(SSL_LIBRARY_VERSION_TLS_1_3);
- ConfigureSessionCache(RESUME_BOTH, RESUME_TICKET);
- // Enable the lower version on the client.
- client_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_2,
- SSL_LIBRARY_VERSION_TLS_1_3);
-
- // Add filters that set downgrade SH.version to 1.2 and the cipher suite
- // to one that works with 1.2, so that we don't run into early sanity checks.
- // We will eventually fail the (sid.version == SH.version) check.
- std::vector<PacketFilter*> filters;
- filters.push_back(new SelectedCipherSuiteReplacer(
- TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256));
- filters.push_back(new SelectedVersionReplacer(SSL_LIBRARY_VERSION_TLS_1_2));
- server_->SetPacketFilter(new ChainedPacketFilter(filters));
-
- ConnectExpectFail();
- client_->CheckErrorCode(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
- server_->CheckErrorCode(SSL_ERROR_BAD_MAC_READ);
-}
-
} // namespace nss_test
--- a/security/nss/gtests/ssl_gtest/ssl_skip_unittest.cc
+++ b/security/nss/gtests/ssl_gtest/ssl_skip_unittest.cc
@@ -23,19 +23,19 @@ class TlsHandshakeSkipFilter : public Tl
public:
// A TLS record filter that skips handshake messages of the identified type.
TlsHandshakeSkipFilter(uint8_t handshake_type)
: handshake_type_(handshake_type), skipped_(false) {}
protected:
// Takes a record; if it is a handshake record, it removes the first handshake
// message that is of handshake_type_ type.
- virtual PacketFilter::Action FilterRecord(
- const TlsRecordHeader& record_header, const DataBuffer& input,
- DataBuffer* output) {
+ virtual PacketFilter::Action FilterRecord(const RecordHeader& record_header,
+ const DataBuffer& input,
+ DataBuffer* output) {
if (record_header.content_type() != kTlsHandshakeType) {
return KEEP;
}
size_t output_offset = 0U;
output->Allocate(input.len());
TlsParser parser(input);
@@ -93,50 +93,16 @@ class TlsSkipTest
server_->SetPacketFilter(filter);
}
ConnectExpectFail();
EXPECT_EQ(kTlsAlertFatal, alert_recorder->level());
EXPECT_EQ(alert, alert_recorder->description());
}
};
-class Tls13SkipTest : public TlsConnectTestBase,
- public ::testing::WithParamInterface<std::string> {
- protected:
- Tls13SkipTest()
- : TlsConnectTestBase(GetParam(), SSL_LIBRARY_VERSION_TLS_1_3) {}
-
- void ServerSkipTest(TlsRecordFilter* filter, int32_t error) {
- EnsureTlsSetup();
- server_->SetPacketFilter(filter);
- filter->EnableDecryption();
- if (mode_ == STREAM) {
- ConnectExpectFail();
- } else {
- ConnectExpectFailOneSide(TlsAgent::CLIENT);
- }
- client_->CheckErrorCode(error);
- if (mode_ == STREAM) {
- server_->CheckErrorCode(SSL_ERROR_BAD_MAC_READ);
- } else {
- ASSERT_EQ(TlsAgent::STATE_CONNECTING, server_->state());
- }
- }
-
- void ClientSkipTest(TlsRecordFilter* filter, int32_t error) {
- EnsureTlsSetup();
- client_->SetPacketFilter(filter);
- filter->EnableDecryption();
- ConnectExpectFailOneSide(TlsAgent::SERVER);
-
- server_->CheckErrorCode(error);
- ASSERT_EQ(TlsAgent::STATE_CONNECTED, client_->state());
- }
-};
-
TEST_P(TlsSkipTest, SkipCertificateRsa) {
EnableOnlyStaticRsaCiphers();
ServerSkipTest(new TlsHandshakeSkipFilter(kTlsHandshakeCertificate));
client_->CheckErrorCode(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
}
TEST_P(TlsSkipTest, SkipCertificateDhe) {
ServerSkipTest(new TlsHandshakeSkipFilter(kTlsHandshakeCertificate));
@@ -177,46 +143,16 @@ TEST_P(TlsSkipTest, SkipCertAndKeyExchEc
Reset(TlsAgent::kServerEcdsa256);
auto chain = new ChainedPacketFilter();
chain->Add(new TlsHandshakeSkipFilter(kTlsHandshakeCertificate));
chain->Add(new TlsHandshakeSkipFilter(kTlsHandshakeServerKeyExchange));
ServerSkipTest(chain);
client_->CheckErrorCode(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
}
-TEST_P(Tls13SkipTest, SkipEncryptedExtensions) {
- ServerSkipTest(new TlsHandshakeSkipFilter(kTlsHandshakeEncryptedExtensions),
- SSL_ERROR_RX_UNEXPECTED_CERTIFICATE);
-}
-
-TEST_P(Tls13SkipTest, SkipServerCertificate) {
- ServerSkipTest(new TlsHandshakeSkipFilter(kTlsHandshakeCertificate),
- SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
-}
-
-TEST_P(Tls13SkipTest, SkipServerCertificateVerify) {
- ServerSkipTest(new TlsHandshakeSkipFilter(kTlsHandshakeCertificateVerify),
- SSL_ERROR_RX_UNEXPECTED_FINISHED);
-}
-
-TEST_P(Tls13SkipTest, SkipClientCertificate) {
- client_->SetupClientAuth();
- server_->RequestClientAuth(true);
- ClientSkipTest(new TlsHandshakeSkipFilter(kTlsHandshakeCertificate),
- SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
-}
-
-TEST_P(Tls13SkipTest, SkipClientCertificateVerify) {
- client_->SetupClientAuth();
- server_->RequestClientAuth(true);
- ClientSkipTest(new TlsHandshakeSkipFilter(kTlsHandshakeCertificateVerify),
- SSL_ERROR_RX_UNEXPECTED_FINISHED);
-}
-
INSTANTIATE_TEST_CASE_P(SkipTls10, TlsSkipTest,
::testing::Combine(TlsConnectTestBase::kTlsModesStream,
TlsConnectTestBase::kTlsV10));
INSTANTIATE_TEST_CASE_P(SkipVariants, TlsSkipTest,
::testing::Combine(TlsConnectTestBase::kTlsModesAll,
TlsConnectTestBase::kTlsV11V12));
-INSTANTIATE_TEST_CASE_P(Skip13Variants, Tls13SkipTest,
- TlsConnectTestBase::kTlsModesAll);
+
} // namespace nss_test
--- a/security/nss/gtests/ssl_gtest/ssl_v2_client_hello_unittest.cc
+++ b/security/nss/gtests/ssl_gtest/ssl_v2_client_hello_unittest.cc
@@ -197,38 +197,16 @@ class SSLv2ClientHelloTest : public SSLv
};
// Test negotiating TLS 1.0 - 1.2.
TEST_P(SSLv2ClientHelloTest, Connect) {
SetAvailableCipherSuite(TLS_DHE_RSA_WITH_AES_128_CBC_SHA);
Connect();
}
-// Sending a v2 ClientHello after a no-op v3 record must fail.
-TEST_P(SSLv2ClientHelloTest, ConnectAfterEmptyV3Record) {
- DataBuffer buffer;
-
- size_t idx = 0;
- idx = buffer.Write(idx, 0x16, 1); // handshake
- idx = buffer.Write(idx, 0x0301, 2); // record_version
- (void)buffer.Write(idx, 0U, 2); // length=0
-
- SetAvailableCipherSuite(TLS_DHE_RSA_WITH_AES_128_CBC_SHA);
- EnsureTlsSetup();
- client_->SendDirect(buffer);
-
- // Need padding so the connection doesn't just time out. With a v2
- // ClientHello parsed as a v3 record we will use the record version
- // as the record length.
- SetPadding(255);
-
- ConnectExpectFail();
- EXPECT_EQ(SSL_ERROR_BAD_CLIENT, server_->error_code());
-}
-
// Test negotiating TLS 1.3.
TEST_F(SSLv2ClientHelloTestF, Connect13) {
EnsureTlsSetup();
SetExpectedVersion(SSL_LIBRARY_VERSION_TLS_1_3);
ConfigureVersion(SSL_LIBRARY_VERSION_TLS_1_3);
std::vector<uint16_t> cipher_suites = {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256};
SetAvailableCipherSuites(cipher_suites);
--- a/security/nss/gtests/ssl_gtest/ssl_version_unittest.cc
+++ b/security/nss/gtests/ssl_gtest/ssl_version_unittest.cc
@@ -118,28 +118,16 @@ TEST_F(TlsConnectTest, TestFallbackFromT
SSL_LIBRARY_VERSION_TLS_1_2);
server_->SetVersionRange(SSL_LIBRARY_VERSION_TLS_1_1,
SSL_LIBRARY_VERSION_TLS_1_3);
ConnectExpectFail();
ASSERT_EQ(SSL_ERROR_RX_MALFORMED_SERVER_HELLO, client_->error_code());
}
#endif
-TEST_P(TlsConnectGeneric, TestFallbackSCSVVersionMatch) {
- client_->SetFallbackSCSVEnabled(true);
- Connect();
-}
-
-TEST_P(TlsConnectGenericPre13, TestFallbackSCSVVersionMismatch) {
- client_->SetFallbackSCSVEnabled(true);
- server_->SetVersionRange(version_, version_ + 1);
- ConnectExpectFail();
- client_->CheckErrorCode(SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT);
-}
-
// The TLS v1.3 spec section C.4 states that 'Implementations MUST NOT send or
// accept any records with a version less than { 3, 0 }'. Thus we will not
// allow version ranges including both SSL v3 and TLS v1.3.
TEST_F(TlsConnectTest, DisallowSSLv3HelloWithTLSv13Enabled) {
SECStatus rv;
SSLVersionRange vrange = {SSL_LIBRARY_VERSION_3_0,
SSL_LIBRARY_VERSION_TLS_1_3};
--- a/security/nss/gtests/ssl_gtest/tls_agent.cc
+++ b/security/nss/gtests/ssl_gtest/tls_agent.cc
@@ -97,44 +97,32 @@ TlsAgent::~TlsAgent() {
void TlsAgent::SetState(State state) {
if (state_ == state) return;
LOG("Changing state from " << state_ << " to " << state);
state_ = state;
}
-/*static*/ bool TlsAgent::LoadCertificate(const std::string& name,
- ScopedCERTCertificate* cert,
- ScopedSECKEYPrivateKey* priv) {
- cert->reset(PK11_FindCertFromNickname(name.c_str(), nullptr));
- EXPECT_NE(nullptr, cert->get());
- if (!cert->get()) return false;
-
- priv->reset(PK11_FindKeyByAnyCert(cert->get(), nullptr));
- EXPECT_NE(nullptr, priv->get());
- if (!priv->get()) return false;
-
- return true;
-}
-
bool TlsAgent::ConfigServerCert(const std::string& name, bool updateKeyBits,
const SSLExtraServerCertData* serverCertData) {
- ScopedCERTCertificate cert;
- ScopedSECKEYPrivateKey priv;
- if (!TlsAgent::LoadCertificate(name, &cert, &priv)) {
- return false;
+ ScopedCERTCertificate cert(PK11_FindCertFromNickname(name.c_str(), nullptr));
+ EXPECT_NE(nullptr, cert.get());
+ if (!cert.get()) return false;
+
+ ScopedSECKEYPublicKey pub(CERT_ExtractPublicKey(cert.get()));
+ EXPECT_NE(nullptr, pub.get());
+ if (!pub.get()) return false;
+ if (updateKeyBits) {
+ server_key_bits_ = SECKEY_PublicKeyStrengthInBits(pub.get());
}
- if (updateKeyBits) {
- ScopedSECKEYPublicKey pub(CERT_ExtractPublicKey(cert.get()));
- EXPECT_NE(nullptr, pub.get());
- if (!pub.get()) return false;
- server_key_bits_ = SECKEY_PublicKeyStrengthInBits(pub.get());
- }
+ ScopedSECKEYPrivateKey priv(PK11_FindKeyByAnyCert(cert.get(), nullptr));
+ EXPECT_NE(nullptr, priv.get());
+ if (!priv.get()) return false;
SECStatus rv =
SSL_ConfigSecureServer(ssl_fd_, nullptr, nullptr, ssl_kea_null);
EXPECT_EQ(SECFailure, rv);
rv = SSL_ConfigServerCert(ssl_fd_, cert.get(), priv.get(), serverCertData,
serverCertData ? sizeof(*serverCertData) : 0);
return rv == SECSuccess;
}
@@ -188,33 +176,40 @@ void TlsAgent::SetupClientAuth() {
EXPECT_TRUE(EnsureTlsSetup());
ASSERT_EQ(CLIENT, role_);
EXPECT_EQ(SECSuccess,
SSL_GetClientAuthDataHook(ssl_fd_, GetClientAuthDataHook,
reinterpret_cast<void*>(this)));
}
+bool TlsAgent::GetClientAuthCredentials(CERTCertificate** cert,
+ SECKEYPrivateKey** priv) const {
+ *cert = PK11_FindCertFromNickname(name_.c_str(), nullptr);
+ EXPECT_NE(nullptr, *cert);
+ if (!*cert) return false;
+
+ *priv = PK11_FindKeyByAnyCert(*cert, nullptr);
+ EXPECT_NE(nullptr, *priv);
+ if (!*priv) return false; // Leak cert.
+
+ return true;
+}
+
SECStatus TlsAgent::GetClientAuthDataHook(void* self, PRFileDesc* fd,
CERTDistNames* caNames,
- CERTCertificate** clientCert,
- SECKEYPrivateKey** clientKey) {
+ CERTCertificate** cert,
+ SECKEYPrivateKey** privKey) {
TlsAgent* agent = reinterpret_cast<TlsAgent*>(self);
ScopedCERTCertificate peerCert(SSL_PeerCertificate(agent->ssl_fd()));
EXPECT_TRUE(peerCert) << "Client should be able to see the server cert";
-
- ScopedCERTCertificate cert;
- ScopedSECKEYPrivateKey priv;
- if (!TlsAgent::LoadCertificate(agent->name(), &cert, &priv)) {
- return SECFailure;
+ if (agent->GetClientAuthCredentials(cert, privKey)) {
+ return SECSuccess;
}
-
- *clientCert = cert.release();
- *clientKey = priv.release();
- return SECSuccess;
+ return SECFailure;
}
bool TlsAgent::GetPeerChainLength(size_t* count) {
CERTCertList* chain = SSL_PeerCertificateChain(ssl_fd_);
if (!chain) return false;
*count = 0;
for (PRCList* cursor = PR_NEXT_LINK(&chain->list); cursor != &chain->list;
@@ -366,24 +361,16 @@ void TlsAgent::SetSessionCacheEnabled(bo
void TlsAgent::Set0RttEnabled(bool en) {
EXPECT_TRUE(EnsureTlsSetup());
SECStatus rv =
SSL_OptionSet(ssl_fd_, SSL_ENABLE_0RTT_DATA, en ? PR_TRUE : PR_FALSE);
EXPECT_EQ(SECSuccess, rv);
}
-void TlsAgent::SetFallbackSCSVEnabled(bool en) {
- EXPECT_TRUE(role_ == CLIENT && EnsureTlsSetup());
-
- SECStatus rv =
- SSL_OptionSet(ssl_fd_, SSL_ENABLE_FALLBACK_SCSV, en ? PR_TRUE : PR_FALSE);
- EXPECT_EQ(SECSuccess, rv);
-}
-
void TlsAgent::SetShortHeadersEnabled() {
EXPECT_TRUE(EnsureTlsSetup());
SECStatus rv = SSLInt_EnableShortHeaders(ssl_fd_);
EXPECT_EQ(SECSuccess, rv);
}
void TlsAgent::SetVersionRange(uint16_t minver, uint16_t maxver) {
@@ -738,20 +725,17 @@ void TlsAgent::SetDowngradeCheckVersion(
SECStatus rv = SSL_SetDowngradeCheckVersion(ssl_fd_, version);
ASSERT_EQ(SECSuccess, rv);
}
void TlsAgent::Handshake() {
LOGV("Handshake");
SECStatus rv = SSL_ForceHandshake(ssl_fd_);
if (rv == SECSuccess) {
- if (!falsestart_enabled_) {
- EXPECT_EQ(STATE_CONNECTED, state_)
- << "the handshake callback should have been called already";
- }
+ Connected();
Poller::Instance()->Wait(READABLE_EVENT, adapter_, this,
&TlsAgent::ReadableCallback);
return;
}
int32_t err = PR_GetError();
if (err == PR_WOULD_BLOCK_ERROR) {
@@ -874,17 +858,16 @@ void TlsAgent::ConfigureSessionCache(Ses
EXPECT_EQ(SECSuccess, rv);
rv = SSL_OptionSet(ssl_fd_, SSL_ENABLE_SESSION_TICKETS,
mode & RESUME_TICKET ? PR_TRUE : PR_FALSE);
EXPECT_EQ(SECSuccess, rv);
}
void TlsAgent::DisableECDHEServerKeyReuse() {
- ASSERT_TRUE(EnsureTlsSetup());
ASSERT_EQ(TlsAgent::SERVER, role_);
SECStatus rv = SSL_OptionSet(ssl_fd_, SSL_REUSE_SERVER_ECDHE_KEY, PR_FALSE);
EXPECT_EQ(SECSuccess, rv);
}
static const std::string kTlsRolesAllArr[] = {"CLIENT", "SERVER"};
::testing::internal::ParamGenerator<std::string>
TlsAgentTestBase::kTlsRolesAll = ::testing::ValuesIn(kTlsRolesAllArr);
--- a/security/nss/gtests/ssl_gtest/tls_agent.h
+++ b/security/nss/gtests/ssl_gtest/tls_agent.h
@@ -9,21 +9,19 @@
#include "prio.h"
#include "ssl.h"
#include <functional>
#include <iostream>
#include "test_io.h"
-#include "tls_filter.h"
#define GTEST_HAS_RTTI 0
#include "gtest/gtest.h"
-#include "scoped_ptrs.h"
extern bool g_ssl_gtest_verbose;
namespace nss_test {
#define LOG(msg) std::cerr << role_str() << ": " << msg << std::endl
#define LOGV(msg) \
do { \
@@ -82,27 +80,20 @@ class TlsAgent : public PollTarget {
adapter_ = DummyPrSocket::GetAdapter(pr_fd_);
if (!adapter_) return false;
return true;
}
void SetPeer(TlsAgent* peer) { adapter_->SetPeer(peer->adapter_); }
- void SetPacketFilter(TlsRecordFilter* filter) {
- filter->SetAgent(this);
- adapter_->SetPacketFilter(filter);
- }
-
void SetPacketFilter(PacketFilter* filter) {
adapter_->SetPacketFilter(filter);
}
- void DeletePacketFilter() { adapter_->SetPacketFilter(nullptr); }
-
void StartConnect(PRFileDesc* model = nullptr);
void CheckKEA(SSLKEAType kea_type, SSLNamedGroup group,
size_t kea_size = 0) const;
void CheckAuthType(SSLAuthType auth_type,
SSLSignatureScheme sig_scheme) const;
void DisableAllCiphers();
void EnableCiphersByAuthType(SSLAuthType authType);
@@ -111,32 +102,30 @@ class TlsAgent : public PollTarget {
void EnableGroupsByAuthType(SSLAuthType authType);
void EnableSingleCipher(uint16_t cipher);
void Handshake();
// Marks the internal state as CONNECTING in anticipation of renegotiation.
void PrepareForRenegotiate();
// Prepares for renegotiation, then actually triggers it.
void StartRenegotiate();
- static bool LoadCertificate(const std::string& name,
- ScopedCERTCertificate* cert,
- ScopedSECKEYPrivateKey* priv);
bool ConfigServerCert(const std::string& name, bool updateKeyBits = false,
const SSLExtraServerCertData* serverCertData = nullptr);
bool ConfigServerCertWithChain(const std::string& name);
bool EnsureTlsSetup(PRFileDesc* modelSocket = nullptr);
void SetupClientAuth();
void RequestClientAuth(bool requireAuth);
+ bool GetClientAuthCredentials(CERTCertificate** cert,
+ SECKEYPrivateKey** priv) const;
void ConfigureSessionCache(SessionResumptionMode mode);
void SetSessionTicketsEnabled(bool en);
void SetSessionCacheEnabled(bool en);
void Set0RttEnabled(bool en);
- void SetFallbackSCSVEnabled(bool en);
void SetShortHeadersEnabled();
void SetVersionRange(uint16_t minver, uint16_t maxver);
void GetVersionRange(uint16_t* minver, uint16_t* maxver);
void CheckPreliminaryInfo();
void ResetPreliminaryInfo();
void SetExpectedVersion(uint16_t version);
void SetServerKeyBits(uint16_t bits);
void ExpectReadWriteError();
@@ -179,17 +168,17 @@ class TlsAgent : public PollTarget {
const CERTCertificate* peer_cert() const {
return SSL_PeerCertificate(ssl_fd_);
}
const char* state_str() const { return state_str(state()); }
static const char* state_str(State state) { return states[state]; }
- PRFileDesc* ssl_fd() const { return ssl_fd_; }
+ PRFileDesc* ssl_fd() { return ssl_fd_; }
DummyPrSocket* adapter() { return adapter_; }
bool is_compressed() const {
return info_.compressionMethod != ssl_compression_null;
}
uint16_t server_key_bits() const { return server_key_bits_; }
uint16_t min_version() const { return vrange_.min; }
uint16_t max_version() const { return vrange_.max; }
--- a/security/nss/gtests/ssl_gtest/tls_connect.cc
+++ b/security/nss/gtests/ssl_gtest/tls_connect.cc
@@ -8,17 +8,16 @@
extern "C" {
#include "libssl_internals.h"
}
#include <iostream>
#include "databuffer.h"
#include "gtest_utils.h"
-#include "scoped_ptrs.h"
#include "sslproto.h"
extern std::string g_working_dir_path;
namespace nss_test {
static const std::string kTlsModesStreamArr[] = {"TLS"};
::testing::internal::ParamGenerator<std::string>
@@ -341,23 +340,16 @@ void TlsConnectTestBase::CheckKeys(SSLKE
}
SSLSignatureScheme scheme;
switch (auth_type) {
case ssl_auth_rsa_decrypt:
scheme = ssl_sig_none;
break;
case ssl_auth_rsa_sign:
- if (version_ >= SSL_LIBRARY_VERSION_TLS_1_2) {
- scheme = ssl_sig_rsa_pss_sha256;
- } else {
- scheme = ssl_sig_rsa_pkcs1_sha256;
- }
- break;
- case ssl_auth_rsa_pss:
scheme = ssl_sig_rsa_pss_sha256;
break;
case ssl_auth_ecdsa:
scheme = ssl_sig_ecdsa_secp256r1_sha256;
break;
case ssl_auth_dsa:
scheme = ssl_sig_dsa_sha1;
break;
@@ -376,34 +368,17 @@ void TlsConnectTestBase::CheckKeys() con
void TlsConnectTestBase::ConnectExpectFail() {
server_->StartConnect();
client_->StartConnect();
Handshake();
ASSERT_EQ(TlsAgent::STATE_ERROR, client_->state());
ASSERT_EQ(TlsAgent::STATE_ERROR, server_->state());
}
-void TlsConnectTestBase::ConnectExpectFailOneSide(TlsAgent::Role failing_side) {
- server_->StartConnect();
- client_->StartConnect();
- client_->SetServerKeyBits(server_->server_key_bits());
- client_->Handshake();
- server_->Handshake();
- TlsAgent* fail_agent;
-
- if (failing_side == TlsAgent::CLIENT) {
- fail_agent = client_;
- } else {
- fail_agent = server_;
- }
- ASSERT_TRUE_WAIT(fail_agent->state() == TlsAgent::STATE_ERROR, 5000);
-}
-
void TlsConnectTestBase::ConfigureVersion(uint16_t version) {
- version_ = version;
client_->SetVersionRange(version, version);
server_->SetVersionRange(version, version);
}
void TlsConnectTestBase::SetExpectedVersion(uint16_t version) {
client_->SetExpectedVersion(version);
server_->SetExpectedVersion(version);
}
@@ -444,26 +419,20 @@ void TlsConnectTestBase::EnableSomeEcdhC
}
}
void TlsConnectTestBase::ConfigureSessionCache(SessionResumptionMode client,
SessionResumptionMode server) {
client_->ConfigureSessionCache(client);
server_->ConfigureSessionCache(server);
if ((server & RESUME_TICKET) != 0) {
- ScopedCERTCertificate cert;
- ScopedSECKEYPrivateKey privKey;
- ASSERT_TRUE(TlsAgent::LoadCertificate(TlsAgent::kServerRsaDecrypt, &cert,
- &privKey));
-
- ScopedSECKEYPublicKey pubKey(CERT_ExtractPublicKey(cert.get()));
- ASSERT_TRUE(pubKey);
-
- EXPECT_EQ(SECSuccess,
- SSL_SetSessionTicketKeyPair(pubKey.get(), privKey.get()));
+ // This is an abomination. NSS encrypts session tickets with the server's
+ // RSA public key. That means we need the server to have an RSA certificate
+ // even if it won't be used for the connection.
+ server_->ConfigServerCert(TlsAgent::kServerRsaDecrypt);
}
}
void TlsConnectTestBase::CheckResumption(SessionResumptionMode expected) {
EXPECT_NE(RESUME_BOTH, expected);
int resume_count = expected ? 1 : 0;
int stateless_count = (expected & RESUME_TICKET) ? 1 : 0;
--- a/security/nss/gtests/ssl_gtest/tls_connect.h
+++ b/security/nss/gtests/ssl_gtest/tls_connect.h
@@ -63,17 +63,16 @@ class TlsConnectTestBase : public ::test
// Run the handshake.
void Handshake();
// Connect and check that it works.
void Connect();
// Check that the connection was successfully established.
void CheckConnected();
// Connect and expect it to fail.
void ConnectExpectFail();
- void ConnectExpectFailOneSide(TlsAgent::Role failingSide);
void ConnectWithCipherSuite(uint16_t cipher_suite);
// Check that the keys used in the handshake match expectations.
void CheckKeys(SSLKEAType kea_type, SSLNamedGroup kea_group,
SSLAuthType auth_type, SSLSignatureScheme sig_scheme) const;
// This version guesses some of the values.
void CheckKeys(SSLKEAType kea_type, SSLAuthType auth_type) const;
// This version assumes defaults.
void CheckKeys() const;
--- a/security/nss/gtests/ssl_gtest/tls_filter.cc
+++ b/security/nss/gtests/ssl_gtest/tls_filter.cc
@@ -10,86 +10,30 @@
extern "C" {
// This is not something that should make you happy.
#include "libssl_internals.h"
}
#include <iostream>
#include "gtest_utils.h"
#include "tls_agent.h"
-#include "tls_filter.h"
-#include "tls_protect.h"
namespace nss_test {
-void TlsVersioned::WriteStream(std::ostream& stream) const {
- stream << (is_dtls() ? "DTLS " : "TLS ");
- switch (version()) {
- case 0:
- stream << "(no version)";
- break;
- case SSL_LIBRARY_VERSION_TLS_1_0:
- stream << "1.0";
- break;
- case SSL_LIBRARY_VERSION_DTLS_1_0_WIRE:
- case SSL_LIBRARY_VERSION_TLS_1_1:
- stream << (is_dtls() ? "1.0" : "1.1");
- break;
- case SSL_LIBRARY_VERSION_DTLS_1_2_WIRE:
- case SSL_LIBRARY_VERSION_TLS_1_2:
- stream << "1.2";
- break;
- case SSL_LIBRARY_VERSION_TLS_1_3:
- stream << "1.3";
- break;
- default:
- stream << "Invalid version: " << version();
- break;
- }
-}
-
-void TlsRecordFilter::EnableDecryption() {
- SSLInt_SetCipherSpecChangeFunc(agent()->ssl_fd(), CipherSpecChanged,
- (void*)this);
-}
-
-void TlsRecordFilter::CipherSpecChanged(void* arg, PRBool sending,
- ssl3CipherSpec* newSpec) {
- TlsRecordFilter* self = static_cast<TlsRecordFilter*>(arg);
- PRBool isServer = self->agent()->role() == TlsAgent::SERVER;
-
- if (g_ssl_gtest_verbose) {
- std::cerr << "Cipher spec changed. Role="
- << (isServer ? "server" : "client")
- << " direction=" << (sending ? "send" : "receive") << std::endl;
- }
- if (!sending) return;
-
- self->cipher_spec_.reset(new TlsCipherSpec());
- bool ret =
- self->cipher_spec_->Init(SSLInt_CipherSpecToAlgorithm(isServer, newSpec),
- SSLInt_CipherSpecToKey(isServer, newSpec),
- SSLInt_CipherSpecToIv(isServer, newSpec));
- EXPECT_EQ(true, ret);
-}
-
PacketFilter::Action TlsRecordFilter::Filter(const DataBuffer& input,
DataBuffer* output) {
bool changed = false;
size_t offset = 0U;
output->Allocate(input.len());
TlsParser parser(input);
-
while (parser.remaining()) {
- TlsRecordHeader header;
+ RecordHeader header;
DataBuffer record;
-
if (!header.Parse(&parser, &record)) {
- ADD_FAILURE() << "not a valid record";
return KEEP;
}
if (FilterRecord(header, record, &offset, output) != KEEP) {
changed = true;
} else {
offset = header.Write(output, offset, record);
}
@@ -100,55 +44,44 @@ PacketFilter::Action TlsRecordFilter::Fi
if (changed) {
++count_;
return (offset == 0) ? DROP : CHANGE;
}
return KEEP;
}
-PacketFilter::Action TlsRecordFilter::FilterRecord(
- const TlsRecordHeader& header, const DataBuffer& record, size_t* offset,
- DataBuffer* output) {
+PacketFilter::Action TlsRecordFilter::FilterRecord(const RecordHeader& header,
+ const DataBuffer& record,
+ size_t* offset,
+ DataBuffer* output) {
DataBuffer filtered;
- uint8_t inner_content_type;
- DataBuffer plaintext;
-
- if (!Unprotect(header, record, &inner_content_type, &plaintext)) {
- return KEEP;
- }
-
- TlsRecordHeader real_header = {header.version(), inner_content_type,
- header.sequence_number()};
-
- PacketFilter::Action action = FilterRecord(real_header, plaintext, &filtered);
+ PacketFilter::Action action = FilterRecord(header, record, &filtered);
if (action == KEEP) {
return KEEP;
}
if (action == DROP) {
std::cerr << "record drop: " << record << std::endl;
return DROP;
}
- EXPECT_GT(0x10000U, filtered.len());
- std::cerr << "record old: " << plaintext << std::endl;
- std::cerr << "record new: " << filtered << std::endl;
+ const DataBuffer* source = &record;
+ if (action == CHANGE) {
+ EXPECT_GT(0x10000U, filtered.len());
+ std::cerr << "record old: " << record << std::endl;
+ std::cerr << "record new: " << filtered << std::endl;
+ source = &filtered;
+ }
- DataBuffer ciphertext;
- bool rv = Protect(header, inner_content_type, filtered, &ciphertext);
- EXPECT_TRUE(rv);
- if (!rv) {
- return KEEP;
- }
- *offset = header.Write(output, *offset, ciphertext);
+ *offset = header.Write(output, *offset, *source);
return CHANGE;
}
-bool TlsRecordHeader::Parse(TlsParser* parser, DataBuffer* body) {
+bool TlsRecordFilter::RecordHeader::Parse(TlsParser* parser, DataBuffer* body) {
if (!parser->Read(&content_type_)) {
return false;
}
uint32_t version;
if (!parser->Read(&version, 2)) {
return false;
}
@@ -164,72 +97,32 @@ bool TlsRecordHeader::Parse(TlsParser* p
if (!parser->Read(&tmp, 4)) {
return false;
}
sequence_number_ |= static_cast<uint64_t>(tmp);
}
return parser->ReadVariable(body, 2);
}
-size_t TlsRecordHeader::Write(DataBuffer* buffer, size_t offset,
- const DataBuffer& body) const {
+size_t TlsRecordFilter::RecordHeader::Write(DataBuffer* buffer, size_t offset,
+ const DataBuffer& body) const {
offset = buffer->Write(offset, content_type_, 1);
offset = buffer->Write(offset, version_, 2);
if (is_dtls()) {
// write epoch (2 octet), and seqnum (6 octet)
offset = buffer->Write(offset, sequence_number_ >> 32, 4);
offset = buffer->Write(offset, sequence_number_ & 0xffffffff, 4);
}
offset = buffer->Write(offset, body.len(), 2);
offset = buffer->Write(offset, body);
return offset;
}
-bool TlsRecordFilter::Unprotect(const TlsRecordHeader& header,
- const DataBuffer& ciphertext,
- uint8_t* inner_content_type,
- DataBuffer* plaintext) {
- if (!cipher_spec_ || header.content_type() != kTlsApplicationDataType) {
- *inner_content_type = header.content_type();
- *plaintext = ciphertext;
- return true;
- }
-
- if (!cipher_spec_->Unprotect(header, ciphertext, plaintext)) return false;
-
- size_t len = plaintext->len();
- while (len > 0 && !plaintext->data()[len - 1]) {
- --len;
- }
- if (!len) {
- // Bogus padding.
- return false;
- }
-
- *inner_content_type = plaintext->data()[len - 1];
- plaintext->Truncate(len - 1);
-
- return true;
-}
-
-bool TlsRecordFilter::Protect(const TlsRecordHeader& header,
- uint8_t inner_content_type,
- const DataBuffer& plaintext,
- DataBuffer* ciphertext) {
- if (!cipher_spec_ || header.content_type() != kTlsApplicationDataType) {
- *ciphertext = plaintext;
- return true;
- }
- DataBuffer padded = plaintext;
- padded.Write(padded.len(), inner_content_type, 1);
- return cipher_spec_->Protect(header, padded, ciphertext);
-}
-
PacketFilter::Action TlsHandshakeFilter::FilterRecord(
- const TlsRecordHeader& record_header, const DataBuffer& input,
+ const RecordHeader& record_header, const DataBuffer& input,
DataBuffer* output) {
// Check that the first byte is as requested.
if (record_header.content_type() != kTlsHandshakeType) {
return KEEP;
}
bool changed = false;
size_t offset = 0U;
@@ -261,18 +154,19 @@ PacketFilter::Action TlsHandshakeFilter:
}
offset = header.Write(output, offset, *source);
}
output->Truncate(offset);
return changed ? (offset ? CHANGE : DROP) : KEEP;
}
-bool TlsHandshakeFilter::HandshakeHeader::ReadLength(
- TlsParser* parser, const TlsRecordHeader& header, uint32_t* length) {
+bool TlsHandshakeFilter::HandshakeHeader::ReadLength(TlsParser* parser,
+ const RecordHeader& header,
+ uint32_t* length) {
if (!parser->Read(length, 3)) {
return false; // malformed
}
if (!header.is_dtls()) {
return true; // nothing left to do
}
@@ -293,51 +187,38 @@ bool TlsHandshakeFilter::HandshakeHeader
return false;
}
// All current tests where we are using this code don't fragment.
return (fragment_offset == 0 && fragment_length == *length);
}
bool TlsHandshakeFilter::HandshakeHeader::Parse(
- TlsParser* parser, const TlsRecordHeader& record_header, DataBuffer* body) {
+ TlsParser* parser, const RecordHeader& record_header, DataBuffer* body) {
version_ = record_header.version();
if (!parser->Read(&handshake_type_)) {
return false; // malformed
}
uint32_t length;
if (!ReadLength(parser, record_header, &length)) {
return false;
}
return parser->Read(body, length);
}
-size_t TlsHandshakeFilter::HandshakeHeader::WriteFragment(
- DataBuffer* buffer, size_t offset, const DataBuffer& body,
- size_t fragment_offset, size_t fragment_length) const {
- EXPECT_TRUE(is_dtls());
- EXPECT_GE(body.len(), fragment_offset + fragment_length);
+size_t TlsHandshakeFilter::HandshakeHeader::Write(
+ DataBuffer* buffer, size_t offset, const DataBuffer& body) const {
offset = buffer->Write(offset, handshake_type(), 1);
offset = buffer->Write(offset, body.len(), 3);
- offset = buffer->Write(offset, message_seq_, 2);
- offset = buffer->Write(offset, fragment_offset, 3);
- offset = buffer->Write(offset, fragment_length, 3);
- offset =
- buffer->Write(offset, body.data() + fragment_offset, fragment_length);
- return offset;
-}
-
-size_t TlsHandshakeFilter::HandshakeHeader::Write(
- DataBuffer* buffer, size_t offset, const DataBuffer& body) const {
if (is_dtls()) {
- return WriteFragment(buffer, offset, body, 0U, body.len());
+ offset = buffer->Write(offset, message_seq_, 2);
+ offset = buffer->Write(offset, 0U, 3); // fragment_offset
+ offset = buffer->Write(offset, body.len(), 3);
}
- offset = buffer->Write(offset, handshake_type(), 1);
- offset = buffer->Write(offset, body.len(), 3);
offset = buffer->Write(offset, body);
return offset;
}
PacketFilter::Action TlsInspectorRecordHandshakeMessage::FilterHandshake(
const HandshakeHeader& header, const DataBuffer& input,
DataBuffer* output) {
// Only do this once.
@@ -358,25 +239,24 @@ PacketFilter::Action TlsInspectorReplace
*output = buffer_;
return CHANGE;
}
return KEEP;
}
PacketFilter::Action TlsConversationRecorder::FilterRecord(
- const TlsRecordHeader& header, const DataBuffer& input,
- DataBuffer* output) {
+ const RecordHeader& header, const DataBuffer& input, DataBuffer* output) {
buffer_.Append(input);
return KEEP;
}
-PacketFilter::Action TlsAlertRecorder::FilterRecord(
- const TlsRecordHeader& header, const DataBuffer& input,
- DataBuffer* output) {
+PacketFilter::Action TlsAlertRecorder::FilterRecord(const RecordHeader& header,
+ const DataBuffer& input,
+ DataBuffer* output) {
if (level_ == kTlsAlertFatal) { // already fatal
return KEEP;
}
if (header.content_type() != kTlsAlertType) {
return KEEP;
}
std::cerr << "Alert: " << input << std::endl;
@@ -433,17 +313,17 @@ PacketFilter::Action TlsExtensionFilter:
return KEEP;
}
return FilterExtensions(&parser, input, output);
}
return KEEP;
}
bool TlsExtensionFilter::FindClientHelloExtensions(TlsParser* parser,
- const TlsVersioned& header) {
+ const Versioned& header) {
if (!parser->Skip(2 + 32)) { // version + random
return false;
}
if (!parser->SkipVariable(1)) { // session ID
return false;
}
if (header.is_dtls() && !parser->SkipVariable(1)) { // DTLS cookie
return false;
@@ -571,17 +451,17 @@ PacketFilter::Action TlsExtensionReplace
PacketFilter::Action TlsExtensionDropper::FilterExtension(
uint16_t extension_type, const DataBuffer& input, DataBuffer* output) {
if (extension_type == extension_) {
return DROP;
}
return KEEP;
}
-PacketFilter::Action AfterRecordN::FilterRecord(const TlsRecordHeader& header,
+PacketFilter::Action AfterRecordN::FilterRecord(const RecordHeader& header,
const DataBuffer& body,
DataBuffer* out) {
if (counter_++ == record_) {
DataBuffer buf;
header.Write(&buf, 0, body);
src_->SendDirect(buf);
dest_->Handshake();
func_();
--- a/security/nss/gtests/ssl_gtest/tls_filter.h
+++ b/security/nss/gtests/ssl_gtest/tls_filter.h
@@ -8,180 +8,123 @@
#define tls_filter_h_
#include <functional>
#include <memory>
#include <vector>
#include "test_io.h"
#include "tls_parser.h"
-#include "tls_protect.h"
-
-extern "C" {
-#include "libssl_internals.h"
-}
namespace nss_test {
-class TlsCipherSpec;
-class TlsAgent;
-
-class TlsVersioned {
- public:
- TlsVersioned() : version_(0) {}
- explicit TlsVersioned(uint16_t version) : version_(version) {}
-
- bool is_dtls() const { return IsDtls(version_); }
- uint16_t version() const { return version_; }
-
- void WriteStream(std::ostream& stream) const;
-
- protected:
- uint16_t version_;
-};
-
-class TlsRecordHeader : public TlsVersioned {
- public:
- TlsRecordHeader() : TlsVersioned(), content_type_(0), sequence_number_(0) {}
- TlsRecordHeader(uint16_t version, uint8_t content_type,
- uint64_t sequence_number)
- : TlsVersioned(version),
- content_type_(content_type),
- sequence_number_(sequence_number) {}
-
- uint8_t content_type() const { return content_type_; }
- uint64_t sequence_number() const { return sequence_number_; }
- size_t header_length() const { return is_dtls() ? 11 : 3; }
-
- // Parse the header; return true if successful; body in an outparam if OK.
- bool Parse(TlsParser* parser, DataBuffer* body);
- // Write the header and body to a buffer at the given offset.
- // Return the offset of the end of the write.
- size_t Write(DataBuffer* buffer, size_t offset, const DataBuffer& body) const;
-
- private:
- uint8_t content_type_;
- uint64_t sequence_number_;
-};
-
// Abstract filter that operates on entire (D)TLS records.
class TlsRecordFilter : public PacketFilter {
public:
- TlsRecordFilter() : agent_(nullptr), count_(0), cipher_spec_() {}
-
- void SetAgent(const TlsAgent* agent) { agent_ = agent; }
- const TlsAgent* agent() const { return agent_; }
+ TlsRecordFilter() : count_(0) {}
// External interface. Overrides PacketFilter.
PacketFilter::Action Filter(const DataBuffer& input, DataBuffer* output);
// Report how many packets were altered by the filter.
size_t filtered_packets() const { return count_; }
- // Enable decryption. This only works properly for TLS 1.3 and above.
- // Enabling it for lower version tests will cause undefined
- // behavior.
- void EnableDecryption();
- bool Unprotect(const TlsRecordHeader& header, const DataBuffer& cipherText,
- uint8_t* inner_content_type, DataBuffer* plaintext);
- bool Protect(const TlsRecordHeader& header, uint8_t inner_content_type,
- const DataBuffer& plaintext, DataBuffer* ciphertext);
+ class Versioned {
+ public:
+ Versioned() : version_(0) {}
+ explicit Versioned(uint16_t version) : version_(version) {}
+
+ bool is_dtls() const { return IsDtls(version_); }
+ uint16_t version() const { return version_; }
+
+ protected:
+ uint16_t version_;
+ };
+
+ class RecordHeader : public Versioned {
+ public:
+ RecordHeader() : Versioned(), content_type_(0), sequence_number_(0) {}
+ RecordHeader(uint16_t version, uint8_t content_type,
+ uint64_t sequence_number)
+ : Versioned(version),
+ content_type_(content_type),
+ sequence_number_(sequence_number) {}
+
+ uint8_t content_type() const { return content_type_; }
+ uint64_t sequence_number() const { return sequence_number_; }
+ size_t header_length() const { return is_dtls() ? 11 : 3; }
+
+ // Parse the header; return true if successful; body in an outparam if OK.
+ bool Parse(TlsParser* parser, DataBuffer* body);
+ // Write the header and body to a buffer at the given offset.
+ // Return the offset of the end of the write.
+ size_t Write(DataBuffer* buffer, size_t offset,
+ const DataBuffer& body) const;
+
+ private:
+ uint8_t content_type_;
+ uint64_t sequence_number_;
+ };
protected:
// There are two filter functions which can be overriden. Both are
// called with the header and the record but the outer one is called
// with a raw pointer to let you write into the buffer and lets you
// do anything with this section of the stream. The inner one
// just lets you change the record contents. By default, the
// outer one calls the inner one, so if you override the outer
// one, the inner one is never called unless you call it yourself.
- virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+ virtual PacketFilter::Action FilterRecord(const RecordHeader& header,
const DataBuffer& record,
size_t* offset, DataBuffer* output);
// The record filter receives the record contentType, version and DTLS
// sequence number (which is zero for TLS), plus the existing record payload.
// It returns an action (KEEP, CHANGE, DROP). It writes to the `changed`
// outparam with the new record contents if it chooses to CHANGE the record.
- virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+ virtual PacketFilter::Action FilterRecord(const RecordHeader& header,
const DataBuffer& data,
DataBuffer* changed) {
return KEEP;
}
private:
- static void CipherSpecChanged(void* arg, PRBool sending,
- ssl3CipherSpec* newSpec);
-
- const TlsAgent* agent_;
size_t count_;
- std::unique_ptr<TlsCipherSpec> cipher_spec_;
};
-inline std::ostream& operator<<(std::ostream& stream, TlsVersioned v) {
- v.WriteStream(stream);
- return stream;
-}
-
-inline std::ostream& operator<<(std::ostream& stream, TlsRecordHeader& hdr) {
- hdr.WriteStream(stream);
- stream << ' ';
- switch (hdr.content_type()) {
- case kTlsChangeCipherSpecType:
- stream << "CCS";
- break;
- case kTlsAlertType:
- stream << "Alert";
- break;
- case kTlsHandshakeType:
- stream << "Handshake";
- break;
- case kTlsApplicationDataType:
- stream << "Data";
- break;
- default:
- stream << '<' << hdr.content_type() << '>';
- break;
- }
- return stream << ' ' << std::hex << hdr.sequence_number() << std::dec;
-}
-
// Abstract filter that operates on handshake messages rather than records.
// This assumes that the handshake messages are written in a block as entire
// records and that they don't span records or anything crazy like that.
class TlsHandshakeFilter : public TlsRecordFilter {
public:
TlsHandshakeFilter() {}
- class HandshakeHeader : public TlsVersioned {
+ class HandshakeHeader : public Versioned {
public:
- HandshakeHeader() : TlsVersioned(), handshake_type_(0), message_seq_(0) {}
+ HandshakeHeader() : Versioned(), handshake_type_(0), message_seq_(0) {}
uint8_t handshake_type() const { return handshake_type_; }
- bool Parse(TlsParser* parser, const TlsRecordHeader& record_header,
+ bool Parse(TlsParser* parser, const RecordHeader& record_header,
DataBuffer* body);
size_t Write(DataBuffer* buffer, size_t offset,
const DataBuffer& body) const;
- size_t WriteFragment(DataBuffer* buffer, size_t offset,
- const DataBuffer& body, size_t fragment_offset,
- size_t fragment_length) const;
private:
// Reads the length from the record header.
// This also reads the DTLS fragment information and checks it.
- bool ReadLength(TlsParser* parser, const TlsRecordHeader& header,
+ bool ReadLength(TlsParser* parser, const RecordHeader& header,
uint32_t* length);
uint8_t handshake_type_;
uint16_t message_seq_;
// fragment_offset is always zero in these tests.
};
protected:
- virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+ virtual PacketFilter::Action FilterRecord(const RecordHeader& header,
const DataBuffer& input,
DataBuffer* output);
virtual PacketFilter::Action FilterHandshake(const HandshakeHeader& header,
const DataBuffer& input,
DataBuffer* output) = 0;
private:
};
@@ -219,31 +162,31 @@ class TlsInspectorReplaceHandshakeMessag
DataBuffer buffer_;
};
// Make a copy of the complete conversation.
class TlsConversationRecorder : public TlsRecordFilter {
public:
TlsConversationRecorder(DataBuffer& buffer) : buffer_(buffer) {}
- virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+ virtual PacketFilter::Action FilterRecord(const RecordHeader& header,
const DataBuffer& input,
DataBuffer* output);
private:
DataBuffer& buffer_;
};
// Records an alert. If an alert has already been recorded, it won't save the
// new alert unless the old alert is a warning and the new one is fatal.
class TlsAlertRecorder : public TlsRecordFilter {
public:
TlsAlertRecorder() : level_(255), description_(255) {}
- virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+ virtual PacketFilter::Action FilterRecord(const RecordHeader& header,
const DataBuffer& input,
DataBuffer* output);
uint8_t level() const { return level_; }
uint8_t description() const { return description_; }
private:
uint8_t level_;
@@ -275,17 +218,17 @@ class TlsExtensionFilter : public TlsHan
DataBuffer* output) override;
virtual PacketFilter::Action FilterExtension(uint16_t extension_type,
const DataBuffer& input,
DataBuffer* output) = 0;
public:
static bool FindClientHelloExtensions(TlsParser* parser,
- const TlsVersioned& header);
+ const Versioned& header);
static bool FindServerHelloExtensions(TlsParser* parser);
private:
PacketFilter::Action FilterExtensions(TlsParser* parser,
const DataBuffer& input,
DataBuffer* output);
};
@@ -336,17 +279,17 @@ class TlsAgent;
typedef std::function<void(void)> VoidFunction;
class AfterRecordN : public TlsRecordFilter {
public:
AfterRecordN(TlsAgent* src, TlsAgent* dest, unsigned int record,
VoidFunction func)
: src_(src), dest_(dest), record_(record), func_(func), counter_(0) {}
- virtual PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
+ virtual PacketFilter::Action FilterRecord(const RecordHeader& header,
const DataBuffer& body,
DataBuffer* out) override;
private:
TlsAgent* src_;
TlsAgent* dest_;
unsigned int record_;
VoidFunction func_;
--- a/security/nss/gtests/ssl_gtest/tls_parser.h
+++ b/security/nss/gtests/ssl_gtest/tls_parser.h
@@ -25,17 +25,16 @@ const uint8_t kTlsHandshakeType = 22;
const uint8_t kTlsApplicationDataType = 23;
const uint8_t kTlsHandshakeClientHello = 1;
const uint8_t kTlsHandshakeServerHello = 2;
const uint8_t kTlsHandshakeHelloRetryRequest = 6;
const uint8_t kTlsHandshakeEncryptedExtensions = 8;
const uint8_t kTlsHandshakeCertificate = 11;
const uint8_t kTlsHandshakeServerKeyExchange = 12;
-const uint8_t kTlsHandshakeCertificateRequest = 13;
const uint8_t kTlsHandshakeCertificateVerify = 15;
const uint8_t kTlsHandshakeClientKeyExchange = 16;
const uint8_t kTlsHandshakeFinished = 20;
const uint8_t kTlsAlertWarning = 1;
const uint8_t kTlsAlertFatal = 2;
const uint8_t kTlsAlertUnexpectedMessage = 10;
deleted file mode 100644
--- a/security/nss/gtests/ssl_gtest/tls_protect.cc
+++ /dev/null
@@ -1,145 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "tls_protect.h"
-#include "tls_filter.h"
-
-namespace nss_test {
-
-AeadCipher::~AeadCipher() {
- if (key_) {
- PK11_FreeSymKey(key_);
- }
-}
-
-bool AeadCipher::Init(PK11SymKey *key, const uint8_t *iv) {
- key_ = PK11_ReferenceSymKey(key);
- if (!key_) return false;
-
- memcpy(iv_, iv, sizeof(iv_));
- return true;
-}
-
-void AeadCipher::FormatNonce(uint64_t seq, uint8_t *nonce) {
- memcpy(nonce, iv_, 12);
-
- for (size_t i = 0; i < 8; ++i) {
- nonce[12 - (i + 1)] ^= seq & 0xff;
- seq >>= 8;
- }
-
- DataBuffer d(nonce, 12);
- std::cerr << "Nonce " << d << std::endl;
-}
-
-bool AeadCipher::AeadInner(bool decrypt, void *params, size_t param_length,
- const uint8_t *in, size_t inlen, uint8_t *out,
- size_t *outlen, size_t maxlen) {
- SECStatus rv;
- unsigned int uoutlen = 0;
- SECItem param = {
- siBuffer, static_cast<unsigned char *>(params),
- static_cast<unsigned int>(param_length),
- };
-
- if (decrypt) {
- rv = PK11_Decrypt(key_, mech_, ¶m, out, &uoutlen, maxlen, in, inlen);
- } else {
- rv = PK11_Encrypt(key_, mech_, ¶m, out, &uoutlen, maxlen, in, inlen);
- }
- *outlen = (int)uoutlen;
-
- return rv == SECSuccess;
-}
-
-bool AeadCipherAesGcm::Aead(bool decrypt, uint64_t seq, const uint8_t *in,
- size_t inlen, uint8_t *out, size_t *outlen,
- size_t maxlen) {
- CK_GCM_PARAMS aeadParams;
- unsigned char nonce[12];
-
- memset(&aeadParams, 0, sizeof(aeadParams));
- aeadParams.pIv = nonce;
- aeadParams.ulIvLen = sizeof(nonce);
- aeadParams.pAAD = NULL;
- aeadParams.ulAADLen = 0;
- aeadParams.ulTagBits = 128;
-
- FormatNonce(seq, nonce);
- return AeadInner(decrypt, (unsigned char *)&aeadParams, sizeof(aeadParams),
- in, inlen, out, outlen, maxlen);
-}
-
-bool AeadCipherChacha20Poly1305::Aead(bool decrypt, uint64_t seq,
- const uint8_t *in, size_t inlen,
- uint8_t *out, size_t *outlen,
- size_t maxlen) {
- CK_NSS_AEAD_PARAMS aeadParams;
- unsigned char nonce[12];
-
- memset(&aeadParams, 0, sizeof(aeadParams));
- aeadParams.pNonce = nonce;
- aeadParams.ulNonceLen = sizeof(nonce);
- aeadParams.pAAD = NULL;
- aeadParams.ulAADLen = 0;
- aeadParams.ulTagLen = 16;
-
- FormatNonce(seq, nonce);
- return AeadInner(decrypt, (unsigned char *)&aeadParams, sizeof(aeadParams),
- in, inlen, out, outlen, maxlen);
-}
-
-bool TlsCipherSpec::Init(SSLCipherAlgorithm cipher, PK11SymKey *key,
- const uint8_t *iv) {
- switch (cipher) {
- case ssl_calg_aes_gcm:
- aead_.reset(new AeadCipherAesGcm());
- break;
- case ssl_calg_chacha20:
- aead_.reset(new AeadCipherChacha20Poly1305());
- break;
- default:
- return false;
- }
-
- return aead_->Init(key, iv);
-}
-
-bool TlsCipherSpec::Unprotect(const TlsRecordHeader &header,
- const DataBuffer &ciphertext,
- DataBuffer *plaintext) {
- // Make space.
- plaintext->Allocate(ciphertext.len());
-
- size_t len;
- bool ret =
- aead_->Aead(true, header.sequence_number(), ciphertext.data(),
- ciphertext.len(), plaintext->data(), &len, plaintext->len());
- if (!ret) return false;
-
- plaintext->Truncate(len);
-
- return true;
-}
-
-bool TlsCipherSpec::Protect(const TlsRecordHeader &header,
- const DataBuffer &plaintext,
- DataBuffer *ciphertext) {
- // Make a padded buffer.
-
- ciphertext->Allocate(plaintext.len() +
- 32); // Room for any plausible auth tag
- size_t len;
- bool ret =
- aead_->Aead(false, header.sequence_number(), plaintext.data(),
- plaintext.len(), ciphertext->data(), &len, ciphertext->len());
- if (!ret) return false;
- ciphertext->Truncate(len);
-
- return true;
-}
-
-} // namespace nss_test
deleted file mode 100644
--- a/security/nss/gtests/ssl_gtest/tls_protect.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef tls_protection_h_
-#define tls_protection_h_
-
-#include <cstdint>
-#include <memory>
-
-#include "databuffer.h"
-#include "pk11pub.h"
-#include "sslt.h"
-
-namespace nss_test {
-class TlsRecordHeader;
-
-class AeadCipher {
- public:
- AeadCipher(CK_MECHANISM_TYPE mech) : mech_(mech), key_(nullptr) {}
- ~AeadCipher();
-
- bool Init(PK11SymKey *key, const uint8_t *iv);
- virtual bool Aead(bool decrypt, uint64_t seq, const uint8_t *in, size_t inlen,
- uint8_t *out, size_t *outlen, size_t maxlen) = 0;
-
- protected:
- void FormatNonce(uint64_t seq, uint8_t *nonce);
- bool AeadInner(bool decrypt, void *params, size_t param_length,
- const uint8_t *in, size_t inlen, uint8_t *out, size_t *outlen,
- size_t maxlen);
-
- CK_MECHANISM_TYPE mech_;
- PK11SymKey *key_;
- uint8_t iv_[12];
-};
-
-class AeadCipherChacha20Poly1305 : public AeadCipher {
- public:
- AeadCipherChacha20Poly1305() : AeadCipher(CKM_NSS_CHACHA20_POLY1305) {}
-
- protected:
- bool Aead(bool decrypt, uint64_t seq, const uint8_t *in, size_t inlen,
- uint8_t *out, size_t *outlen, size_t maxlen);
-};
-
-class AeadCipherAesGcm : public AeadCipher {
- public:
- AeadCipherAesGcm() : AeadCipher(CKM_AES_GCM) {}
-
- protected:
- bool Aead(bool decrypt, uint64_t seq, const uint8_t *in, size_t inlen,
- uint8_t *out, size_t *outlen, size_t maxlen);
-};
-
-// Our analog of ssl3CipherSpec
-class TlsCipherSpec {
- public:
- TlsCipherSpec() : aead_() {}
-
- bool Init(SSLCipherAlgorithm cipher, PK11SymKey *key, const uint8_t *iv);
-
- bool Protect(const TlsRecordHeader &header, const DataBuffer &plaintext,
- DataBuffer *ciphertext);
- bool Unprotect(const TlsRecordHeader &header, const DataBuffer &ciphertext,
- DataBuffer *plaintext);
-
- private:
- std::unique_ptr<AeadCipher> aead_;
-};
-
-} // namespace nss_test
-
-#endif
--- a/security/nss/gtests/util_gtest/util_gtest.gyp
+++ b/security/nss/gtests/util_gtest/util_gtest.gyp
@@ -13,25 +13,16 @@
'sources': [
'util_utf8_unittest.cc',
'<(DEPTH)/gtests/common/gtests.cc'
],
'dependencies': [
'<(DEPTH)/exports.gyp:nss_exports',
'<(DEPTH)/gtests/google_test/google_test.gyp:gtest',
'<(DEPTH)/lib/util/util.gyp:nssutil',
- '<(DEPTH)/lib/nss/nss.gyp:nss_static',
- '<(DEPTH)/lib/pk11wrap/pk11wrap.gyp:pk11wrap_static',
- '<(DEPTH)/lib/cryptohi/cryptohi.gyp:cryptohi',
- '<(DEPTH)/lib/certhigh/certhigh.gyp:certhi',
- '<(DEPTH)/lib/certdb/certdb.gyp:certdb',
- '<(DEPTH)/lib/base/base.gyp:nssb',
- '<(DEPTH)/lib/dev/dev.gyp:nssdev',
- '<(DEPTH)/lib/pki/pki.gyp:nsspki',
- '<(DEPTH)/lib/ssl/ssl.gyp:ssl',
]
}
],
'target_defaults': {
'include_dirs': [
'../../gtests/google_test/gtest/include',
'../../gtests/common',
'../../lib/util'
--- a/security/nss/lib/certdb/alg1485.c
+++ b/security/nss/lib/certdb/alg1485.c
@@ -336,26 +336,23 @@ hexToBin(PLArenaPool* pool, SECItem* des
{
PRUint8* dest;
destItem->data = NULL;
if (len <= 0 || (len & 1)) {
goto loser;
}
len >>= 1;
- if (!SECITEM_AllocItem(pool, destItem, len)) {
+ if (!SECITEM_AllocItem(pool, destItem, len))
goto loser;
- }
dest = destItem->data;
for (; len > 0; len--, src += 2) {
- PRUint16 bin = ((PRUint16)x2b[(PRUint8)src[0]] << 4);
- bin |= (PRUint16)x2b[(PRUint8)src[1]];
- if (bin >> 15) { /* is negative */
+ PRInt16 bin = (x2b[(PRUint8)src[0]] << 4) | x2b[(PRUint8)src[1]];
+ if (bin < 0)
goto loser;
- }
*dest++ = (PRUint8)bin;
}
return SECSuccess;
loser:
if (!pool)
SECITEM_FreeItem(destItem, PR_FALSE);
return SECFailure;
}
--- a/security/nss/lib/certhigh/certhigh.c
+++ b/security/nss/lib/certhigh/certhigh.c
@@ -1075,20 +1075,17 @@ CERT_CertChainFromCert(CERTCertificate *
SECItem derCert;
CERTCertificate *cCert = STAN_GetCERTCertificate(stanCert);
if (!cCert) {
goto loser;
}
derCert.len = (unsigned int)stanCert->encoding.size;
derCert.data = (unsigned char *)stanCert->encoding.data;
derCert.type = siBuffer;
- if (SECITEM_CopyItem(arena, &chain->certs[i], &derCert) != SECSuccess) {
- CERT_DestroyCertificate(cCert);
- goto loser;
- }
+ SECITEM_CopyItem(arena, &chain->certs[i], &derCert);
stanCert = stanChain[++i];
if (!stanCert && !cCert->isRoot) {
/* reached the end of the chain, but the final cert is
* not a root. Don't discard it.
*/
includeRoot = PR_TRUE;
}
CERT_DestroyCertificate(cCert);
--- a/security/nss/lib/certhigh/ocsp.c
+++ b/security/nss/lib/certhigh/ocsp.c
@@ -2190,17 +2190,17 @@ CERT_CreateOCSPRequest(CERTCertList *cer
void
SetRequestExts(void *object, CERTCertExtension **exts)
{
CERTOCSPRequest *request = (CERTOCSPRequest *)object;
request->tbsRequest->requestExtensions = exts;
}
-#if defined(__GNUC__) && !defined(NSS_NO_GCC48)
+#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wvarargs"
#endif
SECStatus
CERT_AddOCSPAcceptableResponses(CERTOCSPRequest *request,
SECOidTag responseType0, ...)
{
void *extHandle;
@@ -2260,17 +2260,17 @@ CERT_AddOCSPAcceptableResponses(CERTOCSP
loser:
if (acceptableResponses != NULL)
PORT_Free(acceptableResponses);
if (extHandle != NULL)
(void)CERT_FinishExtensions(extHandle);
return rv;
}
-#if defined(__GNUC__) && !defined(NSS_NO_GCC48)
+#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
/*
* FUNCTION: CERT_DestroyOCSPRequest
* Frees an OCSP Request structure.
* INPUTS:
* CERTOCSPRequest *request
--- a/security/nss/lib/cryptohi/dsautil.c
+++ b/security/nss/lib/cryptohi/dsautil.c
@@ -161,38 +161,34 @@ common_EncodeDerSig(SECItem *dest, SECIt
** buffer containing the "raw" signature, which is len bytes of r,
** followed by len bytes of s. For DSA, len is the length of q.
** For ECDSA, len depends on the key size used to create the signature.
*/
static SECItem *
common_DecodeDerSig(const SECItem *item, unsigned int len)
{
SECItem *result = NULL;
- PORTCheapArenaPool arena;
SECStatus status;
DSA_ASN1Signature sig;
SECItem dst;
PORT_Memset(&sig, 0, sizeof(sig));
- /* Make enough room for r + s. */
- PORT_InitCheapArena(&arena, PR_MAX(2 * MAX_ECKEY_LEN, DSA_MAX_SIGNATURE_LEN));
-
result = PORT_ZNew(SECItem);
if (result == NULL)
goto loser;
result->len = 2 * len;
result->data = (unsigned char *)PORT_Alloc(2 * len);
if (result->data == NULL)
goto loser;
sig.r.type = siUnsignedInteger;
sig.s.type = siUnsignedInteger;
- status = SEC_QuickDERDecodeItem(&arena.arena, &sig, DSA_SignatureTemplate, item);
+ status = SEC_ASN1DecodeItem(NULL, &sig, DSA_SignatureTemplate, item);
if (status != SECSuccess)
goto loser;
/* Convert sig.r and sig.s from variable length signed integers to
** fixed length unsigned integers.
*/
dst.data = result->data;
dst.len = len;
@@ -201,17 +197,20 @@ common_DecodeDerSig(const SECItem *item,
goto loser;
dst.data += len;
status = DSAU_ConvertSignedToFixedUnsigned(&dst, &sig.s);
if (status != SECSuccess)
goto loser;
done:
- PORT_DestroyCheapArena(&arena);
+ if (sig.r.data != NULL)
+ PORT_Free(sig.r.data);
+ if (sig.s.data != NULL)
+ PORT_Free(sig.s.data);
return result;
loser:
if (result != NULL) {
SECITEM_FreeItem(result, PR_TRUE);
result = NULL;
}
--- a/security/nss/lib/cryptohi/seckey.c
+++ b/security/nss/lib/cryptohi/seckey.c
@@ -1237,32 +1237,16 @@ SECKEY_ConvertToPublicKey(SECKEYPrivateK
if (rv != SECSuccess)
break;
rv = PK11_ReadAttribute(privk->pkcs11Slot, privk->pkcs11ID,
CKA_PUBLIC_EXPONENT, arena, &pubk->u.rsa.publicExponent);
if (rv != SECSuccess)
break;
return pubk;
break;
- case ecKey:
- rv = PK11_ReadAttribute(privk->pkcs11Slot, privk->pkcs11ID,
- CKA_EC_PARAMS, arena, &pubk->u.ec.DEREncodedParams);
- if (rv != SECSuccess) {
- break;
- }
- rv = PK11_ReadAttribute(privk->pkcs11Slot, privk->pkcs11ID,
- CKA_EC_POINT, arena, &pubk->u.ec.publicValue);
- if (rv != SECSuccess || pubk->u.ec.publicValue.len == 0) {
- break;
- }
- rv = seckey_SetPointEncoding(arena, pubk);
- if (rv != SECSuccess) {
- break;
- }
- return pubk;
default:
break;
}
PORT_FreeArena(arena, PR_FALSE);
return NULL;
}
--- a/security/nss/lib/dev/devslot.c
+++ b/security/nss/lib/dev/devslot.c
@@ -86,28 +86,29 @@ nssSlot_GetTokenName(
NSS_IMPLEMENT void
nssSlot_ResetDelay(
NSSSlot *slot)
{
slot->lastTokenPing = 0;
}
static PRBool
-within_token_delay_period(const NSSSlot *slot)
+within_token_delay_period(NSSSlot *slot)
{
PRIntervalTime time, lastTime;
/* Set the delay time for checking the token presence */
if (s_token_delay_time == 0) {
s_token_delay_time = PR_SecondsToInterval(NSSSLOT_TOKEN_DELAY_TIME);
}
time = PR_IntervalNow();
lastTime = slot->lastTokenPing;
if ((lastTime) && ((time - lastTime) < s_token_delay_time)) {
return PR_TRUE;
}
+ slot->lastTokenPing = time;
return PR_FALSE;
}
NSS_IMPLEMENT PRBool
nssSlot_IsTokenPresent(
NSSSlot *slot)
{
CK_RV ckrv;
@@ -130,25 +131,23 @@ nssSlot_IsTokenPresent(
if (!epv) {
return PR_FALSE;
}
nssSlot_EnterMonitor(slot);
ckrv = CKAPI(epv)->C_GetSlotInfo(slot->slotID, &slotInfo);
nssSlot_ExitMonitor(slot);
if (ckrv != CKR_OK) {
slot->token->base.name[0] = 0; /* XXX */
- slot->lastTokenPing = PR_IntervalNow();
return PR_FALSE;
}
slot->ckFlags = slotInfo.flags;
/* check for the presence of the token */
if ((slot->ckFlags & CKF_TOKEN_PRESENT) == 0) {
if (!slot->token) {
/* token was never present */
- slot->lastTokenPing = PR_IntervalNow();
return PR_FALSE;
}
session = nssToken_GetDefaultSession(slot->token);
if (session) {
nssSession_EnterMonitor(session);
/* token is not present */
if (session->handle != CK_INVALID_SESSION) {
/* session is valid, close and invalidate it */
@@ -161,17 +160,16 @@ nssSlot_IsTokenPresent(
if (slot->token->base.name[0] != 0) {
/* notify the high-level cache that the token is removed */
slot->token->base.name[0] = 0; /* XXX */
nssToken_NotifyCertsNotVisible(slot->token);
}
slot->token->base.name[0] = 0; /* XXX */
/* clear the token cache */
nssToken_Remove(slot->token);
- slot->lastTokenPing = PR_IntervalNow();
return PR_FALSE;
}
/* token is present, use the session info to determine if the card
* has been removed and reinserted.
*/
session = nssToken_GetDefaultSession(slot->token);
if (session) {
PRBool isPresent = PR_FALSE;
@@ -184,37 +182,32 @@ nssSlot_IsTokenPresent(
CKAPI(epv)
->C_CloseSession(session->handle);
session->handle = CK_INVALID_SESSION;
}
}
isPresent = session->handle != CK_INVALID_SESSION;
nssSession_ExitMonitor(session);
/* token not removed, finished */
- if (isPresent) {
- slot->lastTokenPing = PR_IntervalNow();
+ if (isPresent)
return PR_TRUE;
- }
}
/* the token has been removed, and reinserted, or the slot contains
* a token it doesn't recognize. invalidate all the old
* information we had on this token, if we can't refresh, clear
* the present flag */
nssToken_NotifyCertsNotVisible(slot->token);
nssToken_Remove(slot->token);
/* token has been removed, need to refresh with new session */
nssrv = nssSlot_Refresh(slot);
if (nssrv != PR_SUCCESS) {
slot->token->base.name[0] = 0; /* XXX */
slot->ckFlags &= ~CKF_TOKEN_PRESENT;
- /* TODO: insert a barrier here to avoid reordering of the assingments */
- slot->lastTokenPing = PR_IntervalNow();
return PR_FALSE;
}
- slot->lastTokenPing = PR_IntervalNow();
return PR_TRUE;
}
NSS_IMPLEMENT void *
nssSlot_GetCryptokiEPV(
NSSSlot *slot)
{
return slot->epv;
--- a/security/nss/lib/freebl/Makefile
+++ b/security/nss/lib/freebl/Makefile
@@ -596,17 +596,17 @@ ECL_USERS = ec.c
ECL_OBJS = $(addprefix $(OBJDIR)/$(PROG_PREFIX), $(ECL_SRCS:.c=$(OBJ_SUFFIX)) $(ECL_ASM_SRCS:$(ASM_SUFFIX)=$(OBJ_SUFFIX)))
ECL_OBJS += $(addprefix $(OBJDIR)/$(PROG_PREFIX), $(ECL_USERS:.c=$(OBJ_SUFFIX)))
$(ECL_OBJS): $(ECL_HDRS)
-$(OBJDIR)/sysrand$(OBJ_SUFFIX): sysrand.c unix_rand.c win_rand.c
+$(OBJDIR)/sysrand$(OBJ_SUFFIX): sysrand.c unix_rand.c win_rand.c os2_rand.c
$(OBJDIR)/$(PROG_PREFIX)mpprime$(OBJ_SUFFIX): primes.c
$(OBJDIR)/ldvector$(OBJ_SUFFIX) $(OBJDIR)/loader$(OBJ_SUFFIX) : loader.h
ifeq ($(SYSV_SPARC),1)
$(OBJDIR)/mpv_sparcv8.o $(OBJDIR)/mpv_sparcv8x.o $(OBJDIR)/montmulfv8.o : $(OBJDIR)/%.o : %.s
--- a/security/nss/lib/freebl/drbg.c
+++ b/security/nss/lib/freebl/drbg.c
@@ -393,37 +393,34 @@ prng_generateNewBytes(RNGContext *rng,
* threads, creating a race condition.
*/
static const PRCallOnceType pristineCallOnce;
static PRCallOnceType coRNGInit;
static PRStatus
rng_init(void)
{
PRUint8 bytes[PRNG_SEEDLEN * 2]; /* entropy + nonce */
-#ifndef UNSAFE_FUZZER_MODE
unsigned int numBytes;
SECStatus rv = SECSuccess;
-#endif
if (globalrng == NULL) {
/* bytes needs to have enough space to hold
* a SHA256 hash value. Blow up at compile time if this isn't true */
PR_STATIC_ASSERT(sizeof(bytes) >= SHA256_LENGTH);
/* create a new global RNG context */
globalrng = &theGlobalRng;
PORT_Assert(NULL == globalrng->lock);
/* create a lock for it */
globalrng->lock = PZ_NewLock(nssILockOther);
if (globalrng->lock == NULL) {
globalrng = NULL;
PORT_SetError(PR_OUT_OF_MEMORY_ERROR);
return PR_FAILURE;
}
-#ifndef UNSAFE_FUZZER_MODE
/* Try to get some seed data for the RNG */
numBytes = (unsigned int)RNG_SystemRNG(bytes, sizeof bytes);
PORT_Assert(numBytes == 0 || numBytes == sizeof bytes);
if (numBytes != 0) {
/* if this is our first call, instantiate, otherwise reseed
* prng_instantiate gets a new clean state, we want to mix
* any previous entropy we may have collected */
if (V(globalrng)[0] == 0) {
@@ -433,21 +430,20 @@ rng_init(void)
}
memset(bytes, 0, numBytes);
} else {
PZ_DestroyLock(globalrng->lock);
globalrng->lock = NULL;
globalrng = NULL;
return PR_FAILURE;
}
+
if (rv != SECSuccess) {
return PR_FAILURE;
}
-#endif
-
/* the RNG is in a valid state */
globalrng->isValid = PR_TRUE;
/* fetch one random value so that we can populate rng->oldV for our
* continous random number test. */
prng_generateNewBytes(globalrng, bytes, SHA256_LENGTH, NULL, 0);
/* Fetch more entropy into the PRNG */
--- a/security/nss/lib/freebl/ec.c
+++ b/security/nss/lib/freebl/ec.c
@@ -561,40 +561,35 @@ ECDH_Derive(SECItem *publicValue,
#endif
if (!publicValue || !ecParams || !privateValue || !derivedSecret ||
!ecParams->name) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
- /*
- * Make sure the point is on the requested curve to avoid
- * certain small subgroup attacks.
- */
- if (EC_ValidatePublicKey(ecParams, publicValue) != SECSuccess) {
- PORT_SetError(SEC_ERROR_BAD_KEY);
- return SECFailure;
- }
-
/* Perform curve specific multiplication using ECMethod */
if (ecParams->fieldID.type == ec_field_plain) {
const ECMethod *method;
memset(derivedSecret, 0, sizeof(*derivedSecret));
derivedSecret = SECITEM_AllocItem(NULL, derivedSecret, ecParams->pointSize);
if (derivedSecret == NULL) {
PORT_SetError(SEC_ERROR_NO_MEMORY);
return SECFailure;
}
method = ec_get_method_from_name(ecParams->name);
if (method == NULL || method->validate == NULL ||
method->mul == NULL) {
PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE);
return SECFailure;
}
+ if (method->validate(publicValue) != SECSuccess) {
+ PORT_SetError(SEC_ERROR_BAD_KEY);
+ return SECFailure;
+ }
return method->mul(derivedSecret, privateValue, publicValue);
}
/*
* We fail if the public value is the point at infinity, since
* this produces predictable results.
*/
if (ec_point_at_infinity(publicValue)) {
@@ -1002,24 +997,19 @@ ECDSA_VerifyDigest(ECPublicKey *key, con
olen = ecParams->order.len;
if (signature->len == 0 || signature->len % 2 != 0 ||
signature->len > 2 * olen) {
PORT_SetError(SEC_ERROR_INPUT_LEN);
goto cleanup;
}
slen = signature->len / 2;
- /*
- * The incoming point has been verified in sftk_handlePublicKeyObject.
- */
-
SECITEM_AllocItem(NULL, &pointC, ecParams->pointSize);
- if (pointC.data == NULL) {
+ if (pointC.data == NULL)
goto cleanup;
- }
CHECK_MPI_OK(mp_init(&r_));
CHECK_MPI_OK(mp_init(&s_));
CHECK_MPI_OK(mp_init(&c));
CHECK_MPI_OK(mp_init(&u1));
CHECK_MPI_OK(mp_init(&u2));
CHECK_MPI_OK(mp_init(&x1));
CHECK_MPI_OK(mp_init(&v));
--- a/security/nss/lib/freebl/ecl/README
+++ b/security/nss/lib/freebl/ecl/README
@@ -85,16 +85,30 @@ y=Y/Z^3).
ecp_jm.c provides point arithmetic using Modified Jacobian
coordinates and mixed Modified_Jacobian-affine coordinates.
(Modified Jacobian coordinates represent a point (x, y)
as (X, Y, Z, a*Z^4), where x=X/Z^2, y=Y/Z^3, and a is
the linear coefficient in the curve defining equation).
ecp_192.c and ecp_224.c provide optimized field arithmetic.
+Point Arithmetic over Binary Polynomial Fields
+----------------------------------------------
+
+ec2_aff.c provides point arithmetic using affine coordinates.
+
+ec2_proj.c provides point arithmetic using projective coordinates.
+(Projective coordinates represent a point (x, y) as (X, Y, Z), where
+x=X/Z, y=Y/Z^2).
+
+ec2_mont.c provides point multiplication using Montgomery projective
+coordinates.
+
+ec2_163.c, ec2_193.c, and ec2_233.c provide optimized field arithmetic.
+
Field Arithmetic
----------------
ecl_gf.c provides constructors for field objects (GFMethod) with the
functions GFMethod_cons*. It also provides wrappers around the basic
field operations.
Prime Field Arithmetic
@@ -107,16 +121,28 @@ functions from the mpi library and adds
It also provides the function to construct a GFMethod object using
Montgomery multiplication.
ecp_192.c and ecp_224.c provide optimized modular reduction for the
fields defined by nistp192 and nistp224 primes.
ecl_gf.c provides wrappers around the basic field operations.
+Binary Polynomial Field Arithmetic
+----------------------------------
+
+../mpi/mp_gf2m.c provides basic binary polynomial field arithmetic,
+including addition, multiplication, squaring, mod, and division, as well
+as conversion ob polynomial representations between bitstring and int[].
+
+ec2_163.c, ec2_193.c, and ec2_233.c provide optimized field mod, mul,
+and sqr operations.
+
+ecl_gf.c provides wrappers around the basic field operations.
+
Field Encoding
--------------
By default, field elements are encoded in their basic form. It is
possible to use an alternative encoding, however. For example, it is
possible to Montgomery representation of prime field elements and
take advantage of the fast modular multiplication that Montgomery
representation provides. The process of converting from basic form to
@@ -156,8 +182,86 @@ multiplication using Jacobian coordinate
(Wiring in function ECGroup_consGFp_mont in ecl.c.)
Curves over prime fields that have optimized modular reduction (i.e.,
secp160r1, nistp192, and nistp224) do not use Montgomery field
arithmetic. Instead, they use basic field arithmetic with their
optimized reduction (as in ecp_192.c and ecp_224.c). They
use the same point multiplication and simultaneous point multiplication
algorithms as other curves over prime fields.
+
+Curves over binary polynomial fields by default use generic field
+arithmetic with montgomery point multiplication and basic kP + lQ
+computation (multiply, multiply, and add). (Wiring in function
+ECGroup_cons_GF2m in ecl.c.)
+
+Curves over binary polynomial fields that have optimized field
+arithmetic (i.e., any 163-, 193, or 233-bit field) use their optimized
+field arithmetic. They use the same point multiplication and
+simultaneous point multiplication algorithms as other curves over binary
+fields.
+
+Example
+-------
+
+We provide an example for plugging in an optimized implementation for
+the Koblitz curve nistk163.
+
+Suppose the file ec2_k163.c contains the optimized implementation. In
+particular it contains a point multiplication function:
+
+ mp_err ec_GF2m_nistk163_pt_mul(const mp_int *n, const mp_int *px,
+ const mp_int *py, mp_int *rx, mp_int *ry, const ECGroup *group);
+
+Since only a pt_mul function is provided, the generic pt_add function
+will be used.
+
+There are two options for handling the optimized field arithmetic used
+by the ..._pt_mul function. Say the optimized field arithmetic includes
+the following functions:
+
+ mp_err ec_GF2m_nistk163_add(const mp_int *a, const mp_int *b,
+ mp_int *r, const GFMethod *meth);
+ mp_err ec_GF2m_nistk163_mul(const mp_int *a, const mp_int *b,
+ mp_int *r, const GFMethod *meth);
+ mp_err ec_GF2m_nistk163_sqr(const mp_int *a, const mp_int *b,
+ mp_int *r, const GFMethod *meth);
+ mp_err ec_GF2m_nistk163_div(const mp_int *a, const mp_int *b,
+ mp_int *r, const GFMethod *meth);
+
+First, the optimized field arithmetic could simply be called directly
+by the ..._pt_mul function. This would be accomplished by changing
+the ecgroup_fromNameAndHex function in ecl.c to include the following
+statements:
+
+ if (name == ECCurve_NIST_K163) {
+ group = ECGroup_consGF2m(&irr, NULL, &curvea, &curveb, &genx,
+ &geny, &order, params->cofactor);
+ if (group == NULL) { res = MP_UNDEF; goto CLEANUP; }
+ MP_CHECKOK( ec_group_set_nistk163(group) );
+ }
+
+and including in ec2_k163.c the following function:
+
+ mp_err ec_group_set_nistk163(ECGroup *group) {
+ group->point_mul = &ec_GF2m_nistk163_pt_mul;
+ return MP_OKAY;
+ }
+
+As a result, ec_GF2m_pt_add and similar functions would use the
+basic binary polynomial field arithmetic ec_GF2m_add, ec_GF2m_mul,
+ec_GF2m_sqr, and ec_GF2m_div.
+
+Alternatively, the optimized field arithmetic could be wired into the
+group's GFMethod. This would be accomplished by putting the following
+function in ec2_k163.c:
+
+ mp_err ec_group_set_nistk163(ECGroup *group) {
+ group->meth->field_add = &ec_GF2m_nistk163_add;
+ group->meth->field_mul = &ec_GF2m_nistk163_mul;
+ group->meth->field_sqr = &ec_GF2m_nistk163_sqr;
+ group->meth->field_div = &ec_GF2m_nistk163_div;
+ group->point_mul = &ec_GF2m_nistk163_pt_mul;
+ return MP_OKAY;
+ }
+
+For an example of functions that use special field encodings, take a
+look at ecp_mont.c.
new file mode 100644
--- /dev/null
+++ b/security/nss/lib/freebl/ecl/tests/ec_naft.c
@@ -0,0 +1,121 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mpi.h"
+#include "mplogic.h"
+#include "ecl.h"
+#include "ecp.h"
+#include "ecl-priv.h"
+
+#include <sys/types.h>
+#include <stdio.h>
+#include <time.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+
+/* Returns 2^e as an integer. This is meant to be used for small powers of
+ * two. */
+int ec_twoTo(int e);
+
+/* Number of bits of scalar to test */
+#define BITSIZE 160
+
+/* Time k repetitions of operation op. */
+#define M_TimeOperation(op, k) \
+ { \
+ double dStart, dNow, dUserTime; \
+ struct rusage ru; \
+ int i; \
+ getrusage(RUSAGE_SELF, &ru); \
+ dStart = (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec * 0.000001; \
+ for (i = 0; i < k; i++) { \
+ { \
+ op; \
+ } \
+ }; \
+ getrusage(RUSAGE_SELF, &ru); \
+ dNow = (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec * 0.000001; \
+ dUserTime = dNow - dStart; \
+ if (dUserTime) \
+ printf(" %-45s\n k: %6i, t: %6.2f sec\n", #op, k, dUserTime); \
+ }
+
+/* Tests wNAF computation. Non-adjacent-form is discussed in the paper: D.
+ * Hankerson, J. Hernandez and A. Menezes, "Software implementation of
+ * elliptic curve cryptography over binary fields", Proc. CHES 2000. */
+
+mp_err
+main(void)
+{
+ signed char naf[BITSIZE + 1];
+ ECGroup *group = NULL;
+ mp_int k;
+ mp_int *scalar;
+ int i, count;
+ int res;
+ int w = 5;
+ char s[1000];
+
+ /* Get a 160 bit scalar to compute wNAF from */
+ group = ECGroup_fromName(ECCurve_SECG_PRIME_160R1);
+ scalar = &group->genx;
+
+ /* Compute wNAF representation of scalar */
+ ec_compute_wNAF(naf, BITSIZE, scalar, w);
+
+ /* Verify correctness of representation */
+ mp_init(&k); /* init k to 0 */
+
+ for (i = BITSIZE; i >= 0; i--) {
+ mp_add(&k, &k, &k);
+ /* digits in mp_???_d are unsigned */
+ if (naf[i] >= 0) {
+ mp_add_d(&k, naf[i], &k);
+ } else {
+ mp_sub_d(&k, -naf[i], &k);
+ }
+ }
+
+ if (mp_cmp(&k, scalar) != 0) {
+ printf("Error: incorrect NAF value.\n");
+ MP_CHECKOK(mp_toradix(&k, s, 16));
+ printf("NAF value %s\n", s);
+ MP_CHECKOK(mp_toradix(scalar, s, 16));
+ printf("original value %s\n", s);
+ goto CLEANUP;
+ }
+
+ /* Verify digits of representation are valid */
+ for (i = 0; i <= BITSIZE; i++) {
+ if (naf[i] % 2 == 0 && naf[i] != 0) {
+ printf("Error: Even non-zero digit found.\n");
+ goto CLEANUP;
+ }
+ if (naf[i] < -(ec_twoTo(w - 1)) || naf[i] >= ec_twoTo(w - 1)) {
+ printf("Error: Magnitude of naf digit too large.\n");
+ goto CLEANUP;
+ }
+ }
+
+ /* Verify sparsity of representation */
+ count = w - 1;
+ for (i = 0; i <= BITSIZE; i++) {
+ if (naf[i] != 0) {
+ if (count < w - 1) {
+ printf("Error: Sparsity failed.\n");
+ goto CLEANUP;
+ }
+ count = 0;
+ } else
+ count++;
+ }
+
+ /* Check timing */
+ M_TimeOperation(ec_compute_wNAF(naf, BITSIZE, scalar, w), 10000);
+
+ printf("Test passed.\n");
+CLEANUP:
+ ECGroup_free(group);
+ return MP_OKAY;
+}
new file mode 100644
--- /dev/null
+++ b/security/nss/lib/freebl/ecl/tests/ecp_test.c
@@ -0,0 +1,409 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mpi.h"
+#include "mplogic.h"
+#include "mpprime.h"
+#include "ecl.h"
+#include "ecl-curve.h"
+#include "ecp.h"
+#include <stdio.h>
+#include <strings.h>
+#include <assert.h>
+
+#include <time.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+
+/* Time k repetitions of operation op. */
+#define M_TimeOperation(op, k) \
+ { \
+ double dStart, dNow, dUserTime; \
+ struct rusage ru; \
+ int i; \
+ getrusage(RUSAGE_SELF, &ru); \
+ dStart = (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec * 0.000001; \
+ for (i = 0; i < k; i++) { \
+ { \
+ op; \
+ } \
+ }; \
+ getrusage(RUSAGE_SELF, &ru); \
+ dNow = (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec * 0.000001; \
+ dUserTime = dNow - dStart; \
+ if (dUserTime) \
+ printf(" %-45s k: %6i, t: %6.2f sec\n", #op, k, dUserTime); \
+ }
+
+/* Test curve using generic field arithmetic. */
+#define ECTEST_GENERIC_GFP(name_c, name) \
+ printf("Testing %s using generic implementation...\n", name_c); \
+ params = EC_GetNamedCurveParams(name); \
+ if (params == NULL) { \
+ printf(" Error: could not construct params.\n"); \
+ res = MP_NO; \
+ goto CLEANUP; \
+ } \
+ ECGroup_free(group); \
+ group = ECGroup_fromHex(params); \
+ if (group == NULL) { \
+ printf(" Error: could not construct group.\n"); \
+ res = MP_NO; \
+ goto CLEANUP; \
+ } \
+ MP_CHECKOK(ectest_curve_GFp(group, ectestPrint, ectestTime, 1)); \
+ printf("... okay.\n");
+
+/* Test curve using specific field arithmetic. */
+#define ECTEST_NAMED_GFP(name_c, name) \
+ printf("Testing %s using specific implementation...\n", name_c); \
+ ECGroup_free(group); \
+ group = ECGroup_fromName(name); \
+ if (group == NULL) { \
+ printf(" Warning: could not construct group.\n"); \
+ printf("... failed; continuing with remaining tests.\n"); \
+ } else { \
+ MP_CHECKOK(ectest_curve_GFp(group, ectestPrint, ectestTime, 0)); \
+ printf("... okay.\n"); \
+ }
+
+/* Performs basic tests of elliptic curve cryptography over prime fields.
+ * If tests fail, then it prints an error message, aborts, and returns an
+ * error code. Otherwise, returns 0. */
+int
+ectest_curve_GFp(ECGroup *group, int ectestPrint, int ectestTime,
+ int generic)
+{
+
+ mp_int one, order_1, gx, gy, rx, ry, n;
+ int size;
+ mp_err res;
+ char s[1000];
+
+ /* initialize values */
+ MP_CHECKOK(mp_init(&one));
+ MP_CHECKOK(mp_init(&order_1));
+ MP_CHECKOK(mp_init(&gx));
+ MP_CHECKOK(mp_init(&gy));
+ MP_CHECKOK(mp_init(&rx));
+ MP_CHECKOK(mp_init(&ry));
+ MP_CHECKOK(mp_init(&n));
+
+ MP_CHECKOK(mp_set_int(&one, 1));
+ MP_CHECKOK(mp_sub(&group->order, &one, &order_1));
+
+ /* encode base point */
+ if (group->meth->field_dec) {
+ MP_CHECKOK(group->meth->field_dec(&group->genx, &gx, group->meth));
+ MP_CHECKOK(group->meth->field_dec(&group->geny, &gy, group->meth));
+ } else {
+ MP_CHECKOK(mp_copy(&group->genx, &gx));
+ MP_CHECKOK(mp_copy(&group->geny, &gy));
+ }
+ if (ectestPrint) {
+ /* output base point */
+ printf(" base point P:\n");
+ MP_CHECKOK(mp_toradix(&gx, s, 16));
+ printf(" %s\n", s);
+ MP_CHECKOK(mp_toradix(&gy, s, 16));
+ printf(" %s\n", s);
+ if (group->meth->field_enc) {
+ printf(" base point P (encoded):\n");
+ MP_CHECKOK(mp_toradix(&group->genx, s, 16));
+ printf(" %s\n", s);
+ MP_CHECKOK(mp_toradix(&group->geny, s, 16));
+ printf(" %s\n", s);
+ }
+ }
+
+#ifdef ECL_ENABLE_GFP_PT_MUL_AFF
+ /* multiply base point by order - 1 and check for negative of base
+ * point */
+ MP_CHECKOK(ec_GFp_pt_mul_aff(&order_1, &group->genx, &group->geny, &rx, &ry, group));
+ if (ectestPrint) {
+ printf(" (order-1)*P (affine):\n");
+ MP_CHECKOK(mp_toradix(&rx, s, 16));
+ printf(" %s\n", s);
+ MP_CHECKOK(mp_toradix(&ry, s, 16));
+ printf(" %s\n", s);
+ }
+ MP_CHECKOK(group->meth->field_neg(&ry, &ry, group->meth));
+ if ((mp_cmp(&rx, &group->genx) != 0) || (mp_cmp(&ry, &group->geny) != 0)) {
+ printf(" Error: invalid result (expected (- base point)).\n");
+ res = MP_NO;
+ goto CLEANUP;
+ }
+#endif
+
+#ifdef ECL_ENABLE_GFP_PT_MUL_AFF
+ /* multiply base point by order - 1 and check for negative of base
+ * point */
+ MP_CHECKOK(ec_GFp_pt_mul_jac(&order_1, &group->genx, &group->geny, &rx, &ry, group));
+ if (ectestPrint) {
+ printf(" (order-1)*P (jacobian):\n");
+ MP_CHECKOK(mp_toradix(&rx, s, 16));
+ printf(" %s\n", s);
+ MP_CHECKOK(mp_toradix(&ry, s, 16));
+ printf(" %s\n", s);
+ }
+ MP_CHECKOK(group->meth->field_neg(&ry, &ry, group->meth));
+ if ((mp_cmp(&rx, &group->genx) != 0) || (mp_cmp(&ry, &group->geny) != 0)) {
+ printf(" Error: invalid result (expected (- base point)).\n");
+ res = MP_NO;
+ goto CLEANUP;
+ }
+#endif
+
+ /* multiply base point by order - 1 and check for negative of base
+ * point */
+ MP_CHECKOK(ECPoint_mul(group, &order_1, NULL, NULL, &rx, &ry));
+ if (ectestPrint) {
+ printf(" (order-1)*P (ECPoint_mul):\n");
+ MP_CHECKOK(mp_toradix(&rx, s, 16));
+ printf(" %s\n", s);
+ MP_CHECKOK(mp_toradix(&ry, s, 16));
+ printf(" %s\n", s);
+ }
+ MP_CHECKOK(mp_submod(&group->meth->irr, &ry, &group->meth->irr, &ry));
+ if ((mp_cmp(&rx, &gx) != 0) || (mp_cmp(&ry, &gy) != 0)) {
+ printf(" Error: invalid result (expected (- base point)).\n");
+ res = MP_NO;
+ goto CLEANUP;
+ }
+
+ /* multiply base point by order - 1 and check for negative of base
+ * point */
+ MP_CHECKOK(ECPoint_mul(group, &order_1, &gx, &gy, &rx, &ry));
+ if (ectestPrint) {
+ printf(" (order-1)*P (ECPoint_mul):\n");
+ MP_CHECKOK(mp_toradix(&rx, s, 16));
+ printf(" %s\n", s);
+ MP_CHECKOK(mp_toradix(&ry, s, 16));
+ printf(" %s\n", s);
+ }
+ MP_CHECKOK(mp_submod(&group->meth->irr, &ry, &group->meth->irr, &ry));
+ if ((mp_cmp(&rx, &gx) != 0) || (mp_cmp(&ry, &gy) != 0)) {
+ printf(" Error: invalid result (expected (- base point)).\n");
+ res = MP_NO;
+ goto CLEANUP;
+ }
+
+#ifdef ECL_ENABLE_GFP_PT_MUL_AFF
+ /* multiply base point by order and check for point at infinity */
+ MP_CHECKOK(ec_GFp_pt_mul_aff(&group->order, &group->genx, &group->geny, &rx, &ry,
+ group));
+ if (ectestPrint) {
+ printf(" (order)*P (affine):\n");
+ MP_CHECKOK(mp_toradix(&rx, s, 16));
+ printf(" %s\n", s);
+ MP_CHECKOK(mp_toradix(&ry, s, 16));
+ printf(" %s\n", s);
+ }
+ if (ec_GFp_pt_is_inf_aff(&rx, &ry) != MP_YES) {
+ printf(" Error: invalid result (expected point at infinity).\n");
+ res = MP_NO;
+ goto CLEANUP;
+ }
+#endif
+
+#ifdef ECL_ENABLE_GFP_PT_MUL_JAC
+ /* multiply base point by order and check for point at infinity */
+ MP_CHECKOK(ec_GFp_pt_mul_jac(&group->order, &group->genx, &group->geny, &rx, &ry,
+ group));
+ if (ectestPrint) {
+ printf(" (order)*P (jacobian):\n");
+ MP_CHECKOK(mp_toradix(&rx, s, 16));
+ printf(" %s\n", s);
+ MP_CHECKOK(mp_toradix(&ry, s, 16));
+ printf(" %s\n", s);
+ }
+ if (ec_GFp_pt_is_inf_aff(&rx, &ry) != MP_YES) {
+ printf(" Error: invalid result (expected point at infinity).\n");
+ res = MP_NO;
+ goto CLEANUP;
+ }
+#endif
+
+ /* multiply base point by order and check for point at infinity */
+ MP_CHECKOK(ECPoint_mul(group, &group->order, NULL, NULL, &rx, &ry));
+ if (ectestPrint) {
+ printf(" (order)*P (ECPoint_mul):\n");
+ MP_CHECKOK(mp_toradix(&rx, s, 16));
+ printf(" %s\n", s);
+ MP_CHECKOK(mp_toradix(&ry, s, 16));
+ printf(" %s\n", s);
+ }
+ if (ec_GFp_pt_is_inf_aff(&rx, &ry) != MP_YES) {
+ printf(" Error: invalid result (expected point at infinity).\n");
+ res = MP_NO;
+ goto CLEANUP;
+ }
+
+ /* multiply base point by order and check for point at infinity */
+ MP_CHECKOK(ECPoint_mul(group, &group->order, &gx, &gy, &rx, &ry));
+ if (ectestPrint) {
+ printf(" (order)*P (ECPoint_mul):\n");
+ MP_CHECKOK(mp_toradix(&rx, s, 16));
+ printf(" %s\n", s);
+ MP_CHECKOK(mp_toradix(&ry, s, 16));
+ printf(" %s\n", s);
+ }
+ if (ec_GFp_pt_is_inf_aff(&rx, &ry) != MP_YES) {
+ printf(" Error: invalid result (expected point at infinity).\n");
+ res = MP_NO;
+ goto CLEANUP;
+ }
+
+ /* check that (order-1)P + (order-1)P + P == (order-1)P */
+ MP_CHECKOK(ECPoints_mul(group, &order_1, &order_1, &gx, &gy, &rx, &ry));
+ MP_CHECKOK(ECPoints_mul(group, &one, &one, &rx, &ry, &rx, &ry));
+ if (ectestPrint) {
+ printf(" (order-1)*P + (order-1)*P + P == (order-1)*P (ECPoints_mul):\n");
+ MP_CHECKOK(mp_toradix(&rx, s, 16));
+ printf(" %s\n", s);
+ MP_CHECKOK(mp_toradix(&ry, s, 16));
+ printf(" %s\n", s);
+ }
+ MP_CHECKOK(mp_submod(&group->meth->irr, &ry, &group->meth->irr, &ry));
+ if ((mp_cmp(&rx, &gx) != 0) || (mp_cmp(&ry, &gy) != 0)) {
+ printf(" Error: invalid result (expected (- base point)).\n");
+ res = MP_NO;
+ goto CLEANUP;
+ }
+
+ /* test validate_point function */
+ if (ECPoint_validate(group, &gx, &gy) != MP_YES) {
+ printf(" Error: validate point on base point failed.\n");
+ res = MP_NO;
+ goto CLEANUP;
+ }
+ MP_CHECKOK(mp_add_d(&gy, 1, &ry));
+ if (ECPoint_validate(group, &gx, &ry) != MP_NO) {
+ printf(" Error: validate point on invalid point passed.\n");
+ res = MP_NO;
+ goto CLEANUP;
+ }
+
+ if (ectestTime) {
+ /* compute random scalar */
+ size = mpl_significant_bits(&group->meth->irr);
+ if (size < MP_OKAY) {
+ goto CLEANUP;
+ }
+ MP_CHECKOK(mpp_random_size(&n, (size + ECL_BITS - 1) / ECL_BITS));
+ MP_CHECKOK(group->meth->field_mod(&n, &n, group->meth));
+ /* timed test */
+ if (generic) {
+#ifdef ECL_ENABLE_GFP_PT_MUL_AFF
+ M_TimeOperation(MP_CHECKOK(ec_GFp_pt_mul_aff(&n, &group->genx, &group->geny, &rx, &ry,
+ group)),
+ 100);
+#endif
+ M_TimeOperation(MP_CHECKOK(ECPoint_mul(group, &n, NULL, NULL, &rx, &ry)),
+ 100);
+ M_TimeOperation(MP_CHECKOK(ECPoints_mul(group, &n, &n, &gx, &gy, &rx, &ry)), 100);
+ } else {
+ M_TimeOperation(MP_CHECKOK(ECPoint_mul(group, &n, NULL, NULL, &rx, &ry)),
+ 100);
+ M_TimeOperation(MP_CHECKOK(ECPoint_mul(group, &n, &gx, &gy, &rx, &ry)),
+ 100);
+ M_TimeOperation(MP_CHECKOK(ECPoints_mul(group, &n, &n, &gx, &gy, &rx, &ry)), 100);
+ }
+ }
+
+CLEANUP:
+ mp_clear(&one);
+ mp_clear(&order_1);
+ mp_clear(&gx);
+ mp_clear(&gy);
+ mp_clear(&rx);
+ mp_clear(&ry);
+ mp_clear(&n);
+ if (res != MP_OKAY) {
+ printf(" Error: exiting with error value %i\n", res);
+ }
+ return res;
+}
+
+/* Prints help information. */
+void
+printUsage()
+{
+ printf("Usage: ecp_test [--print] [--time]\n");
+ printf(" --print Print out results of each point arithmetic test.\n");
+ printf(" --time Benchmark point operations and print results.\n");
+}
+
+/* Performs tests of elliptic curve cryptography over prime fields If
+ * tests fail, then it prints an error message, aborts, and returns an
+ * error code. Otherwise, returns 0. */
+int
+main(int argv, char **argc)
+{
+
+ int ectestTime = 0;
+ int ectestPrint = 0;
+ int i;
+ ECGroup *group = NULL;
+ ECCurveParams *params = NULL;
+ mp_err res;
+
+ /* read command-line arguments */
+ for (i = 1; i < argv; i++) {
+ if ((strcasecmp(argc[i], "time") == 0) || (strcasecmp(argc[i], "-time") == 0) || (strcasecmp(argc[i], "--time") == 0)) {
+ ectestTime = 1;
+ } else if ((strcasecmp(argc[i], "print") == 0) || (strcasecmp(argc[i], "-print") == 0) || (strcasecmp(argc[i], "--print") == 0)) {
+ ectestPrint = 1;
+ } else {
+ printUsage();
+ return 0;
+ }
+ }
+
+ /* generic arithmetic tests */
+ ECTEST_GENERIC_GFP("SECP-160R1", ECCurve_SECG_PRIME_160R1);
+
+ /* specific arithmetic tests */
+ ECTEST_NAMED_GFP("NIST-P192", ECCurve_NIST_P192);
+ ECTEST_NAMED_GFP("NIST-P224", ECCurve_NIST_P224);
+ ECTEST_NAMED_GFP("NIST-P256", ECCurve_NIST_P256);
+ ECTEST_NAMED_GFP("NIST-P384", ECCurve_NIST_P384);
+ ECTEST_NAMED_GFP("NIST-P521", ECCurve_NIST_P521);
+ ECTEST_NAMED_GFP("ANSI X9.62 PRIME192v1", ECCurve_X9_62_PRIME_192V1);
+ ECTEST_NAMED_GFP("ANSI X9.62 PRIME192v2", ECCurve_X9_62_PRIME_192V2);
+ ECTEST_NAMED_GFP("ANSI X9.62 PRIME192v3", ECCurve_X9_62_PRIME_192V3);
+ ECTEST_NAMED_GFP("ANSI X9.62 PRIME239v1", ECCurve_X9_62_PRIME_239V1);
+ ECTEST_NAMED_GFP("ANSI X9.62 PRIME239v2", ECCurve_X9_62_PRIME_239V2);
+ ECTEST_NAMED_GFP("ANSI X9.62 PRIME239v3", ECCurve_X9_62_PRIME_239V3);
+ ECTEST_NAMED_GFP("ANSI X9.62 PRIME256v1", ECCurve_X9_62_PRIME_256V1);
+ ECTEST_NAMED_GFP("SECP-112R1", ECCurve_SECG_PRIME_112R1);
+ ECTEST_NAMED_GFP("SECP-112R2", ECCurve_SECG_PRIME_112R2);
+ ECTEST_NAMED_GFP("SECP-128R1", ECCurve_SECG_PRIME_128R1);
+ ECTEST_NAMED_GFP("SECP-128R2", ECCurve_SECG_PRIME_128R2);
+ ECTEST_NAMED_GFP("SECP-160K1", ECCurve_SECG_PRIME_160K1);
+ ECTEST_NAMED_GFP("SECP-160R1", ECCurve_SECG_PRIME_160R1);
+ ECTEST_NAMED_GFP("SECP-160R2", ECCurve_SECG_PRIME_160R2);
+ ECTEST_NAMED_GFP("SECP-192K1", ECCurve_SECG_PRIME_192K1);
+ ECTEST_NAMED_GFP("SECP-192R1", ECCurve_SECG_PRIME_192R1);
+ ECTEST_NAMED_GFP("SECP-224K1", ECCurve_SECG_PRIME_224K1);
+ ECTEST_NAMED_GFP("SECP-224R1", ECCurve_SECG_PRIME_224R1);
+ ECTEST_NAMED_GFP("SECP-256K1", ECCurve_SECG_PRIME_256K1);
+ ECTEST_NAMED_GFP("SECP-256R1", ECCurve_SECG_PRIME_256R1);
+ ECTEST_NAMED_GFP("SECP-384R1", ECCurve_SECG_PRIME_384R1);
+ ECTEST_NAMED_GFP("SECP-521R1", ECCurve_SECG_PRIME_521R1);
+ ECTEST_NAMED_GFP("WTLS-6 (112)", ECCurve_WTLS_6);
+ ECTEST_NAMED_GFP("WTLS-7 (160)", ECCurve_WTLS_7);
+ ECTEST_NAMED_GFP("WTLS-8 (112)", ECCurve_WTLS_8);
+ ECTEST_NAMED_GFP("WTLS-9 (160)", ECCurve_WTLS_9);
+ ECTEST_NAMED_GFP("WTLS-12 (224)", ECCurve_WTLS_12);
+ ECTEST_NAMED_GFP("Curve25519", ECCurve25519);
+
+CLEANUP:
+ EC_FreeCurveParams(params);
+ ECGroup_free(group);
+ if (res != MP_OKAY) {
+ printf("Error: exiting with error value %i\n", res);
+ }
+ return res;
+}
--- a/security/nss/lib/freebl/freebl.gyp
+++ b/security/nss/lib/freebl/freebl.gyp
@@ -27,98 +27,241 @@
'type': 'static_library',
'sources': [
'loader.c'
],
'dependencies': [
'<(DEPTH)/exports.gyp:nss_exports'
]
},
- # For test builds, build a static freebl library so we can statically
- # link it into the test build binary. This way we don't have to
- # dlopen() the shared lib but can directly call freebl functions.
{
- 'target_name': 'freebl_static',
- 'type': 'static_library',
- 'includes': [
- 'freebl_base.gypi',
- ],
- 'dependencies': [
- '<(DEPTH)/exports.gyp:nss_exports',
+ 'target_name': '<(freebl_name)',
+ 'type': 'shared_library',
+ 'sources': [
+ 'aeskeywrap.c',
+ 'alg2268.c',
+ 'alghmac.c',
+ 'arcfive.c',
+ 'arcfour.c',
+ 'camellia.c',
+ 'chacha20poly1305.c',
+ 'ctr.c',
+ 'cts.c',
+ 'des.c',
+ 'desblapi.c',
+ 'dh.c',
+ 'drbg.c',
+ 'dsa.c',
+ 'ec.c',
+ 'ecdecode.c',
+ 'ecl/ec_naf.c',
+ 'ecl/ecl.c',
+ 'ecl/ecl_curve.c',
+ 'ecl/ecl_gf.c',
+ 'ecl/ecl_mult.c',
+ 'ecl/ecp_25519.c',
+ 'ecl/ecp_256.c',
+ 'ecl/ecp_256_32.c',
+ 'ecl/ecp_384.c',
+ 'ecl/ecp_521.c',
+ 'ecl/ecp_aff.c',
+ 'ecl/ecp_jac.c',
+ 'ecl/ecp_jm.c',
+ 'ecl/ecp_mont.c',
+ 'fipsfreebl.c',
+ 'freeblver.c',
+ 'gcm.c',
+ 'hmacct.c',
+ 'jpake.c',
+ 'ldvector.c',
+ 'md2.c',
+ 'md5.c',
+ 'mpi/mp_gf2m.c',
+ 'mpi/mpcpucache.c',
+ 'mpi/mpi.c',
+ 'mpi/mplogic.c',
+ 'mpi/mpmontg.c',
+ 'mpi/mpprime.c',
+ 'pqg.c',
+ 'rawhash.c',
+ 'rijndael.c',
+ 'rsa.c',
+ 'rsapkcs.c',
+ 'seed.c',
+ 'sha512.c',
+ 'sha_fast.c',
+ 'shvfy.c',
+ 'sysrand.c',
+ 'tlsprfalg.c'
],
'conditions': [
[ 'OS=="linux"', {
- 'defines!': [
- 'FREEBL_NO_DEPEND',
- 'FREEBL_LOWHASH',
- 'USE_HW_AES',
- 'INTEL_GCM',
+ 'sources': [
+ 'nsslowhash.c',
+ 'stubs.c',
],
'conditions': [
+ [ 'test_build==1', {
+ 'dependencies': [
+ '<(DEPTH)/lib/util/util.gyp:nssutil3',
+ ],
+ }],
[ 'target_arch=="x64"', {
- # The AES assembler code doesn't work in static test builds.
- # The linker complains about non-relocatable code, and I
- # currently don't know how to fix this properly.
- 'sources!': [
+ 'sources': [
+ 'arcfour-amd64-gas.s',
'intel-aes.s',
'intel-gcm.s',
+ 'mpi/mpi_amd64.c',
+ 'mpi/mpi_amd64_gas.s',
+ 'mpi/mp_comba.c',
+ ],
+ 'dependencies': [
+ 'intel-gcm-wrap_c_lib',
+ ],
+ 'conditions': [
+ [ 'cc_is_clang==1', {
+ 'cflags': [
+ '-no-integrated-as',
+ ],
+ 'cflags_mozilla': [
+ '-no-integrated-as',
+ ],
+ 'asflags_mozilla': [
+ '-no-integrated-as',
+ ],
+ }],
+ ],
+ }],
+ [ 'target_arch=="ia32"', {
+ 'sources': [
+ 'mpi/mpi_x86.s',
+ ],
+ }],
+ [ 'target_arch=="arm"', {
+ 'sources': [
+ 'mpi/mpi_arm.c',
],
}],
],
- }],
- ],
- },
- {
- 'target_name': '<(freebl_name)',
- 'type': 'shared_library',
- 'includes': [
- 'freebl_base.gypi',
- ],
- 'dependencies': [
- '<(DEPTH)/exports.gyp:nss_exports',
- ],
- 'conditions': [
- [ 'OS!="linux" and OS!="android"', {
+ }, {
+ # not Linux
'conditions': [
[ 'moz_fold_libs==0', {
'dependencies': [
- '<(DEPTH)/lib/util/util.gyp:nssutil3',
+ '../util/util.gyp:nssutil3',
],
}, {
'libraries': [
'<(moz_folded_library_name)',
],
}],
],
- }, 'target_arch=="x64"', {
- 'dependencies': [
- 'intel-gcm-wrap_c_lib',
+ }],
+ [ 'OS=="win"', {
+ 'sources': [
+ #TODO: building with mingw should not need this.
+ 'ecl/uint128.c',
+ #TODO: clang-cl needs -msse3 here
+ 'intel-gcm-wrap.c',
+ ],
+ 'libraries': [
+ 'advapi32.lib',
+ ],
+ 'conditions': [
+ [ 'target_arch=="x64"', {
+ 'sources': [
+ 'arcfour-amd64-masm.asm',
+ 'mpi/mpi_amd64.c',
+ 'mpi/mpi_amd64_masm.asm',
+ 'mpi/mp_comba_amd64_masm.asm',
+ 'intel-aes-x64-masm.asm',
+ 'intel-gcm-x64-masm.asm',
+ ],
+ }, {
+ # not x64
+ 'sources': [
+ 'mpi/mpi_x86_asm.c',
+ 'intel-aes-x86-masm.asm',
+ 'intel-gcm-x86-masm.asm',
+ ],
+ }],
+ ],
+ }],
+ ['target_arch=="ia32" or target_arch=="x64"', {
+ 'sources': [
+ # All intel architectures get the 64 bit version
+ 'ecl/curve25519_64.c',
+ ],
+ }, {
+ 'sources': [
+ # All non intel architectures get the generic 32 bit implementation (slow!)
+ 'ecl/curve25519_32.c',
],
}],
- [ 'OS=="win" and cc_is_clang==1', {
- 'dependencies': [
- 'intel-gcm-wrap_c_lib',
+ #TODO uint128.c
+ [ 'disable_chachapoly==0', {
+ 'conditions': [
+ [ 'OS!="win" and target_arch=="x64"', {
+ 'sources': [
+ 'chacha20_vec.c',
+ 'poly1305-donna-x64-sse2-incremental-source.c',
+ ],
+ }, {
+ # not x64
+ 'sources': [
+ 'chacha20.c',
+ 'poly1305.c',
+ ],
+ }],
],
}],
- [ 'OS=="linux"', {
+ [ 'fuzz==1', {
'sources': [
- 'nsslowhash.c',
- 'stubs.c',
+ 'det_rng.c',
+ ],
+ 'defines': [
+ 'UNSAFE_FUZZER_MODE',
+ ],
+ }],
+ [ 'test_build==1', {
+ 'defines': [
+ 'CT_VERIF',
],
}],
+ [ 'OS=="mac"', {
+ 'conditions': [
+ [ 'target_arch=="ia32"', {
+ 'sources': [
+ 'mpi/mpi_sse2.s',
+ ],
+ 'defines': [
+ 'MP_USE_UINT_DIGIT',
+ 'MP_ASSEMBLY_MULTIPLY',
+ 'MP_ASSEMBLY_SQUARE',
+ 'MP_ASSEMBLY_DIV_2DX1D',
+ ],
+ }],
+ ],
+ }],
+ ],
+ 'dependencies': [
+ '<(DEPTH)/exports.gyp:nss_exports',
],
'variables': {
'conditions': [
[ 'OS=="linux"', {
'mapfile': 'freebl_hash_vector.def',
}, {
'mapfile': 'freebl.def',
}],
]
},
+ 'ldflags': [
+ '-Wl,-Bsymbolic'
+ ]
},
],
'conditions': [
[ 'OS=="linux"', {
# stub build
'targets': [
{
'target_name': 'freebl3',
@@ -211,31 +354,33 @@
'NSS_X86',
],
}],
],
}],
[ 'OS=="linux"', {
'defines': [
'FREEBL_LOWHASH',
- 'FREEBL_NO_DEPEND',
],
- }],
- [ 'OS=="linux" or OS=="android"', {
'conditions': [
+ [ 'test_build==0', {
+ 'defines': [
+ 'FREEBL_NO_DEPEND',
+ ],
+ }],
[ 'target_arch=="x64"', {
'defines': [
'MP_IS_LITTLE_ENDIAN',
'NSS_BEVAND_ARCFOUR',
'MPI_AMD64',
'MP_ASSEMBLY_MULTIPLY',
'NSS_USE_COMBA',
],
}],
- [ 'target_arch=="x64"', {
+ [ 'target_arch=="x64" and use_msan==0', {
'defines': [
'USE_HW_AES',
'INTEL_GCM',
],
}],
[ 'target_arch=="ia32"', {
'defines': [
'MP_IS_LITTLE_ENDIAN',
@@ -248,21 +393,16 @@
[ 'target_arch=="arm"', {
'defines': [
'MP_ASSEMBLY_MULTIPLY',
'MP_ASSEMBLY_SQUARE',
'MP_USE_UINT_DIGIT',
'SHA_NO_LONG_LONG',
],
}],
- [ 'target_arch=="arm64" or target_arch=="aarch64"', {
- 'defines': [
- 'NSS_USE_64',
- ],
- }],
],
}],
],
},
'variables': {
'module': 'nss',
}
}
deleted file mode 100644
--- a/security/nss/lib/freebl/freebl_base.gypi
+++ /dev/null
@@ -1,194 +0,0 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-{
- 'sources': [
- 'aeskeywrap.c',
- 'alg2268.c',
- 'alghmac.c',
- 'arcfive.c',
- 'arcfour.c',
- 'camellia.c',
- 'chacha20poly1305.c',
- 'ctr.c',
- 'cts.c',
- 'des.c',
- 'desblapi.c',
- 'dh.c',
- 'drbg.c',
- 'dsa.c',
- 'ec.c',
- 'ecdecode.c',
- 'ecl/ec_naf.c',
- 'ecl/ecl.c',
- 'ecl/ecl_curve.c',
- 'ecl/ecl_gf.c',
- 'ecl/ecl_mult.c',
- 'ecl/ecp_25519.c',
- 'ecl/ecp_256.c',
- 'ecl/ecp_256_32.c',
- 'ecl/ecp_384.c',
- 'ecl/ecp_521.c',
- 'ecl/ecp_aff.c',
- 'ecl/ecp_jac.c',
- 'ecl/ecp_jm.c',
- 'ecl/ecp_mont.c',
- 'fipsfreebl.c',
- 'freeblver.c',
- 'gcm.c',
- 'hmacct.c',
- 'jpake.c',
- 'ldvector.c',
- 'md2.c',
- 'md5.c',
- 'mpi/mp_gf2m.c',
- 'mpi/mpcpucache.c',
- 'mpi/mpi.c',
- 'mpi/mplogic.c',
- 'mpi/mpmontg.c',
- 'mpi/mpprime.c',
- 'pqg.c',
- 'rawhash.c',
- 'rijndael.c',
- 'rsa.c',
- 'rsapkcs.c',
- 'seed.c',
- 'sha512.c',
- 'sha_fast.c',
- 'shvfy.c',
- 'sysrand.c',
- 'tlsprfalg.c'
- ],
- 'conditions': [
- [ 'OS=="linux" or OS=="android"', {
- 'conditions': [
- [ 'target_arch=="x64"', {
- 'sources': [
- 'arcfour-amd64-gas.s',
- 'intel-aes.s',
- 'intel-gcm.s',
- 'mpi/mpi_amd64.c',
- 'mpi/mpi_amd64_gas.s',
- 'mpi/mp_comba.c',
- ],
- 'conditions': [
- [ 'cc_is_clang==1', {
- 'cflags': [
- '-no-integrated-as',
- ],
- 'cflags_mozilla': [
- '-no-integrated-as',
- ],
- 'asflags_mozilla': [
- '-no-integrated-as',
- ],
- }],
- ],
- }],
- [ 'target_arch=="ia32"', {
- 'sources': [
- 'mpi/mpi_x86.s',
- ],
- }],
- [ 'target_arch=="arm"', {
- 'sources': [
- 'mpi/mpi_arm.c',
- ],
- }],
- ],
- }],
- [ 'OS=="win"', {
- 'sources': [
- #TODO: building with mingw should not need this.
- 'ecl/uint128.c',
- ],
- 'libraries': [
- 'advapi32.lib',
- ],
- 'conditions': [
- [ 'target_arch=="x64"', {
- 'sources': [
- 'arcfour-amd64-masm.asm',
- 'mpi/mpi_amd64.c',
- 'mpi/mpi_amd64_masm.asm',
- 'mpi/mp_comba_amd64_masm.asm',
- 'intel-aes-x64-masm.asm',
- 'intel-gcm-x64-masm.asm',
- ],
- }, {
- # not x64
- 'sources': [
- 'mpi/mpi_x86_asm.c',
- 'intel-aes-x86-masm.asm',
- 'intel-gcm-x86-masm.asm',
- ],
- }],
- [ 'cc_is_clang!=1', {
- # MSVC
- 'sources': [
- 'intel-gcm-wrap.c',
- ],
- }],
- ],
- }],
- ['target_arch=="ia32" or target_arch=="x64"', {
- 'sources': [
- # All intel architectures get the 64 bit version
- 'ecl/curve25519_64.c',
- ],
- }, {
- 'sources': [
- # All non intel architectures get the generic 32 bit implementation (slow!)
- 'ecl/curve25519_32.c',
- ],
- }],
- #TODO uint128.c
- [ 'disable_chachapoly==0', {
- 'conditions': [
- [ 'OS!="win" and target_arch=="x64"', {
- 'sources': [
- 'chacha20_vec.c',
- 'poly1305-donna-x64-sse2-incremental-source.c',
- ],
- }, {
- # not x64
- 'sources': [
- 'chacha20.c',
- 'poly1305.c',
- ],
- }],
- ],
- }],
- [ 'fuzz_tls==1', {
- 'sources': [
- 'det_rng.c',
- ],
- 'defines': [
- 'UNSAFE_FUZZER_MODE',
- ],
- }],
- [ 'ct_verif==1', {
- 'defines': [
- 'CT_VERIF',
- ],
- }],
- [ 'OS=="mac"', {
- 'conditions': [
- [ 'target_arch=="ia32"', {
- 'sources': [
- 'mpi/mpi_sse2.s',
- ],
- 'defines': [
- 'MP_USE_UINT_DIGIT',
- 'MP_ASSEMBLY_MULTIPLY',
- 'MP_ASSEMBLY_SQUARE',
- 'MP_ASSEMBLY_DIV_2DX1D',
- ],
- }],
- ],
- }],
- ],
- 'ldflags': [
- '-Wl,-Bsymbolic'
- ],
-}
new file mode 100644
--- /dev/null
+++ b/security/nss/lib/freebl/os2_rand.c
@@ -0,0 +1,334 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#define INCL_DOS
+#define INCL_DOSERRORS
+#include <os2.h>
+#include "secrng.h"
+#include "prerror.h"
+#include <stdlib.h>
+#include <time.h>
+#include <stdio.h>
+#include <sys/stat.h>
+
+static BOOL
+clockTickTime(unsigned long *phigh, unsigned long *plow)
+{
+ APIRET rc = NO_ERROR;
+ QWORD qword = { 0, 0 };
+
+ rc = DosTmrQueryTime(&qword);
+ if (rc != NO_ERROR)
+ return FALSE;
+
+ *phigh = qword.ulHi;
+ *plow = qword.ulLo;
+
+ return TRUE;
+}
+
+size_t
+RNG_GetNoise(void *buf, size_t maxbuf)
+{
+ unsigned long high = 0;
+ unsigned long low = 0;
+ clock_t val = 0;
+ int n = 0;
+ int nBytes = 0;
+ time_t sTime;
+
+ if (maxbuf <= 0)
+ return 0;
+
+ clockTickTime(&high, &low);
+
+ /* get the maximally changing bits first */
+ nBytes = sizeof(low) > maxbuf ? maxbuf : sizeof(low);
+ memcpy(buf, &low, nBytes);
+ n += nBytes;
+ maxbuf -= nBytes;
+
+ if (maxbuf <= 0)
+ return n;
+
+ nBytes = sizeof(high) > maxbuf ? maxbuf : sizeof(high);
+ memcpy(((char *)buf) + n, &high, nBytes);
+ n += nBytes;
+ maxbuf -= nBytes;
+
+ if (maxbuf <= 0)
+ return n;
+
+ /* get the number of milliseconds that have elapsed since application started */
+ val = clock();
+
+ nBytes = sizeof(val) > maxbuf ? maxbuf : sizeof(val);
+ memcpy(((char *)buf) + n, &val, nBytes);
+ n += nBytes;
+ maxbuf -= nBytes;
+
+ if (maxbuf <= 0)
+ return n;
+
+ /* get the time in seconds since midnight Jan 1, 1970 */
+ time(&sTime);
+ nBytes = sizeof(sTime) > maxbuf ? maxbuf : sizeof(sTime);
+ memcpy(((char *)buf) + n, &sTime, nBytes);
+ n += nBytes;
+
+ return n;
+}
+
+static BOOL
+EnumSystemFiles(void (*func)(const char *))
+{
+ APIRET rc;
+ ULONG sysInfo = 0;
+ char bootLetter[2];
+ char sysDir[_MAX_PATH] = "";
+ char filename[_MAX_PATH];
+ HDIR hdir = HDIR_CREATE;
+ ULONG numFiles = 1;
+ FILEFINDBUF3 fileBuf = { 0 };
+ ULONG buflen = sizeof(FILEFINDBUF3);
+
+ if (DosQuerySysInfo(QSV_BOOT_DRIVE, QSV_BOOT_DRIVE, (PVOID)&sysInfo,
+ sizeof(ULONG)) == NO_ERROR) {
+ bootLetter[0] = sysInfo + 'A' - 1;
+ bootLetter[1] = '\0';
+ strcpy(sysDir, bootLetter);
+ strcpy(sysDir + 1, ":\\OS2\\");
+
+ strcpy(filename, sysDir);
+ strcat(filename, "*.*");
+ }
+
+ rc = DosFindFirst(filename, &hdir, FILE_NORMAL, &fileBuf, buflen,
+ &numFiles, FIL_STANDARD);
+ if (rc == NO_ERROR) {
+ do {
+ // pass the full pathname to the callback
+ sprintf(filename, "%s%s", sysDir, fileBuf.achName);
+ (*func)(filename);
+
+ numFiles = 1;
+ rc = DosFindNext(hdir, &fileBuf, buflen, &numFiles);
+ if (rc != NO_ERROR && rc != ERROR_NO_MORE_FILES)
+ printf("DosFindNext errod code = %d\n", rc);
+ } while (rc == NO_ERROR);
+
+ rc = DosFindClose(hdir);
+ if (rc != NO_ERROR)
+ printf("DosFindClose error code = %d", rc);
+ } else
+ printf("DosFindFirst error code = %d", rc);
+
+ return TRUE;
+}
+
+static int dwNumFiles, dwReadEvery, dwFileToRead = 0;
+
+static void
+CountFiles(const char *file)
+{
+ dwNumFiles++;
+}
+
+static void
+ReadFiles(const char *file)
+{
+ if ((dwNumFiles % dwReadEvery) == 0)
+ RNG_FileForRNG(file);
+
+ dwNumFiles++;
+}
+
+static void
+ReadSingleFile(const char *filename)
+{
+ unsigned char buffer[1024];
+ FILE *file;
+
+ file = fopen((char *)filename, "rb");
+ if (file != NULL) {
+ while (fread(buffer, 1, sizeof(buffer), file) > 0)
+ ;
+ fclose(file);
+ }
+}
+
+static void
+ReadOneFile(const char *file)
+{
+ if (dwNumFiles == dwFileToRead) {
+ ReadSingleFile(file);
+ }
+
+ dwNumFiles++;
+}
+
+static void
+ReadSystemFiles(void)
+{
+ // first count the number of files
+ dwNumFiles = 0;
+ if (!EnumSystemFiles(CountFiles))
+ return;
+
+ RNG_RandomUpdate(&dwNumFiles, sizeof(dwNumFiles));
+
+ // now read 10 files
+ if (dwNumFiles == 0)
+ return;
+
+ dwReadEvery = dwNumFiles / 10;
+ if (dwReadEvery == 0)
+ dwReadEvery = 1; // less than 10 files
+
+ dwNumFiles = 0;
+ EnumSystemFiles(ReadFiles);
+}
+
+void
+RNG_SystemInfoForRNG(void)
+{
+ unsigned long *plong = 0;
+ PTIB ptib;
+ PPIB ppib;
+ APIRET rc = NO_ERROR;
+ DATETIME dt;
+ COUNTRYCODE cc = { 0 };
+ COUNTRYINFO ci = { 0 };
+ unsigned long actual = 0;
+ char path[_MAX_PATH] = "";
+ char fullpath[_MAX_PATH] = "";
+ unsigned long pathlength = sizeof(path);
+ FSALLOCATE fsallocate;
+ FILESTATUS3 fstatus;
+ unsigned long defaultdrive = 0;
+ unsigned long logicaldrives = 0;
+ unsigned long sysInfo[QSV_MAX] = { 0 };
+ char buffer[20];
+ int nBytes = 0;
+
+ nBytes = RNG_GetNoise(buffer, sizeof(buffer));
+ RNG_RandomUpdate(buffer, nBytes);
+
+ /* allocate memory and use address and memory */
+ plong = (unsigned long *)malloc(sizeof(*plong));
+ RNG_RandomUpdate(&plong, sizeof(plong));
+ RNG_RandomUpdate(plong, sizeof(*plong));
+ free(plong);
+
+ /* process info */
+ rc = DosGetInfoBlocks(&ptib, &ppib);
+ if (rc == NO_ERROR) {
+ RNG_RandomUpdate(ptib, sizeof(*ptib));
+ RNG_RandomUpdate(ppib, sizeof(*ppib));
+ }
+
+ /* time */
+ rc = DosGetDateTime(&dt);
+ if (rc == NO_ERROR) {
+ RNG_RandomUpdate(&dt, sizeof(dt));
+ }
+
+ /* country */
+ rc = DosQueryCtryInfo(sizeof(ci), &cc, &ci, &actual);
+ if (rc == NO_ERROR) {
+ RNG_RandomUpdate(&cc, sizeof(cc));
+ RNG_RandomUpdate(&ci, sizeof(ci));
+ RNG_RandomUpdate(&actual, sizeof(actual));
+ }
+
+ /* current directory */
+ rc = DosQueryCurrentDir(0, path, &pathlength);
+ strcat(fullpath, "\\");
+ strcat(fullpath, path);
+ if (rc == NO_ERROR) {
+ RNG_RandomUpdate(fullpath, strlen(fullpath));
+ // path info
+ rc = DosQueryPathInfo(fullpath, FIL_STANDARD, &fstatus, sizeof(fstatus));
+ if (rc == NO_ERROR) {
+ RNG_RandomUpdate(&fstatus, sizeof(fstatus));
+ }
+ }
+
+ /* file system info */
+ rc = DosQueryFSInfo(0, FSIL_ALLOC, &fsallocate, sizeof(fsallocate));
+ if (rc == NO_ERROR) {
+ RNG_RandomUpdate(&fsallocate, sizeof(fsallocate));
+ }
+
+ /* drive info */
+ rc = DosQueryCurrentDisk(&defaultdrive, &logicaldrives);
+ if (rc == NO_ERROR) {
+ RNG_RandomUpdate(&defaultdrive, sizeof(defaultdrive));
+ RNG_RandomUpdate(&logicaldrives, sizeof(logicaldrives));
+ }
+
+ /* system info */
+ rc = DosQuerySysInfo(1L, QSV_MAX, (PVOID)&sysInfo, sizeof(ULONG) * QSV_MAX);
+ if (rc == NO_ERROR) {
+ RNG_RandomUpdate(&sysInfo, sizeof(sysInfo));
+ }
+
+ // now let's do some files
+ ReadSystemFiles();
+
+ /* more noise */
+ nBytes = RNG_GetNoise(buffer, sizeof(buffer));
+ RNG_RandomUpdate(buffer, nBytes);
+}
+
+void
+RNG_FileForRNG(const char *filename)
+{
+ struct stat stat_buf;
+ unsigned char buffer[1024];
+ FILE *file = 0;
+ int nBytes = 0;
+ static int totalFileBytes = 0;
+
+ if (stat((char *)filename, &stat_buf) < 0)
+ return;
+
+ RNG_RandomUpdate((unsigned char *)&stat_buf, sizeof(stat_buf));
+
+ file = fopen((char *)filename, "r");
+ if (file != NULL) {
+ for (;;) {
+ size_t bytes = fread(buffer, 1, sizeof(buffer), file);
+
+ if (bytes == 0)
+ break;
+
+ RNG_RandomUpdate(buffer, bytes);
+ totalFileBytes += bytes;
+ if (totalFileBytes > 250000)
+ break;
+ }
+ fclose(file);
+ }
+
+ nBytes = RNG_GetNoise(buffer, 20);
+ RNG_RandomUpdate(buffer, nBytes);
+}
+
+static void
+rng_systemJitter(void)
+{
+ dwNumFiles = 0;
+ EnumSystemFiles(ReadOneFile);
+ dwFileToRead++;
+ if (dwFileToRead >= dwNumFiles) {
+ dwFileToRead = 0;
+ }
+}
+
+size_t
+RNG_SystemRNG(void *dest, size_t maxLen)
+{
+ return rng_systemFromNoise(dest, maxLen);
+}
--- a/security/nss/lib/freebl/rsa.c
+++ b/security/nss/lib/freebl/rsa.c
@@ -1231,20 +1231,17 @@ get_blinding_params(RSAPrivateKey *key,
*/
PR_INSERT_BEFORE(&rsabp->link, el);
}
/* We've found (or created) the RSAblindingParams struct for this key.
* Now, search its list of ready blinding params for a usable one.
*/
while (0 != (bp = rsabp->bp)) {
-#ifndef UNSAFE_FUZZER_MODE
- if (--(bp->counter) > 0)
-#endif
- {
+ if (--(bp->counter) > 0) {
/* Found a match and there are still remaining uses left */
/* Return the parameters */
CHECK_MPI_OK(mp_copy(&bp->f, f));
CHECK_MPI_OK(mp_copy(&bp->g, g));
PZ_Unlock(blindingParamsList.lock);
return SECSuccess;
}
--- a/security/nss/lib/freebl/rsapkcs.c
+++ b/security/nss/lib/freebl/rsapkcs.c
@@ -80,35 +80,16 @@ constantTimeCondition(unsigned int c,
static unsigned int
rsa_modulusLen(SECItem *modulus)
{
unsigned char byteZero = modulus->data[0];
unsigned int modLen = modulus->len - !byteZero;
return modLen;
}
-static unsigned int
-rsa_modulusBits(SECItem *modulus)
-{
- unsigned char byteZero = modulus->data[0];
- unsigned int numBits = (modulus->len - 1) * 8;
-
- if (byteZero == 0) {
- numBits -= 8;
- byteZero = modulus->data[1];
- }
-
- while (byteZero > 0) {
- numBits++;
- byteZero >>= 1;
- }
-
- return numBits;
-}
-
/*
* Format one block of data for public/private key encryption using
* the rules defined in PKCS #1.
*/
static unsigned char *
rsa_FormatOneBlock(unsigned modulusLen,
RSA_BlockType blockType,
SECItem *data)
@@ -976,21 +957,22 @@ failure:
}
/*
* Encode a RSA-PSS signature.
* Described in RFC 3447, section 9.1.1.
* We use mHash instead of M as input.
* emBits from the RFC is just modBits - 1, see section 8.1.1.
* We only support MGF1 as the MGF.
+ *
+ * NOTE: this code assumes modBits is a multiple of 8.
*/
static SECStatus
emsa_pss_encode(unsigned char *em,
unsigned int emLen,
- unsigned int emBits,
const unsigned char *mHash,
HASH_HashType hashAlg,
HASH_HashType maskHashAlg,
const unsigned char *salt,
unsigned int saltLen)
{
const SECHashObject *hash;
void *hash_context;
@@ -1045,62 +1027,56 @@ emsa_pss_encode(unsigned char *em,
MGF1(maskHashAlg, dbMask, dbMaskLen, &em[dbMaskLen], hash->length);
/* Step 10 */
for (i = 0; i < dbMaskLen; i++)
em[i] ^= dbMask[i];
PORT_Free(dbMask);
/* Step 11 */
- em[0] &= 0xff >> (8 * emLen - emBits);
+ em[0] &= 0x7f;
/* Step 12 */
em[emLen - 1] = 0xbc;
return SECSuccess;
}
/*
* Verify a RSA-PSS signature.
* Described in RFC 3447, section 9.1.2.
* We use mHash instead of M as input.
* emBits from the RFC is just modBits - 1, see section 8.1.2.
* We only support MGF1 as the MGF.
+ *
+ * NOTE: this code assumes modBits is a multiple of 8.
*/
static SECStatus
emsa_pss_verify(const unsigned char *mHash,
const unsigned char *em,
unsigned int emLen,
- unsigned int emBits,
HASH_HashType hashAlg,
HASH_HashType maskHashAlg,
unsigned int saltLen)
{
const SECHashObject *hash;
void *hash_context;
unsigned char *db;
unsigned char *H_; /* H' from the RFC */
unsigned int i;
unsigned int dbMaskLen;
- unsigned int zeroBits;
SECStatus rv;
hash = HASH_GetRawHashObject(hashAlg);
dbMaskLen = emLen - hash->length - 1;
- /* Step 3 + 4 */
+ /* Step 3 + 4 + 6 */
if ((emLen < (hash->length + saltLen + 2)) ||
- (em[emLen - 1] != 0xbc)) {
- PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
- return SECFailure;
- }
-
- /* Step 6 */
- zeroBits = 8 * emLen - emBits;
- if (em[0] >> (8 - zeroBits)) {
+ (em[emLen - 1] != 0xbc) ||
+ ((em[0] & 0x80) != 0)) {
PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
return SECFailure;
}
/* Step 7 */
db = (unsigned char *)PORT_Alloc(dbMaskLen);
if (db == NULL) {
PORT_SetError(SEC_ERROR_NO_MEMORY);
@@ -1110,17 +1086,17 @@ emsa_pss_verify(const unsigned char *mHa
MGF1(maskHashAlg, db, dbMaskLen, &em[dbMaskLen], hash->length);
/* Step 8 */
for (i = 0; i < dbMaskLen; i++) {
db[i] ^= em[i];
}
/* Step 9 */
- db[0] &= 0xff >> zeroBits;
+ db[0] &= 0x7f;
/* Step 10 */
for (i = 0; i < (dbMaskLen - saltLen - 1); i++) {
if (db[i] != 0) {
PORT_Free(db);
PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
return SECFailure;
}
@@ -1175,43 +1151,34 @@ RSA_SignPSS(RSAPrivateKey *key,
unsigned char *output,
unsigned int *outputLen,
unsigned int maxOutputLen,
const unsigned char *input,
unsigned int inputLen)
{
SECStatus rv = SECSuccess;
unsigned int modulusLen = rsa_modulusLen(&key->modulus);
- unsigned int modulusBits = rsa_modulusBits(&key->modulus);
- unsigned int emLen = modulusLen;
- unsigned char *pssEncoded, *em;
+ unsigned char *pssEncoded = NULL;
if (maxOutputLen < modulusLen) {
PORT_SetError(SEC_ERROR_OUTPUT_LEN);
return SECFailure;
}
if ((hashAlg == HASH_AlgNULL) || (maskHashAlg == HASH_AlgNULL)) {
PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
return SECFailure;
}
- pssEncoded = em = (unsigned char *)PORT_Alloc(modulusLen);
+ pssEncoded = (unsigned char *)PORT_Alloc(modulusLen);
if (pssEncoded == NULL) {
PORT_SetError(SEC_ERROR_NO_MEMORY);
return SECFailure;
}
-
- /* len(em) == ceil((modulusBits - 1) / 8). */
- if (modulusBits % 8 == 1) {
- em[0] = 0;
- emLen--;
- em++;
- }
- rv = emsa_pss_encode(em, emLen, modulusBits - 1, input, hashAlg,
+ rv = emsa_pss_encode(pssEncoded, modulusLen, input, hashAlg,
maskHashAlg, salt, saltLength);
if (rv != SECSuccess)
goto done;
rv = RSA_PrivateKeyOpDoubleChecked(key, output, pssEncoded);
*outputLen = modulusLen;
done:
@@ -1226,52 +1193,45 @@ RSA_CheckSignPSS(RSAPublicKey *key,
unsigned int saltLength,
const unsigned char *sig,
unsigned int sigLen,
const unsigned char *hash,
unsigned int hashLen)
{
SECStatus rv;
unsigned int modulusLen = rsa_modulusLen(&key->modulus);
- unsigned int modulusBits = rsa_modulusBits(&key->modulus);
- unsigned int emLen = modulusLen;
- unsigned char *buffer, *em;
+ unsigned char *buffer;
if (sigLen != modulusLen) {
PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
return SECFailure;
}
if ((hashAlg == HASH_AlgNULL) || (maskHashAlg == HASH_AlgNULL)) {
PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
return SECFailure;
}
- buffer = em = (unsigned char *)PORT_Alloc(modulusLen);
+ buffer = (unsigned char *)PORT_Alloc(modulusLen);
if (!buffer) {
PORT_SetError(SEC_ERROR_NO_MEMORY);
return SECFailure;
}
rv = RSA_PublicKeyOp(key, buffer, sig);
if (rv != SECSuccess) {
PORT_Free(buffer);
PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
return SECFailure;
}
- /* len(em) == ceil((modulusBits - 1) / 8). */
- if (modulusBits % 8 == 1) {
- emLen--;
- em++;
- }
- rv = emsa_pss_verify(hash, em, emLen, modulusBits - 1, hashAlg,
+ rv = emsa_pss_verify(hash, buffer, modulusLen, hashAlg,
maskHashAlg, saltLength);
+ PORT_Free(buffer);
- PORT_Free(buffer);
return rv;
}
/* XXX Doesn't set error code */
SECStatus
RSA_Sign(RSAPrivateKey *key,
unsigned char *output,
unsigned int *outputLen,
--- a/security/nss/lib/freebl/sysrand.c
+++ b/security/nss/lib/freebl/sysrand.c
@@ -3,14 +3,47 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifdef FREEBL_NO_DEPEND
#include "stubs.h"
#endif
#include "seccomon.h"
+#ifndef XP_WIN
+static size_t rng_systemFromNoise(unsigned char *dest, size_t maxLen);
+#endif
+
#if defined(XP_UNIX) || defined(XP_BEOS)
#include "unix_rand.c"
#endif
#ifdef XP_WIN
#include "win_rand.c"
#endif
+#ifdef XP_OS2
+#include "os2_rand.c"
+#endif
+
+#ifndef XP_WIN
+/*
+ * Normal RNG_SystemRNG() isn't available, use the system noise to collect
+ * the required amount of entropy.
+ */
+static size_t
+rng_systemFromNoise(unsigned char *dest, size_t maxLen)
+{
+ size_t retBytes = maxLen;
+
+ while (maxLen) {
+ size_t nbytes = RNG_GetNoise(dest, maxLen);
+
+ PORT_Assert(nbytes != 0);
+
+ dest += nbytes;
+ maxLen -= nbytes;
+
+ /* some hw op to try to introduce more entropy into the next
+ * RNG_GetNoise call */
+ rng_systemJitter();
+ }
+ return retBytes;
+}
+#endif
--- a/security/nss/lib/freebl/unix_rand.c
+++ b/security/nss/lib/freebl/unix_rand.c
@@ -155,17 +155,17 @@ RNG_kstat(PRUint32 *fed)
PORT_Assert(0);
rv = SECFailure;
}
return rv;
}
#endif
-#if defined(SCO) || defined(UNIXWARE) || defined(BSDI) || defined(FREEBSD) || defined(NETBSD) || defined(DARWIN) || defined(OPENBSD) || defined(NTO) || defined(__riscos__) || defined(__GNU__) || defined(__FreeBSD_kernel__) || defined(__NetBSD_kernel__)
+#if defined(SCO) || defined(UNIXWARE) || defined(BSDI) || defined(FREEBSD) || defined(NETBSD) || defined(DARWIN) || defined(OPENBSD) || defined(NTO) || defined(__riscos__)
#include <sys/times.h>
#define getdtablesize() sysconf(_SC_OPEN_MAX)
static size_t
GetHighResClock(void *buf, size_t maxbytes)
{
int ticks;
@@ -889,19 +889,16 @@ RNG_SystemInfoForRNG(void)
/* Give in system information */
if (gethostname(buf, sizeof(buf)) == 0) {
RNG_RandomUpdate(buf, strlen(buf));
}
GiveSystemInfo();
/* grab some data from system's PRNG before any other files. */
bytes = RNG_FileUpdate("/dev/urandom", SYSTEM_RNG_SEED_COUNT);
- if (!bytes) {
- PORT_SetError(SEC_ERROR_NEED_RANDOM);
- }
/* If the user points us to a random file, pass it through the rng */
randfile = PR_GetEnvSecure("NSRANDFILE");
if ((randfile != NULL) && (randfile[0] != '\0')) {
char *randCountString = PR_GetEnvSecure("NSRANDCOUNT");
int randCount = randCountString ? atoi(randCountString) : 0;
if (randCount != 0) {
RNG_FileUpdate(randfile, randCount);
@@ -1020,16 +1017,30 @@ RNG_FileUpdate(const char *fileName, siz
}
void
RNG_FileForRNG(const char *fileName)
{
RNG_FileUpdate(fileName, TOTAL_FILE_LIMIT);
}
+void
+ReadSingleFile(const char *fileName)
+{
+ FILE *file;
+ unsigned char buffer[BUFSIZ];
+
+ file = fopen(fileName, "rb");
+ if (file != NULL) {
+ while (fread(buffer, 1, sizeof(buffer), file) > 0)
+ ;
+ fclose(file);
+ }
+}
+
#define _POSIX_PTHREAD_SEMANTICS
#include <dirent.h>
PRBool
ReadFileOK(char *dir, char *file)
{
struct stat stat_buf;
char filename[PATH_MAX];
@@ -1039,29 +1050,111 @@ ReadFileOK(char *dir, char *file)
return PR_FALSE; /* name too long, can't read it anyway */
}
if (stat(filename, &stat_buf) < 0)
return PR_FALSE; /* can't stat, probably can't read it then as well */
return S_ISREG(stat_buf.st_mode) ? PR_TRUE : PR_FALSE;
}
+/*
+ * read one file out of either /etc or the user's home directory.
+ * fileToRead tells which file to read.
+ *
+ * return 1 if it's time to reset the fileToRead (no more files to read).
+ */
+static int
+ReadOneFile(int fileToRead)
+{
+ char *dir = "/etc";
+ DIR *fd = opendir(dir);
+ int resetCount = 0;
+ struct dirent *entry;
+#if defined(__sun)
+ char firstName[256];
+#else
+ char firstName[NAME_MAX + 1];
+#endif
+ const char *name = NULL;
+ int i;
+
+ if (fd == NULL) {
+ dir = PR_GetEnvSecure("HOME");
+ if (dir) {
+ fd = opendir(dir);
+ }
+ }
+ if (fd == NULL) {
+ return 1;
+ }
+
+ firstName[0] = '\0';
+ for (i = 0; i <= fileToRead; i++) {
+ do {
+ /* readdir() isn't guaranteed to be thread safe on every platform;
+ * this code assumes the same directory isn't read concurrently.
+ * This usage is confirmed safe on Linux, see bug 1254334. */
+ entry = readdir(fd);
+ } while (entry != NULL && !ReadFileOK(dir, &entry->d_name[0]));
+ if (entry == NULL) {
+ resetCount = 1; /* read to the end, start again at the beginning */
+ if (firstName[0]) {
+ /* ran out of entries in the directory, use the first one */
+ name = firstName;
+ }
+ break;
+ }
+ name = entry->d_name;
+ if (i == 0) {
+ /* copy the name of the first in case we run out of entries */
+ PORT_Assert(PORT_Strlen(name) < sizeof(firstName));
+ PORT_Strncpy(firstName, name, sizeof(firstName) - 1);
+ firstName[sizeof(firstName) - 1] = '\0';
+ }
+ }
+
+ if (name) {
+ char filename[PATH_MAX];
+ int count = snprintf(filename, sizeof(filename), "%s/%s", dir, name);
+ if (count >= 1) {
+ ReadSingleFile(filename);
+ }
+ }
+
+ closedir(fd);
+ return resetCount;
+}
+
+/*
+ * do something to try to introduce more noise into the 'GetNoise' call
+ */
+static void
+rng_systemJitter(void)
+{
+ static int fileToRead = 1;
+
+ if (ReadOneFile(fileToRead)) {
+ fileToRead = 1;
+ } else {
+ fileToRead++;
+ }
+}
+
size_t
RNG_SystemRNG(void *dest, size_t maxLen)
{
FILE *file;
int fd;
int bytes;
size_t fileBytes = 0;
unsigned char *buffer = dest;
file = fopen("/dev/urandom", "r");
if (file == NULL) {
- PORT_SetError(SEC_ERROR_NEED_RANDOM);
- return 0;
+ return rng_systemFromNoise(dest, maxLen);
}
/* Read from the underlying file descriptor directly to bypass stdio
* buffering and avoid reading more bytes than we need from /dev/urandom.
* NOTE: we can't use fread with unbuffered I/O because fread may return
* EOF in unbuffered I/O mode on Android.
*/
fd = fileno(file);
/* 'file' was just opened, so this should not fail. */
--- a/security/nss/lib/nss/nss.h
+++ b/security/nss/lib/nss/nss.h
@@ -17,22 +17,22 @@
/*
* NSS's major version, minor version, patch level, build number, and whether
* this is a beta release.
*
* The format of the version string should be
* "<major version>.<minor version>[.<patch level>[.<build number>]][ <ECC>][ <Beta>]"
*/
-#define NSS_VERSION "3.30" _NSS_CUSTOMIZED " Beta"
+#define NSS_VERSION "3.28.1" _NSS_CUSTOMIZED
#define NSS_VMAJOR 3
-#define NSS_VMINOR 30
-#define NSS_VPATCH 0
+#define NSS_VMINOR 28
+#define NSS_VPATCH 1
#define NSS_VBUILD 0
-#define NSS_BETA PR_TRUE
+#define NSS_BETA PR_FALSE
#ifndef RC_INVOKED
#include "seccomon.h"
typedef struct NSSInitParametersStr NSSInitParameters;
/*
--- a/security/nss/lib/pk11wrap/pk11load.c
+++ b/security/nss/lib/pk11wrap/pk11load.c
@@ -12,20 +12,16 @@
#include "prlink.h"
#include "pk11func.h"
#include "secmodi.h"
#include "secmodti.h"
#include "nssilock.h"
#include "secerr.h"
#include "prenv.h"
#include "utilparst.h"
-#include "prio.h"
-#include "prprf.h"
-#include <stdio.h>
-#include "prsystem.h"
#define DEBUG_MODULE 1
#ifdef DEBUG_MODULE
static char *modToDBG = NULL;
#include "debug_module.c"
#endif
@@ -349,46 +345,46 @@ SECMOD_SetRootCerts(PK11SlotInfo *slot,
/* increment module count & store new list */
mod->slotInfo = psi_list;
mod->slotInfoCount++;
}
psi->hasRootCerts = 1;
}
}
-#ifndef NSS_TEST_BUILD
static const char *my_shlib_name =
SHLIB_PREFIX "nss" SHLIB_VERSION "." SHLIB_SUFFIX;
static const char *softoken_shlib_name =
SHLIB_PREFIX "softokn" SOFTOKEN_SHLIB_VERSION "." SHLIB_SUFFIX;
static const PRCallOnceType pristineCallOnce;
static PRCallOnceType loadSoftokenOnce;
static PRLibrary *softokenLib;
static PRInt32 softokenLoadCount;
+#include "prio.h"
+#include "prprf.h"
+#include <stdio.h>
+#include "prsystem.h"
+
/* This function must be run only once. */
/* determine if hybrid platform, then actually load the DSO. */
static PRStatus
softoken_LoadDSO(void)
{
PRLibrary *handle;
handle = PORT_LoadLibraryFromOrigin(my_shlib_name,
(PRFuncPtr)&softoken_LoadDSO,
softoken_shlib_name);
if (handle) {
softokenLib = handle;
return PR_SUCCESS;
}
return PR_FAILURE;
}
-#else
-CK_RV NSC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList);
-char **NSC_ModuleDBFunc(unsigned long function, char *parameters, void *args);
-#endif
/*
* load a new module into our address space and initialize it.
*/
SECStatus
secmod_LoadPKCS11Module(SECMODModule *mod, SECMODModule **oldModule)
{
PRLibrary *library = NULL;
@@ -397,21 +393,18 @@ secmod_LoadPKCS11Module(SECMODModule *mo
CK_ULONG slotCount = 0;
SECStatus rv;
PRBool alreadyLoaded = PR_FALSE;
char *disableUnload = NULL;
if (mod->loaded)
return SECSuccess;
- /* internal modules get loaded from their internal list */
+ /* intenal modules get loaded from their internal list */
if (mod->internal && (mod->dllName == NULL)) {
-#ifdef NSS_TEST_BUILD
- entry = (CK_C_GetFunctionList)NSC_GetFunctionList;
-#else
/*
* Loads softoken as a dynamic library,
* even though the rest of NSS assumes this as the "internal" module.
*/
if (!softokenLib &&
PR_SUCCESS != PR_CallOnce(&loadSoftokenOnce, &softoken_LoadDSO))
return SECFailure;
@@ -422,25 +415,20 @@ secmod_LoadPKCS11Module(SECMODModule *mo
PR_FindSymbol(softokenLib, "FC_GetFunctionList");
} else {
entry = (CK_C_GetFunctionList)
PR_FindSymbol(softokenLib, "NSC_GetFunctionList");
}
if (!entry)
return SECFailure;
-#endif
if (mod->isModuleDB) {
mod->moduleDBFunc = (CK_C_GetFunctionList)
-#ifdef NSS_TEST_BUILD
- NSC_ModuleDBFunc;
-#else
PR_FindSymbol(softokenLib, "NSC_ModuleDBFunc");
-#endif
}
if (mod->moduleDBOnly) {
mod->loaded = PR_TRUE;
return SECSuccess;
}
} else {
/* Not internal, load the DLL and look up C_GetFunctionList */
@@ -608,33 +596,31 @@ SECMOD_UnloadModule(SECMODModule *mod)
}
mod->moduleID = 0;
mod->loaded = PR_FALSE;
/* do we want the semantics to allow unloading the internal library?
* if not, we should change this to SECFailure and move it above the
* mod->loaded = PR_FALSE; */
if (mod->internal && (mod->dllName == NULL)) {
-#ifndef NSS_TEST_BUILD
if (0 == PR_ATOMIC_DECREMENT(&softokenLoadCount)) {
if (softokenLib) {
disableUnload = PR_GetEnvSecure("NSS_DISABLE_UNLOAD");
if (!disableUnload) {
#ifdef DEBUG
PRStatus status = PR_UnloadLibrary(softokenLib);
PORT_Assert(PR_SUCCESS == status);
#else
PR_UnloadLibrary(softokenLib);
#endif
}
softokenLib = NULL;
}
loadSoftokenOnce = pristineCallOnce;
}
-#endif
return SECSuccess;
}
library = (PRLibrary *)mod->library;
/* paranoia */
if (library == NULL) {
return SECFailure;
}
--- a/security/nss/lib/pk11wrap/pk11mech.c
+++ b/security/nss/lib/pk11wrap/pk11mech.c
@@ -607,20 +607,16 @@ PK11_GetKeyGenWithSize(CK_MECHANISM_TYPE
case CKM_GENERIC_SECRET_KEY_GEN:
return CKM_GENERIC_SECRET_KEY_GEN;
case CKM_PBE_MD2_DES_CBC:
case CKM_PBE_MD5_DES_CBC:
case CKM_PBA_SHA1_WITH_SHA1_HMAC:
case CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN:
case CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN:
case CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN:
- case CKM_NSS_PKCS12_PBE_SHA224_HMAC_KEY_GEN:
- case CKM_NSS_PKCS12_PBE_SHA256_HMAC_KEY_GEN:
- case CKM_NSS_PKCS12_PBE_SHA384_HMAC_KEY_GEN:
- case CKM_NSS_PKCS12_PBE_SHA512_HMAC_KEY_GEN:
case CKM_NETSCAPE_PBE_SHA1_DES_CBC:
case CKM_NETSCAPE_PBE_SHA1_40_BIT_RC2_CBC:
case CKM_NETSCAPE_PBE_SHA1_128_BIT_RC2_CBC:
case CKM_NETSCAPE_PBE_SHA1_40_BIT_RC4:
case CKM_NETSCAPE_PBE_SHA1_128_BIT_RC4:
case CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC:
case CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC:
case CKM_PBE_SHA1_RC2_40_CBC:
--- a/security/nss/lib/pk11wrap/pk11pk12.c
+++ b/security/nss/lib/pk11wrap/pk11pk12.c
@@ -60,39 +60,25 @@ struct SECKEYDHPrivateKeyStr {
PLArenaPool *arena;
SECItem prime;
SECItem base;
SECItem privateValue;
};
typedef struct SECKEYDHPrivateKeyStr SECKEYDHPrivateKey;
/*
-** Elliptic Curve Private Key structures
-** <https://tools.ietf.org/html/rfc5915#section-3>
-*/
-struct SECKEYECPrivateKeyStr {
- PLArenaPool *arena;
- SECItem version;
- SECItem curveOID; /* optional/ignored */
- SECItem publicValue; /* required (for now) */
- SECItem privateValue;
-};
-typedef struct SECKEYECPrivateKeyStr SECKEYECPrivateKey;
-
-/*
** raw private key object
*/
struct SECKEYRawPrivateKeyStr {
PLArenaPool *arena;
KeyType keyType;
union {
SECKEYRSAPrivateKey rsa;
SECKEYDSAPrivateKey dsa;
SECKEYDHPrivateKey dh;
- SECKEYECPrivateKey ec;
} u;
};
typedef struct SECKEYRawPrivateKeyStr SECKEYRawPrivateKey;
SEC_ASN1_MKSUB(SEC_AnyTemplate)
SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate)
/* ASN1 Templates for new decoder/encoder */
@@ -148,43 +134,16 @@ const SEC_ASN1Template SECKEY_DSAPrivate
};
const SEC_ASN1Template SECKEY_DHPrivateKeyExportTemplate[] = {
{ SEC_ASN1_INTEGER, offsetof(SECKEYRawPrivateKey, u.dh.privateValue) },
{ SEC_ASN1_INTEGER, offsetof(SECKEYRawPrivateKey, u.dh.base) },
{ SEC_ASN1_INTEGER, offsetof(SECKEYRawPrivateKey, u.dh.prime) },
};
-#ifndef NSS_DISABLE_ECC
-SEC_ASN1_MKSUB(SEC_BitStringTemplate)
-SEC_ASN1_MKSUB(SEC_ObjectIDTemplate)
-
-const SEC_ASN1Template SECKEY_ECPrivateKeyExportTemplate[] = {
- { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECKEYRawPrivateKey) },
- { SEC_ASN1_INTEGER, offsetof(SECKEYRawPrivateKey, u.ec.version) },
- { SEC_ASN1_OCTET_STRING,
- offsetof(SECKEYRawPrivateKey, u.ec.privateValue) },
- /* This value will always be ignored. u.ec.curveOID will always be
- * overriden with the outer AlgorithmID.parameters. */
- { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED |
- SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC |
- SEC_ASN1_XTRN | 0,
- offsetof(SECKEYRawPrivateKey, u.ec.curveOID),
- SEC_ASN1_SUB(SEC_ObjectIDTemplate) },
- /* The public value is optional per RFC, but required in NSS. We
- * can't do scalar mult on ECs to get a raw point with PK11 APIs. */
- { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED |
- SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC |
- SEC_ASN1_XTRN | 1,
- offsetof(SECKEYRawPrivateKey, u.ec.publicValue),
- SEC_ASN1_SUB(SEC_BitStringTemplate) },
- { 0 }
-};
-#endif /* NSS_DISABLE_ECC */
-
const SEC_ASN1Template SECKEY_EncryptedPrivateKeyInfoTemplate[] = {
{ SEC_ASN1_SEQUENCE,
0, NULL, sizeof(SECKEYEncryptedPrivateKeyInfo) },
{ SEC_ASN1_INLINE | SEC_ASN1_XTRN,
offsetof(SECKEYEncryptedPrivateKeyInfo, algorithm),
SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
{ SEC_ASN1_OCTET_STRING,
offsetof(SECKEYEncryptedPrivateKeyInfo, encryptedData) },
@@ -234,25 +193,16 @@ prepare_dsa_priv_key_export_for_asn1(SEC
static void
prepare_dh_priv_key_export_for_asn1(SECKEYRawPrivateKey *key)
{
key->u.dh.privateValue.type = siUnsignedInteger;
key->u.dh.prime.type = siUnsignedInteger;
key->u.dh.base.type = siUnsignedInteger;
}
-static void
-prepare_ec_priv_key_export_for_asn1(SECKEYRawPrivateKey *key)
-{
- key->u.ec.version.type = siUnsignedInteger;
- key->u.ec.curveOID.type = siUnsignedInteger;
- key->u.ec.privateValue.type = siUnsignedInteger;
- key->u.ec.publicValue.type = siUnsignedInteger;
-}
-
SECStatus
PK11_ImportDERPrivateKeyInfo(PK11SlotInfo *slot, SECItem *derPKI,
SECItem *nickname, SECItem *publicValue, PRBool isPerm,
PRBool isPrivate, unsigned int keyUsage, void *wincx)
{
return PK11_ImportDERPrivateKeyInfoAndReturnKey(slot, derPKI,
nickname, publicValue,
isPerm, isPrivate, keyUsage,
@@ -477,60 +427,17 @@ PK11_ImportAndReturnPrivateKey(PK11SlotI
attrs++;
PK11_SETATTRS(attrs, CKA_BASE, lpk->u.dh.base.data,
lpk->u.dh.base.len);
attrs++;
PK11_SETATTRS(attrs, CKA_VALUE, lpk->u.dh.privateValue.data,
lpk->u.dh.privateValue.len);
attrs++;
break;
-#ifndef NSS_DISABLE_ECC
- case ecKey:
- keyType = CKK_EC;
- if (lpk->u.ec.publicValue.len == 0) {
- goto loser;
- }
- if (PK11_IsInternal(slot)) {
- PK11_SETATTRS(attrs, CKA_NETSCAPE_DB,
- lpk->u.ec.publicValue.data,
- lpk->u.ec.publicValue.len);
- attrs++;
- }
- PK11_SETATTRS(attrs, CKA_SIGN, (keyUsage & KU_DIGITAL_SIGNATURE) ? &cktrue
- : &ckfalse,
- sizeof(CK_BBOOL));
- attrs++;
- PK11_SETATTRS(attrs, CKA_SIGN_RECOVER,
- (keyUsage & KU_DIGITAL_SIGNATURE) ? &cktrue
- : &ckfalse,
- sizeof(CK_BBOOL));
- attrs++;
- PK11_SETATTRS(attrs, CKA_DERIVE, (keyUsage & KU_KEY_AGREEMENT) ? &cktrue
- : &ckfalse,
- sizeof(CK_BBOOL));
- attrs++;
- ck_id = PK11_MakeIDFromPubKey(&lpk->u.ec.publicValue);
- if (ck_id == NULL) {
- goto loser;
- }
- PK11_SETATTRS(attrs, CKA_ID, ck_id->data, ck_id->len);
- attrs++;
- signedattr = attrs;
- /* curveOID always is a copy of AlgorithmID.parameters. */
- PK11_SETATTRS(attrs, CKA_EC_PARAMS, lpk->u.ec.curveOID.data,
- lpk->u.ec.curveOID.len);
- attrs++;
- PK11_SETATTRS(attrs, CKA_VALUE, lpk->u.ec.privateValue.data,
- lpk->u.ec.privateValue.len);
- attrs++;
- PK11_SETATTRS(attrs, CKA_EC_POINT, lpk->u.ec.publicValue.data,
- lpk->u.ec.publicValue.len);
- attrs++;
- break;
-#endif /* NSS_DISABLE_ECC */
+ /* what about fortezza??? */
default:
PORT_SetError(SEC_ERROR_BAD_KEY);
goto loser;
}
templateCount = attrs - theTemplate;
PORT_Assert(templateCount <= sizeof(theTemplate) / sizeof(CK_ATTRIBUTE));
PORT_Assert(signedattr != NULL);
signedcount = attrs - signedattr;
@@ -601,57 +508,33 @@ PK11_ImportPrivateKeyInfoAndReturnKey(PK
goto loser;
}
prepare_dh_priv_key_export_for_asn1(lpk);
keyTemplate = SECKEY_DHPrivateKeyExportTemplate;
paramTemplate = NULL;
paramDest = NULL;
lpk->keyType = dhKey;
break;
-#ifndef NSS_DISABLE_ECC
- case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
- prepare_ec_priv_key_export_for_asn1(lpk);
- keyTemplate = SECKEY_ECPrivateKeyExportTemplate;
- paramTemplate = NULL;
- paramDest = NULL;
- lpk->keyType = ecKey;
- break;
-#endif /* NSS_DISABLE_ECC */
default:
keyTemplate = NULL;
paramTemplate = NULL;
paramDest = NULL;
break;
}
if (!keyTemplate) {
goto loser;
}
/* decode the private key and any algorithm parameters */
- rv = SEC_QuickDERDecodeItem(arena, lpk, keyTemplate, &pki->privateKey);
+ rv = SEC_ASN1DecodeItem(arena, lpk, keyTemplate, &pki->privateKey);
if (rv != SECSuccess) {
goto loser;
}
-
-#ifndef NSS_DISABLE_ECC
- if (lpk->keyType == ecKey) {
- /* Convert length in bits to length in bytes. */
- lpk->u.ec.publicValue.len >>= 3;
-
- /* Always override curveOID, we're ignoring any given value. */
- rv = SECITEM_CopyItem(arena, &lpk->u.ec.curveOID,
- &pki->algorithm.parameters);
- if (rv != SECSuccess) {
- goto loser;
- }
- }
-#endif /* NSS_DISABLE_ECC */
-
if (paramDest && paramTemplate) {
rv = SEC_ASN1DecodeItem(arena, paramDest, paramTemplate,
&(pki->algorithm.parameters));
if (rv != SECSuccess) {
goto loser;
}
}
--- a/security/nss/lib/pk11wrap/pk11wrap.gyp
+++ b/security/nss/lib/pk11wrap/pk11wrap.gyp
@@ -2,69 +2,50 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
{
'includes': [
'../../coreconf/config.gypi'
],
'targets': [
{
- 'target_name': 'pk11wrap_static',
- 'type': 'static_library',
- 'defines': [
- 'NSS_TEST_BUILD',
- ],
- 'dependencies': [
- 'pk11wrap_base',
- '<(DEPTH)/exports.gyp:nss_exports',
- '<(DEPTH)/lib/softoken/softoken.gyp:softokn_static',
- ],
- },
- {
'target_name': 'pk11wrap',
'type': 'static_library',
- 'dependencies': [
- 'pk11wrap_base',
- '<(DEPTH)/exports.gyp:nss_exports',
+ 'sources': [
+ 'dev3hack.c',
+ 'pk11akey.c',
+ 'pk11auth.c',
+ 'pk11cert.c',
+ 'pk11cxt.c',
+ 'pk11err.c',
+ 'pk11kea.c',
+ 'pk11list.c',
+ 'pk11load.c',
+ 'pk11mech.c',
+ 'pk11merge.c',
+ 'pk11nobj.c',
+ 'pk11obj.c',
+ 'pk11pars.c',
+ 'pk11pbe.c',
+ 'pk11pk12.c',
+ 'pk11pqg.c',
+ 'pk11sdr.c',
+ 'pk11skey.c',
+ 'pk11slot.c',
+ 'pk11util.c'
],
- },
- {
- 'target_name': 'pk11wrap_base',
- 'type': 'none',
- 'direct_dependent_settings': {
- 'sources': [
- 'dev3hack.c',
- 'pk11akey.c',
- 'pk11auth.c',
- 'pk11cert.c',
- 'pk11cxt.c',
- 'pk11err.c',
- 'pk11kea.c',
- 'pk11list.c',
- 'pk11load.c',
- 'pk11mech.c',
- 'pk11merge.c',
- 'pk11nobj.c',
- 'pk11obj.c',
- 'pk11pars.c',
- 'pk11pbe.c',
- 'pk11pk12.c',
- 'pk11pqg.c',
- 'pk11sdr.c',
- 'pk11skey.c',
- 'pk11slot.c',
- 'pk11util.c'
- ],
- },
- },
+ 'dependencies': [
+ '<(DEPTH)/exports.gyp:nss_exports'
+ ]
+ }
],
'target_defaults': {
'defines': [
'SHLIB_SUFFIX=\"<(dll_suffix)\"',
'SHLIB_PREFIX=\"<(dll_prefix)\"',
'SHLIB_VERSION=\"3\"',
'SOFTOKEN_SHLIB_VERSION=\"3\"'
]
},
'variables': {
'module': 'nss'
}
-}
+}
\ No newline at end of file
--- a/security/nss/lib/pkcs12/p12d.c
+++ b/security/nss/lib/pkcs12/p12d.c
@@ -1330,33 +1330,21 @@ sec_pkcs12_decoder_verify_mac(SEC_PKCS12
integrityMech = CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN;
break;
case SEC_OID_MD5:
integrityMech = CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN;
break;
case SEC_OID_MD2:
integrityMech = CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN;
break;
- case SEC_OID_SHA224:
- integrityMech = CKM_NSS_PKCS12_PBE_SHA224_HMAC_KEY_GEN;
- break;
- case SEC_OID_SHA256:
- integrityMech = CKM_NSS_PKCS12_PBE_SHA256_HMAC_KEY_GEN;
- break;
- case SEC_OID_SHA384:
- integrityMech = CKM_NSS_PKCS12_PBE_SHA384_HMAC_KEY_GEN;
- break;
- case SEC_OID_SHA512:
- integrityMech = CKM_NSS_PKCS12_PBE_SHA512_HMAC_KEY_GEN;
- break;
default:
goto loser;
}
- symKey = PK11_KeyGen(NULL, integrityMech, params, 0, NULL);
+ symKey = PK11_KeyGen(NULL, integrityMech, params, 20, NULL);
PK11_DestroyPBEParams(params);
params = NULL;
if (!symKey)
goto loser;
/* init hmac */
pk11cx = PK11_CreateContextBySymKey(sec_pkcs12_algtag_to_mech(algtag),
CKA_SIGN, symKey, &ignore);
if (!pk11cx) {
--- a/security/nss/lib/pki/cryptocontext.c
+++ b/security/nss/lib/pki/cryptocontext.c
@@ -42,20 +42,17 @@ nssCryptoContext_Create(
return rvCC;
}
NSS_IMPLEMENT PRStatus
NSSCryptoContext_Destroy(NSSCryptoContext *cc)
{
PRStatus status = PR_SUCCESS;
- PORT_Assert(cc && cc->certStore);
- if (!cc) {
- return PR_FAILURE;
- }
+ PORT_Assert(cc->certStore);
if (cc->certStore) {
status = nssCertificateStore_Destroy(cc->certStore);
if (status == PR_FAILURE) {
return status;
}
} else {
status = PR_FAILURE;
}
@@ -91,18 +88,18 @@ NSSCryptoContext_GetTrustDomain(NSSCrypt
NSS_IMPLEMENT NSSCertificate *
NSSCryptoContext_FindOrImportCertificate(
NSSCryptoContext *cc,
NSSCertificate *c)
{
NSSCertificate *rvCert = NULL;
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
nss_SetError(NSS_ERROR_INVALID_ARGUMENT);
return rvCert;
}
rvCert = nssCertificateStore_FindOrAdd(cc->certStore, c);
if (rvCert == c && c->object.cryptoContext != cc) {
PORT_Assert(!c->object.cryptoContext);
c->object.cryptoContext = cc;
}
@@ -144,18 +141,18 @@ NSSCryptoContext_ImportEncodedPKIXCertif
}
NSS_IMPLEMENT PRStatus
nssCryptoContext_ImportTrust(
NSSCryptoContext *cc,
NSSTrust *trust)
{
PRStatus nssrv;
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return PR_FAILURE;
}
nssrv = nssCertificateStore_AddTrust(cc->certStore, trust);
#if 0
if (nssrv == PR_SUCCESS) {
trust->object.cryptoContext = cc;
}
#endif
@@ -163,18 +160,18 @@ nssCryptoContext_ImportTrust(
}
NSS_IMPLEMENT PRStatus
nssCryptoContext_ImportSMIMEProfile(
NSSCryptoContext *cc,
nssSMIMEProfile *profile)
{
PRStatus nssrv;
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return PR_FAILURE;
}
nssrv = nssCertificateStore_AddSMIMEProfile(cc->certStore, profile);
#if 0
if (nssrv == PR_SUCCESS) {
profile->object.cryptoContext = cc;
}
#endif
@@ -187,18 +184,18 @@ NSSCryptoContext_FindBestCertificateByNi
const NSSUTF8 *name,
NSSTime *timeOpt, /* NULL for "now" */
NSSUsage *usage,
NSSPolicies *policiesOpt /* NULL for none */
)
{
NSSCertificate **certs;
NSSCertificate *rvCert = NULL;
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return NULL;
}
certs = nssCertificateStore_FindCertificatesByNickname(cc->certStore,
name,
NULL, 0, NULL);
if (certs) {
rvCert = nssCertificateArray_FindBestCertificate(certs,
timeOpt,
@@ -213,36 +210,36 @@ NSS_IMPLEMENT NSSCertificate **
NSSCryptoContext_FindCertificatesByNickname(
NSSCryptoContext *cc,
NSSUTF8 *name,
NSSCertificate *rvOpt[],
PRUint32 maximumOpt, /* 0 for no max */
NSSArena *arenaOpt)
{
NSSCertificate **rvCerts;
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return NULL;
}
rvCerts = nssCertificateStore_FindCertificatesByNickname(cc->certStore,
name,
rvOpt,
maximumOpt,
arenaOpt);
return rvCerts;
}
NSS_IMPLEMENT NSSCertificate *
NSSCryptoContext_FindCertificateByIssuerAndSerialNumber(
NSSCryptoContext *cc,
NSSDER *issuer,
NSSDER *serialNumber)
{
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return NULL;
}
return nssCertificateStore_FindCertificateByIssuerAndSerialNumber(
cc->certStore,
issuer,
serialNumber);
}
@@ -251,18 +248,18 @@ NSSCryptoContext_FindBestCertificateBySu
NSSCryptoContext *cc,
NSSDER *subject,
NSSTime *timeOpt,
NSSUsage *usage,
NSSPolicies *policiesOpt)
{
NSSCertificate **certs;
NSSCertificate *rvCert = NULL;
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return NULL;
}
certs = nssCertificateStore_FindCertificatesBySubject(cc->certStore,
subject,
NULL, 0, NULL);
if (certs) {
rvCert = nssCertificateArray_FindBestCertificate(certs,
timeOpt,
@@ -277,18 +274,18 @@ NSS_IMPLEMENT NSSCertificate **
nssCryptoContext_FindCertificatesBySubject(
NSSCryptoContext *cc,
NSSDER *subject,
NSSCertificate *rvOpt[],
PRUint32 maximumOpt, /* 0 for no max */
NSSArena *arenaOpt)
{
NSSCertificate **rvCerts;
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return NULL;
}
rvCerts = nssCertificateStore_FindCertificatesBySubject(cc->certStore,
subject,
rvOpt,
maximumOpt,
arenaOpt);
return rvCerts;
@@ -331,18 +328,18 @@ NSSCryptoContext_FindCertificatesByNameC
return NULL;
}
NSS_IMPLEMENT NSSCertificate *
NSSCryptoContext_FindCertificateByEncodedCertificate(
NSSCryptoContext *cc,
NSSBER *encodedCertificate)
{
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return NULL;
}
return nssCertificateStore_FindCertificateByEncodedCertificate(
cc->certStore,
encodedCertificate);
}
NSS_IMPLEMENT NSSCertificate *
@@ -351,18 +348,18 @@ NSSCryptoContext_FindBestCertificateByEm
NSSASCII7 *email,
NSSTime *timeOpt,
NSSUsage *usage,
NSSPolicies *policiesOpt)
{
NSSCertificate **certs;
NSSCertificate *rvCert = NULL;
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return NULL;
}
certs = nssCertificateStore_FindCertificatesByEmail(cc->certStore,
email,
NULL, 0, NULL);
if (certs) {
rvCert = nssCertificateArray_FindBestCertificate(certs,
timeOpt,
@@ -377,18 +374,18 @@ NSS_IMPLEMENT NSSCertificate **
NSSCryptoContext_FindCertificatesByEmail(
NSSCryptoContext *cc,
NSSASCII7 *email,
NSSCertificate *rvOpt[],
PRUint32 maximumOpt, /* 0 for no max */
NSSArena *arenaOpt)
{
NSSCertificate **rvCerts;
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return NULL;
}
rvCerts = nssCertificateStore_FindCertificatesByEmail(cc->certStore,
email,
rvOpt,
maximumOpt,
arenaOpt);
return rvCerts;
@@ -486,30 +483,30 @@ NSSCryptoContext_FindUserCertificatesFor
return NULL;
}
NSS_IMPLEMENT NSSTrust *
nssCryptoContext_FindTrustForCertificate(
NSSCryptoContext *cc,
NSSCertificate *cert)
{
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return NULL;
}
return nssCertificateStore_FindTrustForCertificate(cc->certStore, cert);
}
NSS_IMPLEMENT nssSMIMEProfile *
nssCryptoContext_FindSMIMEProfileForCertificate(
NSSCryptoContext *cc,
NSSCertificate *cert)
{
- PORT_Assert(cc && cc->certStore);
- if (!cc || !cc->certStore) {
+ PORT_Assert(cc->certStore);
+ if (!cc->certStore) {
return NULL;
}
return nssCertificateStore_FindSMIMEProfileForCertificate(cc->certStore,
cert);
}
NSS_IMPLEMENT PRStatus
NSSCryptoContext_GenerateKeyPair(
--- a/security/nss/lib/softoken/legacydb/dbmshim.c
+++ b/security/nss/lib/softoken/legacydb/dbmshim.c
@@ -42,16 +42,19 @@
/* a Shim data structure. This data structure has a db built into it. */
typedef struct DBSStr DBS;
struct DBSStr {
DB db;
char *blobdir;
int mode;
PRBool readOnly;
+ PRFileMap *dbs_mapfile;
+ unsigned char *dbs_addr;
+ PRUint32 dbs_len;
char staticBlobArea[BLOB_BUF_LEN];
};
/*
* return true if the Datablock contains a blobtype
*/
static PRBool
dbs_IsBlob(DBT *blobData)
@@ -236,16 +239,53 @@ loser:
PR_smprintf_free(file);
}
/* don't let close or delete reset the error */
PR_SetError(error, 0);
return -1;
}
/*
+ * we need to keep a address map in memory between calls to DBM.
+ * remember what we have mapped can close it when we get another dbm
+ * call.
+ *
+ * NOTE: Not all platforms support mapped files. This code is designed to
+ * detect this at runtime. If map files aren't supported the OS will indicate
+ * this by failing the PR_Memmap call. In this case we emulate mapped files
+ * by just reading in the file into regular memory. We signal this state by
+ * making dbs_mapfile NULL and dbs_addr non-NULL.
+ */
+
+static void
+dbs_freemap(DBS *dbsp)
+{
+ if (dbsp->dbs_mapfile) {
+ PR_MemUnmap(dbsp->dbs_addr, dbsp->dbs_len);
+ PR_CloseFileMap(dbsp->dbs_mapfile);
+ dbsp->dbs_mapfile = NULL;
+ dbsp->dbs_addr = NULL;
+ dbsp->dbs_len = 0;
+ } else if (dbsp->dbs_addr) {
+ PORT_Free(dbsp->dbs_addr);
+ dbsp->dbs_addr = NULL;
+ dbsp->dbs_len = 0;
+ }
+ return;
+}
+
+static void
+dbs_setmap(DBS *dbsp, PRFileMap *mapfile, unsigned char *addr, PRUint32 len)
+{
+ dbsp->dbs_mapfile = mapfile;
+ dbsp->dbs_addr = addr;
+ dbsp->dbs_len = len;
+}
+
+/*
* platforms that cannot map the file need to read it into a temp buffer.
*/
static unsigned char *
dbs_EmulateMap(PRFileDesc *filed, int len)
{
unsigned char *addr;
PRInt32 dataRead;
@@ -272,16 +312,17 @@ dbs_EmulateMap(PRFileDesc *filed, int le
* data points to the blob record on input and the real record (if we could
* read it) on output. if there is an error data is not modified.
*/
static int
dbs_readBlob(DBS *dbsp, DBT *data)
{
char *file = NULL;
PRFileDesc *filed = NULL;
+ PRFileMap *mapfile = NULL;
unsigned char *addr = NULL;
int error;
int len = -1;
file = dbs_getBlobFilePath(dbsp->blobdir, data);
if (!file) {
goto loser;
}
@@ -298,24 +339,28 @@ dbs_readBlob(DBS *dbsp, DBT *data)
* https://msdn.microsoft.com/en-us/library/windows/desktop/aa366761(v=vs.85).aspx
* Let's always use the emulated map, i.e. read the file.
*/
addr = dbs_EmulateMap(filed, len);
if (addr == NULL) {
goto loser;
}
PR_Close(filed);
+ dbs_setmap(dbsp, mapfile, addr, len);
data->data = addr;
data->size = len;
return 0;
loser:
/* preserve the error code */
error = PR_GetError();
+ if (mapfile) {
+ PR_CloseFileMap(mapfile);
+ }
if (filed) {
PR_Close(filed);
}
PR_SetError(error, 0);
return -1;
}
/*
@@ -323,32 +368,36 @@ loser:
*/
static int
dbs_get(const DB *dbs, const DBT *key, DBT *data, unsigned int flags)
{
int ret;
DBS *dbsp = (DBS *)dbs;
DB *db = (DB *)dbs->internal;
+ dbs_freemap(dbsp);
+
ret = (*db->get)(db, key, data, flags);
if ((ret == 0) && dbs_IsBlob(data)) {
ret = dbs_readBlob(dbsp, data);
}
return (ret);
}
static int
dbs_put(const DB *dbs, DBT *key, const DBT *data, unsigned int flags)
{
DBT blob;
int ret = 0;
DBS *dbsp = (DBS *)dbs;
DB *db = (DB *)dbs->internal;
+ dbs_freemap(dbsp);
+
/* If the db is readonly, just pass the data down to rdb and let it fail */
if (!dbsp->readOnly) {
DBT oldData;
int ret1;
/* make sure the current record is deleted if it's a blob */
ret1 = (*db->get)(db, key, &oldData, 0);
if ((ret1 == 0) && flags == R_NOOVERWRITE) {
@@ -371,26 +420,32 @@ dbs_put(const DB *dbs, DBT *key, const D
}
return (ret);
}
static int
dbs_sync(const DB *dbs, unsigned int flags)
{
DB *db = (DB *)dbs->internal;
+ DBS *dbsp = (DBS *)dbs;
+
+ dbs_freemap(dbsp);
+
return (*db->sync)(db, flags);
}
static int
dbs_del(const DB *dbs, const DBT *key, unsigned int flags)
{
int ret;
DBS *dbsp = (DBS *)dbs;
DB *db = (DB *)dbs->internal;
+ dbs_freemap(dbsp);
+
if (!dbsp->readOnly) {
DBT oldData;
ret = (*db->get)(db, key, &oldData, 0);
if ((ret == 0) && dbs_IsBlob(&oldData)) {
dbs_removeBlob(dbsp, &oldData);
}
}
@@ -399,32 +454,35 @@ dbs_del(const DB *dbs, const DBT *key, u
static int
dbs_seq(const DB *dbs, DBT *key, DBT *data, unsigned int flags)
{
int ret;
DBS *dbsp = (DBS *)dbs;
DB *db = (DB *)dbs->internal;
+ dbs_freemap(dbsp);
+
ret = (*db->seq)(db, key, data, flags);
if ((ret == 0) && dbs_IsBlob(data)) {
/* don't return a blob read as an error so traversals keep going */
(void)dbs_readBlob(dbsp, data);
}
return (ret);
}
static int
dbs_close(DB *dbs)
{
DBS *dbsp = (DBS *)dbs;
DB *db = (DB *)dbs->internal;
int ret;
+ dbs_freemap(dbsp);
ret = (*db->close)(db);
PORT_Free(dbsp->blobdir);
PORT_Free(dbsp);
return ret;
}
static int
dbs_fd(const DB *dbs)
@@ -505,16 +563,19 @@ dbsopen(const char *dbname, int flags, i
dbs = &dbsp->db;
dbsp->blobdir = dbs_mkBlobDirName(dbname);
if (dbsp->blobdir == NULL) {
goto loser;
}
dbsp->mode = mode;
dbsp->readOnly = (PRBool)(flags == NO_RDONLY);
+ dbsp->dbs_mapfile = NULL;
+ dbsp->dbs_addr = NULL;
+ dbsp->dbs_len = 0;
/* the real dbm call */
db = dbopen(dbname, flags, mode, type, &dbs_hashInfo);
if (db == NULL) {
goto loser;
}
dbs->internal = (void *)db;
dbs->type = type;
--- a/security/nss/lib/softoken/lowpbe.c
+++ b/security/nss/lib/softoken/lowpbe.c
@@ -403,16 +403,17 @@ loser:
result = NULL;
} else {
result->len = dkLen;
}
return result;
}
+#define HMAC_BUFFER 64
#define NSSPBE_ROUNDUP(x, y) ((((x) + ((y)-1)) / (y)) * (y))
#define NSSPBE_MIN(x, y) ((x) < (y) ? (x) : (y))
/*
* This is the extended PBE function defined by the final PKCS #12 spec.
*/
static SECItem *
nsspkcs5_PKCS12PBE(const SECHashObject *hashObject,
NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem,
@@ -424,44 +425,40 @@ nsspkcs5_PKCS12PBE(const SECHashObject *
unsigned char *S, *P;
SECItem *A = NULL, B, D, I;
SECItem *salt = &pbe_param->salt;
unsigned int c, i = 0;
unsigned int hashLen;
int iter;
unsigned char *iterBuf;
void *hash = NULL;
- unsigned int bufferLength;
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (!arena) {
return NULL;
}
/* how many hash object lengths are needed */
c = (bytesNeeded + (hashLength - 1)) / hashLength;
- /* 64 if 0 < hashLength <= 32, 128 if 32 < hashLength <= 64 */
- bufferLength = NSSPBE_ROUNDUP(hashLength * 2, 64);
-
/* initialize our buffers */
- D.len = bufferLength;
+ D.len = HMAC_BUFFER;
/* B and D are the same length, use one alloc go get both */
D.data = (unsigned char *)PORT_ArenaZAlloc(arena, D.len * 2);
B.len = D.len;
B.data = D.data + D.len;
/* if all goes well, A will be returned, so don't use our temp arena */
A = SECITEM_AllocItem(NULL, NULL, c * hashLength);
if (A == NULL) {
goto loser;
}
- SLen = NSSPBE_ROUNDUP(salt->len, bufferLength);
- PLen = NSSPBE_ROUNDUP(pwitem->len, bufferLength);
+ SLen = NSSPBE_ROUNDUP(salt->len, HMAC_BUFFER);
+ PLen = NSSPBE_ROUNDUP(pwitem->len, HMAC_BUFFER);
I.len = SLen + PLen;
I.data = (unsigned char *)PORT_ArenaZAlloc(arena, I.len);
if (I.data == NULL) {
goto loser;
}
/* S & P are only used to initialize I */
S = I.data;
--- a/security/nss/lib/softoken/pkcs11.c
+++ b/security/nss/lib/softoken/pkcs11.c
@@ -475,20 +475,16 @@ static const struct mechanismList mechan
{ CKM_PBE_SHA1_RC2_128_CBC, { 128, 128, CKF_GENERATE }, PR_TRUE },
{ CKM_PBE_SHA1_RC4_40, { 40, 40, CKF_GENERATE }, PR_TRUE },
{ CKM_PBE_SHA1_RC4_128, { 128, 128, CKF_GENERATE }, PR_TRUE },
{ CKM_PBA_SHA1_WITH_SHA1_HMAC, { 20, 20, CKF_GENERATE }, PR_TRUE },
{ CKM_PKCS5_PBKD2, { 1, 256, CKF_GENERATE }, PR_TRUE },
{ CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN, { 20, 20, CKF_GENERATE }, PR_TRUE },
{ CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN, { 16, 16, CKF_GENERATE }, PR_TRUE },
{ CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN, { 16, 16, CKF_GENERATE }, PR_TRUE },
- { CKM_NSS_PKCS12_PBE_SHA224_HMAC_KEY_GEN, { 28, 28, CKF_GENERATE }, PR_TRUE },
- { CKM_NSS_PKCS12_PBE_SHA256_HMAC_KEY_GEN, { 32, 32, CKF_GENERATE }, PR_TRUE },
- { CKM_NSS_PKCS12_PBE_SHA384_HMAC_KEY_GEN, { 48, 48, CKF_GENERATE }, PR_TRUE },
- { CKM_NSS_PKCS12_PBE_SHA512_HMAC_KEY_GEN, { 64, 64, CKF_GENERATE }, PR_TRUE },
/* ------------------ AES Key Wrap (also encrypt) ------------------- */
{ CKM_NETSCAPE_AES_KEY_WRAP, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
{ CKM_NETSCAPE_AES_KEY_WRAP_PAD, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE },
/* --------------------------- J-PAKE -------------------------------- */
{ CKM_NSS_JPAKE_ROUND1_SHA1, { 0, 0, CKF_GENERATE }, PR_TRUE },
{ CKM_NSS_JPAKE_ROUND1_SHA256, { 0, 0, CKF_GENERATE }, PR_TRUE },
{ CKM_NSS_JPAKE_ROUND1_SHA384, { 0, 0, CKF_GENERATE }, PR_TRUE },
{ CKM_NSS_JPAKE_ROUND1_SHA512, { 0, 0, CKF_GENERATE }, PR_TRUE },
@@ -3144,21 +3140,19 @@ nsc_CommonFinalize(CK_VOID_PTR pReserved
/* tell freeBL to clean up after itself */
BL_Cleanup();
/* reset fork status in freebl. We must do this before BL_Unload so that
* this call doesn't force freebl to be reloaded. */
BL_SetForkState(PR_FALSE);
-#ifndef NSS_TEST_BUILD
/* unload freeBL shared library from memory. This may only decrement the
* OS refcount if it's been loaded multiple times, eg. by libssl */
BL_Unload();
-#endif
/* clean up the default OID table */
SECOID_Shutdown();
/* reset fork status in util */
UTIL_SetForkState(PR_FALSE);
nsc_init = PR_FALSE;
--- a/security/nss/lib/softoken/pkcs11c.c
+++ b/security/nss/lib/softoken/pkcs11c.c
@@ -3966,32 +3966,16 @@ nsc_SetupHMACKeyGen(CK_MECHANISM_PTR pMe
case CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN:
params->hashType = HASH_AlgMD5;
params->keyLen = 16;
break;
case CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN:
params->hashType = HASH_AlgMD2;
params->keyLen = 16;
break;
- case CKM_NSS_PKCS12_PBE_SHA224_HMAC_KEY_GEN:
- params->hashType = HASH_AlgSHA224;
- params->keyLen = 28;
- break;
- case CKM_NSS_PKCS12_PBE_SHA256_HMAC_KEY_GEN:
- params->hashType = HASH_AlgSHA256;
- params->keyLen = 32;
- break;
- case CKM_NSS_PKCS12_PBE_SHA384_HMAC_KEY_GEN:
- params->hashType = HASH_AlgSHA384;
- params->keyLen = 48;
- break;
- case CKM_NSS_PKCS12_PBE_SHA512_HMAC_KEY_GEN:
- params->hashType = HASH_AlgSHA512;
- params->keyLen = 64;
- break;
default:
PORT_FreeArena(arena, PR_TRUE);
return CKR_MECHANISM_INVALID;
}
*pbe = params;
return CKR_OK;
}
@@ -4200,20 +4184,16 @@ NSC_GenerateKey(CK_SESSION_HANDLE hSessi
key_type = CKK_GENERIC_SECRET;
key_length = 48;
key_gen_type = nsc_ssl;
break;
case CKM_PBA_SHA1_WITH_SHA1_HMAC:
case CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN:
case CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN:
case CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN:
- case CKM_NSS_PKCS12_PBE_SHA224_HMAC_KEY_GEN:
- case CKM_NSS_PKCS12_PBE_SHA256_HMAC_KEY_GEN:
- case CKM_NSS_PKCS12_PBE_SHA384_HMAC_KEY_GEN:
- case CKM_NSS_PKCS12_PBE_SHA512_HMAC_KEY_GEN:
key_gen_type = nsc_pbe;
key_type = CKK_GENERIC_SECRET;
crv = nsc_SetupHMACKeyGen(pMechanism, &pbe_param);
break;
case CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC:
faultyPBE3DES = PR_TRUE;
/* fall through */
case CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC:
@@ -7262,16 +7242,24 @@ NSC_DeriveKey(CK_SESSION_HANDLE hSession
if (rv != SECSuccess) {
goto ec_loser;
}
ecPoint = newPoint;
}
if (mechanism == CKM_ECDH1_COFACTOR_DERIVE) {
withCofactor = PR_TRUE;
+ } else {
+ /* When not using cofactor derivation, one should
+ * validate the public key to avoid small subgroup
+ * attacks.
+ */
+ if (EC_ValidatePublicKey(&privKey->u.ec.ecParams, &ecPoint) != SECSuccess) {
+ goto ec_loser;
+ }
}
rv = ECDH_Derive(&ecPoint, &privKey->u.ec.ecParams, &ecScalar,
withCofactor, &tmp);
PORT_Free(ecScalar.data);
ecScalar.data = NULL;
if (privKey != sourceKey->objectInfo) {
nsslowkey_DestroyPrivateKey(privKey);
--- a/security/nss/lib/softoken/softkver.h
+++ b/security/nss/lib/softoken/softkver.h
@@ -16,16 +16,16 @@
/*
* Softoken's major version, minor version, patch level, build number,
* and whether this is a beta release.
*
* The format of the version string should be
* "<major version>.<minor version>[.<patch level>[.<build number>]][ <ECC>][ <Beta>]"
*/
-#define SOFTOKEN_VERSION "3.30" SOFTOKEN_ECC_STRING " Beta"
+#define SOFTOKEN_VERSION "3.28.1" SOFTOKEN_ECC_STRING
#define SOFTOKEN_VMAJOR 3
-#define SOFTOKEN_VMINOR 30
-#define SOFTOKEN_VPATCH 0
+#define SOFTOKEN_VMINOR 28
+#define SOFTOKEN_VPATCH 1
#define SOFTOKEN_VBUILD 0
-#define SOFTOKEN_BETA PR_TRUE
+#define SOFTOKEN_BETA PR_FALSE
#endif /* _SOFTKVER_H_ */
--- a/security/nss/lib/softoken/softoken.gyp
+++ b/security/nss/lib/softoken/softoken.gyp
@@ -2,75 +2,45 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
{
'includes': [
'../../coreconf/config.gypi'
],
'targets': [
{
- 'target_name': 'softokn_static',
+ 'target_name': 'softokn',
'type': 'static_library',
- 'defines': [
- 'NSS_TEST_BUILD',
+ 'sources': [
+ 'fipsaudt.c',
+ 'fipstest.c',
+ 'fipstokn.c',
+ 'jpakesftk.c',
+ 'lgglue.c',
+ 'lowkey.c',
+ 'lowpbe.c',
+ 'padbuf.c',
+ 'pkcs11.c',
+ 'pkcs11c.c',
+ 'pkcs11u.c',
+ 'sdb.c',
+ 'sftkdb.c',
+ 'sftkhmac.c',
+ 'sftkpars.c',
+ 'sftkpwd.c',
+ 'softkver.c',
+ 'tlsprf.c'
],
'dependencies': [
- 'softokn_base',
- '<(DEPTH)/exports.gyp:nss_exports',
- '<(DEPTH)/lib/freebl/freebl.gyp:freebl_static',
- ],
- 'conditions': [
- [ 'use_system_sqlite==1', {
- 'dependencies': [
- '<(DEPTH)/lib/sqlite/sqlite.gyp:sqlite3',
- ],
- }, {
- 'dependencies': [
- '<(DEPTH)/lib/sqlite/sqlite.gyp:sqlite',
- ],
- }],
- ],
- },
- {
- 'target_name': 'softokn',
- 'type': 'static_library',
- 'dependencies': [
- 'softokn_base',
'<(DEPTH)/exports.gyp:nss_exports',
'<(DEPTH)/lib/sqlite/sqlite.gyp:sqlite3',
'<(DEPTH)/lib/freebl/freebl.gyp:freebl',
]
},
{
- 'target_name': 'softokn_base',
- 'type': 'none',
- 'direct_dependent_settings': {
- 'sources': [
- 'fipsaudt.c',
- 'fipstest.c',
- 'fipstokn.c',
- 'jpakesftk.c',
- 'lgglue.c',
- 'lowkey.c',
- 'lowpbe.c',
- 'padbuf.c',
- 'pkcs11.c',
- 'pkcs11c.c',
- 'pkcs11u.c',
- 'sdb.c',
- 'sftkdb.c',
- 'sftkhmac.c',
- 'sftkpars.c',
- 'sftkpwd.c',
- 'softkver.c',
- 'tlsprf.c'
- ],
- },
- },
- {
'target_name': 'softokn3',
'type': 'shared_library',
'dependencies': [
'softokn',
],
'conditions': [
[ 'moz_fold_libs==0', {
'dependencies': [
--- a/security/nss/lib/softoken/softoken.h
+++ b/security/nss/lib/softoken/softoken.h
@@ -178,17 +178,17 @@ extern PRBool sftk_fatalError;
*/
#ifdef SOLARIS
/* Solaris 8, s9 use PID checks, s10 uses pthread_atfork */
#define CHECK_FORK_MIXED
-#elif defined(LINUX) || defined(__GLIBC__)
+#elif defined(LINUX)
#define CHECK_FORK_PTHREAD
#else
/* Other Unix platforms use only PID checks. Even if pthread_atfork is
* available, the behavior of dlclose isn't guaranteed by POSIX to
* unregister the fork handler. */
--- a/security/nss/lib/ssl/SSLerrs.h
+++ b/security/nss/lib/ssl/SSLerrs.h
@@ -499,12 +499,9 @@ ER3(SSL_ERROR_BAD_2ND_CLIENT_HELLO, (SSL
ER3(SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION, (SSL_ERROR_BASE + 157),
"SSL expected a signature algorithms extension.")
ER3(SSL_ERROR_MALFORMED_PSK_KEY_EXCHANGE_MODES, (SSL_ERROR_BASE + 158),
"SSL received a malformed PSK key exchange modes extension.")
ER3(SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES, (SSL_ERROR_BASE + 159),
- "SSL expected a PSK key exchange modes extension.")
-
-ER3(SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA, (SSL_ERROR_BASE + 160),
- "SSL got a pre-TLS 1.3 version even though we sent early data.")
+ "SSL expected a missing PSK key exchange modes extension.")
--- a/security/nss/lib/ssl/config.mk
+++ b/security/nss/lib/ssl/config.mk
@@ -57,11 +57,15 @@ endif
endif
ifdef NSS_SSL_ENABLE_ZLIB
DEFINES += -DNSS_SSL_ENABLE_ZLIB
include $(CORE_DEPTH)/coreconf/zlib.mk
endif
+ifndef NSS_ENABLE_TLS_1_3
+NSS_DISABLE_TLS_1_3=1
+endif
+
ifdef NSS_DISABLE_TLS_1_3
DEFINES += -DNSS_DISABLE_TLS_1_3
endif
--- a/security/nss/lib/ssl/dtlscon.c
+++ b/security/nss/lib/ssl/dtlscon.c
@@ -230,36 +230,16 @@ dtls_RetransmitDetected(sslSocket *ss)
} else {
PORT_Assert(ss->ssl3.hs.rtTimerCb == NULL);
/* ... and ignore it. */
}
return rv;
}
-static SECStatus
-dtls_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *data, PRBool last)
-{
-
- /* At this point we are advancing our state machine, so we can free our last
- * flight of messages. */
- dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
- ss->ssl3.hs.recvdHighWater = -1;
-
- /* Reset the timer to the initial value if the retry counter
- * is 0, per Sec. 4.2.4.1 */
- dtls_CancelTimer(ss);
- if (ss->ssl3.hs.rtRetries == 0) {
- ss->ssl3.hs.rtTimeoutMs = DTLS_RETRANSMIT_INITIAL_MS;
- }
-
- return ssl3_HandleHandshakeMessage(ss, data, ss->ssl3.hs.msg_len,
- last);
-}
-
/* Called only from ssl3_HandleRecord, for each (deciphered) DTLS record.
* origBuf is the decrypted ssl record content and is expected to contain
* complete handshake records
* Caller must hold the handshake and RecvBuf locks.
*
* Note that this code uses msg_len for two purposes:
*
* (1) To pass the length to ssl3_HandleHandshakeMessage()
@@ -344,20 +324,33 @@ dtls_HandleHandshake(sslSocket *ss, sslB
*/
if ((message_seq == ss->ssl3.hs.recvMessageSeq) &&
(fragment_offset == 0) &&
(fragment_length == message_length)) {
/* Complete next message. Process immediately */
ss->ssl3.hs.msg_type = (SSL3HandshakeType)type;
ss->ssl3.hs.msg_len = message_length;
- rv = dtls_HandleHandshakeMessage(ss, buf.buf,
+ /* At this point we are advancing our state machine, so
+ * we can free our last flight of messages */
+ dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
+ ss->ssl3.hs.recvdHighWater = -1;
+ dtls_CancelTimer(ss);
+
+ /* Reset the timer to the initial value if the retry counter
+ * is 0, per Sec. 4.2.4.1 */
+ if (ss->ssl3.hs.rtRetries == 0) {
+ ss->ssl3.hs.rtTimeoutMs = DTLS_RETRANSMIT_INITIAL_MS;
+ }
+
+ rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len,
buf.len == fragment_length);
if (rv == SECFailure) {
- break; /* Discard the remainder of the record. */
+ /* Do not attempt to process rest of messages in this record */
+ break;
}
} else {
if (message_seq < ss->ssl3.hs.recvMessageSeq) {
/* Case 3: we do an immediate retransmit if we're
* in a waiting state. */
rv = dtls_RetransmitDetected(ss);
break;
} else if (message_seq > ss->ssl3.hs.recvMessageSeq) {
@@ -448,21 +441,34 @@ dtls_HandleHandshake(sslSocket *ss, sslB
ss->ssl3.hs.recvdHighWater++;
} else {
break;
}
}
/* If we have all the bytes, then we are good to go */
if (ss->ssl3.hs.recvdHighWater == ss->ssl3.hs.msg_len) {
- rv = dtls_HandleHandshakeMessage(ss, ss->ssl3.hs.msg_body.buf,
- buf.len == fragment_length);
+ ss->ssl3.hs.recvdHighWater = -1;
+
+ rv = ssl3_HandleHandshakeMessage(
+ ss,
+ ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len,
+ buf.len == fragment_length);
+ if (rv == SECFailure)
+ break; /* Skip rest of record */
- if (rv == SECFailure) {
- break; /* Discard the rest of the record. */
+ /* At this point we are advancing our state machine, so
+ * we can free our last flight of messages */
+ dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
+ dtls_CancelTimer(ss);
+
+ /* If there have been no retries this time, reset the
+ * timer value to the default per Section 4.2.4.1 */
+ if (ss->ssl3.hs.rtRetries == 0) {
+ ss->ssl3.hs.rtTimeoutMs = DTLS_RETRANSMIT_INITIAL_MS;
}
}
}
}
buf.buf += fragment_length;
buf.len -= fragment_length;
}
--- a/security/nss/lib/ssl/ssl.def
+++ b/security/nss/lib/ssl/ssl.def
@@ -216,14 +216,8 @@ SSL_NamedGroupConfig;
;+ global:
SSL_ExportEarlyKeyingMaterial;
SSL_SendAdditionalKeyShares;
SSL_SignatureSchemePrefSet;
SSL_SignatureSchemePrefGet;
;+ local:
;+*;
;+};
-;+NSS_3.30 { # NSS 3.30 release
-;+ global:
-SSL_SetSessionTicketKeyPair;
-;+ local:
-;+*;
-;+};
--- a/security/nss/lib/ssl/ssl.gyp
+++ b/security/nss/lib/ssl/ssl.gyp
@@ -58,39 +58,34 @@
[ 'ssl_enable_zlib==1', {
'dependencies': [
'<(DEPTH)/lib/zlib/zlib.gyp:nss_zlib'
],
'defines': [
'NSS_SSL_ENABLE_ZLIB',
],
}],
- [ 'fuzz_tls==1', {
+ [ 'fuzz==1', {
'defines': [
'UNSAFE_FUZZER_MODE',
],
}],
- [ 'mozilla_client==1', {
- 'defines': [
- 'NSS_ENABLE_TLS13_SHORT_HEADERS',
- ],
- }],
],
'dependencies': [
'<(DEPTH)/exports.gyp:nss_exports',
+ '<(DEPTH)/lib/freebl/freebl.gyp:freebl',
],
},
{
'target_name': 'ssl3',
'type': 'shared_library',
'dependencies': [
'ssl',
'<(DEPTH)/lib/nss/nss.gyp:nss3',
'<(DEPTH)/lib/util/util.gyp:nssutil3',
- '<(DEPTH)/lib/freebl/freebl.gyp:freebl',
],
'variables': {
'mapfile': 'ssl.def'
}
}
],
'target_defaults': {
'defines': [
--- a/security/nss/lib/ssl/ssl.h
+++ b/security/nss/lib/ssl/ssl.h
@@ -223,17 +223,17 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRF
*
* When this option is set, the server's session tickets will contain
* a flag indicating that it accepts 0-RTT. When resuming such a
* session, PR_Write() on the client will be allowed immediately after
* starting the handshake and PR_Read() on the server will be allowed
* on the server to read that data. Calls to
* SSL_GetPreliminaryChannelInfo() and SSL_GetNextProto()
* can be made used during this period to learn about the channel
- * parameters.
+ * parameters [TODO(ekr@rtfm.com): This hasn't landed yet].
*
* The transition between the 0-RTT and 1-RTT modes is marked by the
* handshake callback.
*
* WARNING: 0-RTT data has different anti-replay and PFS properties than
* the rest of the TLS data. See [draft-ietf-tls-tls13; Section 6.2.3]
* for more details.
*/
@@ -910,29 +910,16 @@ SSL_IMPORT SECStatus SSL_ConfigSecureSer
** SSL_ConfigSecureServerCert can be used to pass a certificate chain.
*/
SSL_IMPORT SECStatus
SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert,
const CERTCertificateList *certChainOpt,
SECKEYPrivateKey *key, SSLKEAType kea);
/*
-** SSL_SetSessionTicketKeyPair configures an asymmetric key pair for use in
-** wrapping session ticket keys, used by the server. This function currently
-** only accepts an RSA public/private key pair.
-**
-** Prior to the existence of this function, NSS used an RSA private key
-** associated with a configured certificate to perform session ticket
-** encryption. If this function isn't used, the keys provided with a configured
-** RSA certificate are used for wrapping session ticket keys.
-*/
-SSL_IMPORT SECStatus
-SSL_SetSessionTicketKeyPair(SECKEYPublicKey *pubKey, SECKEYPrivateKey *privKey);
-
-/*
** Configure a secure server's session-id cache. Define the maximum number
** of entries in the cache, the longevity of the entires, and the directory
** where the cache files will be placed. These values can be zero, and
** if so, the implementation will choose defaults.
** This version of the function is for use in applications that have only one
** process that uses the cache (even if that process has multiple threads).
*/
SSL_IMPORT SECStatus SSL_ConfigServerSessionIDCache(int maxCacheEntries,
--- a/security/nss/lib/ssl/ssl3con.c
+++ b/security/nss/lib/ssl/ssl3con.c
@@ -268,16 +268,20 @@ ssl_CompressionEnabled(sslSocket *ss, SS
}
static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = {
ct_RSA_sign,
ct_ECDSA_sign,
ct_DSS_sign,
};
+/* This global item is used only in servers. It is is initialized by
+** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
+*/
+CERTDistNames *ssl3_server_ca_list = NULL;
static SSL3Statistics ssl3stats;
/* Record protection algorithms, indexed by SSL3BulkCipher.
*
* The |max_records| field (|mr| below) is set to a number that is higher than
* recommended in some literature (esp. TLS 1.3) because we currently abort the
* connection when this limit is reached and we want to ensure that we only
* rarely hit this limit. See bug 1268745 for details.
@@ -854,31 +858,33 @@ ssl_HasCert(const sslSocket *ss, SSLAuth
PRCList *cursor;
if (authType == ssl_auth_null || authType == ssl_auth_psk || authType == ssl_auth_tls13_any) {
return PR_TRUE;
}
for (cursor = PR_NEXT_LINK(&ss->serverCerts);
cursor != &ss->serverCerts;
cursor = PR_NEXT_LINK(cursor)) {
sslServerCert *cert = (sslServerCert *)cursor;
+ if (cert->certType.authType != authType) {
+ continue;
+ }
if (!cert->serverKeyPair ||
!cert->serverKeyPair->privKey ||
- !cert->serverCertChain ||
- !SSL_CERT_IS(cert, authType)) {
+ !cert->serverCertChain) {
continue;
}
/* When called from ssl3_config_match_init(), all the EC curves will be
* enabled, so this will essentially do nothing (unless we implement
* curve configuration). However, once we have seen the
* supported_groups extension and this is called from config_match(),
* this will filter out certificates with an unsupported curve. */
if ((authType == ssl_auth_ecdsa ||
authType == ssl_auth_ecdh_ecdsa ||
authType == ssl_auth_ecdh_rsa) &&
- !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
+ !ssl_NamedGroupEnabled(ss, cert->certType.namedCurve)) {
continue;
}
return PR_TRUE;
}
return PR_FALSE;
}
const ssl3BulkCipherDef *
@@ -1033,19 +1039,18 @@ Null_Cipher(void *ctx, unsigned char *ou
const unsigned char *input, int inputLen)
{
if (inputLen > maxOutputLen) {
*outputLen = 0; /* Match PK11_CipherOp in setting outputLen */
PORT_SetError(SEC_ERROR_OUTPUT_LEN);
return SECFailure;
}
*outputLen = inputLen;
- if (inputLen > 0 && input != output) {
+ if (input != output)
PORT_Memcpy(output, input, inputLen);
- }
return SECSuccess;
}
/*
* SSL3 Utility functions
*/
/* allowLargerPeerVersion controls whether the function will select the
@@ -1078,21 +1083,20 @@ ssl3_NegotiateVersion(sslSocket *ss, SSL
/* Used by the client when the server produces a version number.
* This reads, validates, and normalizes the value. */
SECStatus
ssl_ClientReadVersion(sslSocket *ss, SSL3Opaque **b, unsigned int *len,
SSL3ProtocolVersion *version)
{
SSL3ProtocolVersion v;
- PRUint32 temp;
- SECStatus rv;
-
- rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, b, len);
- if (rv != SECSuccess) {
+ PRInt32 temp;
+
+ temp = ssl3_ConsumeHandshakeNumber(ss, 2, b, len);
+ if (temp < 0) {
return SECFailure; /* alert has been sent */
}
#ifdef TLS_1_3_DRAFT_VERSION
if (temp == SSL_LIBRARY_VERSION_TLS_1_3) {
(void)SSL3_SendAlert(ss, alert_fatal, protocol_version);
PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
return SECFailure;
@@ -1615,16 +1619,20 @@ ssl3_SetupPendingCipherSpec(sslSocket *s
pwSpec->decodeContext = NULL;
pwSpec->mac_size = pwSpec->mac_def->mac_size;
pwSpec->compression_method = ss->ssl3.hs.compression;
pwSpec->compressContext = NULL;
pwSpec->decompressContext = NULL;
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ PORT_Assert(ss->ssl3.hs.kea_def->ephemeral);
+ PORT_Assert(pwSpec->cipher_def->type == type_aead);
+ }
ssl_ReleaseSpecWriteLock(ss); /*******************************/
return SECSuccess;
}
#ifdef NSS_SSL_ENABLE_ZLIB
#define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream)
static SECStatus
@@ -3111,30 +3119,24 @@ ssl3_HandleNoCertificate(sslSocket *ss)
** ssl3_HandleRecord <-
**
*/
SECStatus
SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
{
PRUint8 bytes[2];
SECStatus rv;
- PRBool needHsLock = !ssl_HaveSSL3HandshakeLock(ss);
-
- /* Check that if I need the HS lock I also need the Xmit lock */
- PORT_Assert(!needHsLock || !ssl_HaveXmitBufLock(ss));
SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
SSL_GETPID(), ss->fd, level, desc));
bytes[0] = level;
bytes[1] = desc;
- if (needHsLock) {
- ssl_GetSSL3HandshakeLock(ss);
- }
+ ssl_GetSSL3HandshakeLock(ss);
if (level == alert_fatal) {
if (!ss->opt.noCache && ss->sec.ci.sid) {
ss->sec.uncache(ss->sec.ci.sid);
}
}
ssl_GetXmitBufLock(ss);
rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
if (rv == SECSuccess) {
@@ -3142,19 +3144,17 @@ SSL3_SendAlert(sslSocket *ss, SSL3AlertL
sent = ssl3_SendRecord(ss, NULL, content_alert, bytes, 2,
(desc == no_certificate) ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
}
if (level == alert_fatal) {
ss->ssl3.fatalAlertSent = PR_TRUE;
}
ssl_ReleaseXmitBufLock(ss);
- if (needHsLock) {
- ssl_ReleaseSSL3HandshakeLock(ss);
- }
+ ssl_ReleaseSSL3HandshakeLock(ss);
return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
}
/*
* Send illegal_parameter alert. Set generic error number.
*/
static SECStatus
ssl3_IllegalParameter(sslSocket *ss)
@@ -4325,17 +4325,17 @@ ssl3_AppendHandshakeHeader(sslSocket *ss
* stream "b" (which is *length bytes long). Copy them into buffer "v".
* Reduces *length by bytes. Advances *b by bytes.
*
* If this function returns SECFailure, it has already sent an alert,
* and has set a generic error code. The caller should probably
* override the generic error code by setting another.
*/
SECStatus
-ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes, SSL3Opaque **b,
+ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b,
PRUint32 *length)
{
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
if ((PRUint32)bytes > *length) {
return ssl3_DecodeError(ss);
}
@@ -4343,43 +4343,47 @@ ssl3_ConsumeHandshake(sslSocket *ss, voi
PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
*b += bytes;
*length -= bytes;
return SECSuccess;
}
/* Read up the next "bytes" number of bytes from the (decrypted) input
* stream "b" (which is *length bytes long), and interpret them as an
- * integer in network byte order. Sets *num to the received value.
+ * integer in network byte order. Returns the received value.
* Reduces *length by bytes. Advances *b by bytes.
*
+ * Returns SECFailure (-1) on failure.
+ * This value is indistinguishable from the equivalent received value.
+ * Only positive numbers are to be received this way.
+ * Thus, the largest value that may be sent this way is 0x7fffffff.
* On error, an alert has been sent, and a generic error code has been set.
*/
-SECStatus
-ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num, PRUint32 bytes,
- SSL3Opaque **b, PRUint32 *length)
+PRInt32
+ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b,
+ PRUint32 *length)
{
PRUint8 *buf = *b;
int i;
+ PRInt32 num = 0;
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
-
- *num = 0;
- if (bytes > *length || bytes > sizeof(*num)) {
+ PORT_Assert(bytes <= sizeof num);
+
+ if ((PRUint32)bytes > *length) {
return ssl3_DecodeError(ss);
}
PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
- for (i = 0; i < bytes; i++) {
- *num = (*num << 8) + buf[i];
- }
+ for (i = 0; i < bytes; i++)
+ num = (num << 8) + buf[i];
*b += bytes;
*length -= bytes;
- return SECSuccess;
+ return num;
}
/* Read in two values from the incoming decrypted byte stream "b", which is
* *length bytes long. The first value is a number whose size is "bytes"
* bytes long. The second value is a byte-string whose size is the value
* of the first number received. The latter byte-string, and its length,
* is returned in the SECItem i.
*
@@ -4387,32 +4391,31 @@ ssl3_ConsumeHandshakeNumber(sslSocket *s
* On error, an alert has been sent, and a generic error code has been set.
*
* RADICAL CHANGE for NSS 3.11. All callers of this function make copies
* of the data returned in the SECItem *i, so making a copy of it here
* is simply wasteful. So, This function now just sets SECItem *i to
* point to the values in the buffer **b.
*/
SECStatus
-ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRUint32 bytes,
+ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes,
SSL3Opaque **b, PRUint32 *length)
{
- PRUint32 count;
- SECStatus rv;
+ PRInt32 count;
PORT_Assert(bytes <= 3);
i->len = 0;
i->data = NULL;
i->type = siBuffer;
- rv = ssl3_ConsumeHandshakeNumber(ss, &count, bytes, b, length);
- if (rv != SECSuccess) {
+ count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length);
+ if (count < 0) { /* Can't test for SECSuccess here. */
return SECFailure;
}
if (count > 0) {
- if (count > *length) {
+ if ((PRUint32)count > *length) {
return ssl3_DecodeError(ss);
}
i->data = *b;
i->len = count;
*b += count;
*length -= count;
}
return SECSuccess;
@@ -4673,21 +4676,20 @@ ssl_IsRsaPssSignatureScheme(SSLSignature
* SignatureAndHashAlgorithm) structure from |b| and puts the resulting value
* into |out|. |b| and |length| are updated accordingly.
*
* See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
SECStatus
ssl_ConsumeSignatureScheme(sslSocket *ss, SSL3Opaque **b,
PRUint32 *length, SSLSignatureScheme *out)
{
- PRUint32 tmp;
- SECStatus rv;
-
- rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
- if (rv != SECSuccess) {
+ PRInt32 tmp;
+
+ tmp = ssl3_ConsumeHandshakeNumber(ss, 2, b, length);
+ if (tmp < 0) {
return SECFailure; /* Error code set already. */
}
if (!ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) {
PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
return SECFailure;
}
*out = (SSLSignatureScheme)tmp;
return SECSuccess;
@@ -5572,105 +5574,76 @@ ssl3_HandleHelloRequest(sslSocket *ss)
ssl_GetXmitBufLock(ss);
rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
ssl_ReleaseXmitBufLock(ss);
return rv;
}
+#define UNKNOWN_WRAP_MECHANISM 0x7fffffff
+
static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
CKM_DES3_ECB,
CKM_CAST5_ECB,
CKM_DES_ECB,
CKM_KEY_WRAP_LYNKS,
CKM_IDEA_ECB,
CKM_CAST3_ECB,
CKM_CAST_ECB,
CKM_RC5_ECB,
CKM_RC2_ECB,
CKM_CDMF_ECB,
CKM_SKIPJACK_WRAP,
CKM_SKIPJACK_CBC64,
CKM_AES_ECB,
CKM_CAMELLIA_ECB,
- CKM_SEED_ECB
+ CKM_SEED_ECB,
+ UNKNOWN_WRAP_MECHANISM
};
-static SECStatus
-ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech, unsigned int *wrapMechIndex)
-{
- unsigned int i;
- for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
- if (wrapMechanismList[i] == mech) {
- *wrapMechIndex = i;
- return SECSuccess;
- }
- }
- PORT_Assert(0);
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
-}
-
-/* Each process sharing the server session ID cache has its own array of SymKey
- * pointers for the symmetric wrapping keys that are used to wrap the master
- * secrets. There is one key for each authentication type. These Symkeys
- * correspond to the wrapped SymKeys kept in the server session cache.
- */
-const SSLAuthType ssl_wrap_key_auth_type[SSL_NUM_WRAP_KEYS] = {
- ssl_auth_rsa_decrypt,
- ssl_auth_rsa_sign,
- ssl_auth_rsa_pss,
- ssl_auth_ecdsa,
- ssl_auth_ecdh_rsa,
- ssl_auth_ecdh_ecdsa
-};
-
-static SECStatus
-ssl_FindIndexByWrapKey(const sslServerCert *serverCert, unsigned int *wrapKeyIndex)
-{
- unsigned int i;
- for (i = 0; i < SSL_NUM_WRAP_KEYS; ++i) {
- if (SSL_CERT_IS(serverCert, ssl_wrap_key_auth_type[i])) {
- *wrapKeyIndex = i;
- return SECSuccess;
- }
- }
- /* Can't assert here because we still get people using DSA certificates. */
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
+static int
+ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech)
+{
+ const CK_MECHANISM_TYPE *pMech = wrapMechanismList;
+
+ while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) {
+ ++pMech;
+ }
+ return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1
+ : (pMech - wrapMechanismList);
}
static PK11SymKey *
ssl_UnwrapSymWrappingKey(
SSLWrappedSymWrappingKey *pWswk,
SECKEYPrivateKey *svrPrivKey,
- unsigned int wrapKeyIndex,
+ SSLAuthType authType,
CK_MECHANISM_TYPE masterWrapMech,
void *pwArg)
{
PK11SymKey *unwrappedWrappingKey = NULL;
SECItem wrappedKey;
PK11SymKey *Ks;
SECKEYPublicKey pubWrapKey;
ECCWrappedKeyInfo *ecWrapped;
/* found the wrapping key on disk. */
PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
- PORT_Assert(pWswk->wrapKeyIndex == wrapKeyIndex);
+ PORT_Assert(pWswk->authType == authType);
if (pWswk->symWrapMechanism != masterWrapMech ||
- pWswk->wrapKeyIndex != wrapKeyIndex) {
+ pWswk->authType != authType) {
goto loser;
}
wrappedKey.type = siBuffer;
wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
wrappedKey.len = pWswk->wrappedSymKeyLen;
PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
- switch (ssl_wrap_key_auth_type[wrapKeyIndex]) {
+ switch (authType) {
case ssl_auth_rsa_decrypt:
case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
unwrappedWrappingKey =
PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
masterWrapMech, CKA_UNWRAP, 0);
break;
@@ -5733,18 +5706,24 @@ ssl_UnwrapSymWrappingKey(
PORT_Assert(0);
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
goto loser;
}
loser:
return unwrappedWrappingKey;
}
+/* Each process sharing the server session ID cache has its own array of SymKey
+ * pointers for the symmetric wrapping keys that are used to wrap the master
+ * secrets. There is one key for each authentication type. These Symkeys
+ * correspond to the wrapped SymKeys kept in the server session cache.
+ */
+
typedef struct {
- PK11SymKey *symWrapKey[SSL_NUM_WRAP_KEYS];
+ PK11SymKey *symWrapKey[ssl_auth_size];
} ssl3SymWrapKey;
static PZLock *symWrapKeysLock = NULL;
static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS];
SECStatus
ssl_FreeSymWrapKeysLock(void)
{
@@ -5762,17 +5741,17 @@ SSL3_ShutdownServerCache(void)
{
int i, j;
if (!symWrapKeysLock)
return SECSuccess; /* lock was never initialized */
PZ_Lock(symWrapKeysLock);
/* get rid of all symWrapKeys */
for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
- for (j = 0; j < SSL_NUM_WRAP_KEYS; ++j) {
+ for (j = 0; j < ssl_auth_size; ++j) {
PK11SymKey **pSymWrapKey;
pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
if (*pSymWrapKey) {
PK11_FreeSymKey(*pSymWrapKey);
*pSymWrapKey = NULL;
}
}
}
@@ -5796,59 +5775,55 @@ ssl_InitSymWrapKeysLock(void)
*
* Note that this function performs some fairly inadvisable functions with
* certificate private keys. ECDSA keys are used with ECDH; similarly, RSA
* signing keys are used to encrypt. Bug 1248320.
*/
PK11SymKey *
ssl3_GetWrappingKey(sslSocket *ss,
PK11SlotInfo *masterSecretSlot,
+ const sslServerCert *serverCert,
CK_MECHANISM_TYPE masterWrapMech,
void *pwArg)
{
SSLAuthType authType;
SECKEYPrivateKey *svrPrivKey;
SECKEYPublicKey *svrPubKey = NULL;
PK11SymKey *unwrappedWrappingKey = NULL;
PK11SymKey **pSymWrapKey;
CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM;
int length;
- unsigned int wrapMechIndex;
- unsigned int wrapKeyIndex;
+ int symWrapMechIndex;
SECStatus rv;
SECItem wrappedKey;
SSLWrappedSymWrappingKey wswk;
PK11SymKey *Ks = NULL;
SECKEYPublicKey *pubWrapKey = NULL;
SECKEYPrivateKey *privWrapKey = NULL;
ECCWrappedKeyInfo *ecWrapped;
- const sslServerCert *serverCert = ss->sec.serverCert;
PORT_Assert(serverCert);
PORT_Assert(serverCert->serverKeyPair);
PORT_Assert(serverCert->serverKeyPair->privKey);
PORT_Assert(serverCert->serverKeyPair->pubKey);
if (!serverCert || !serverCert->serverKeyPair ||
!serverCert->serverKeyPair->privKey ||
!serverCert->serverKeyPair->pubKey) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return NULL; /* hmm */
}
-
- rv = ssl_FindIndexByWrapKey(serverCert, &wrapKeyIndex);
- if (rv != SECSuccess)
- return NULL; /* unusable wrapping key. */
-
- rv = ssl_FindIndexByWrapMechanism(masterWrapMech, &wrapMechIndex);
- if (rv != SECSuccess)
+ authType = serverCert->certType.authType;
+ svrPrivKey = serverCert->serverKeyPair->privKey;
+
+ symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech);
+ PORT_Assert(symWrapMechIndex >= 0);
+ if (symWrapMechIndex < 0)
return NULL; /* invalid masterWrapMech. */
- authType = ssl_wrap_key_auth_type[wrapKeyIndex];
- svrPrivKey = serverCert->serverKeyPair->privKey;
- pSymWrapKey = &symWrapKeys[wrapMechIndex].symWrapKey[wrapKeyIndex];
+ pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[authType];
ssl_InitSessionCacheLocks(PR_TRUE);
PZ_Lock(symWrapKeysLock);
unwrappedWrappingKey = *pSymWrapKey;
if (unwrappedWrappingKey != NULL) {
if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
@@ -5857,21 +5832,20 @@ ssl3_GetWrappingKey(sslSocket *ss,
}
/* slot series has changed, so this key is no good any more. */
PK11_FreeSymKey(unwrappedWrappingKey);
*pSymWrapKey = unwrappedWrappingKey = NULL;
}
/* Try to get wrapped SymWrapping key out of the (disk) cache. */
/* Following call fills in wswk on success. */
- rv = ssl_GetWrappingKey(wrapMechIndex, wrapKeyIndex, &wswk);
- if (rv == SECSuccess) {
+ if (ssl_GetWrappingKey(symWrapMechIndex, authType, &wswk)) {
/* found the wrapped sym wrapping key on disk. */
unwrappedWrappingKey =
- ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
+ ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, authType,
masterWrapMech, pwArg);
if (unwrappedWrappingKey) {
goto install;
}
}
if (!masterSecretSlot) /* caller doesn't want to create a new one. */
goto loser;
@@ -6010,36 +5984,35 @@ ssl3_GetWrappingKey(sslSocket *ss,
if (rv != SECSuccess) {
ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
goto loser;
}
PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
wswk.symWrapMechanism = masterWrapMech;
+ wswk.symWrapMechIndex = symWrapMechIndex;
wswk.asymWrapMechanism = asymWrapMechanism;
- wswk.wrapMechIndex = wrapMechIndex;
- wswk.wrapKeyIndex = wrapKeyIndex;
+ wswk.authType = authType;
wswk.wrappedSymKeyLen = wrappedKey.len;
/* put it on disk. */
/* If the wrapping key for this KEA type has already been set,
* then abandon the value we just computed and
* use the one we got from the disk.
*/
- rv = ssl_SetWrappingKey(&wswk);
- if (rv == SECSuccess) {
+ if (ssl_SetWrappingKey(&wswk)) {
/* somebody beat us to it. The original contents of our wswk
* has been replaced with the content on disk. Now, discard
* the key we just created and unwrap this new one.
*/
PK11_FreeSymKey(unwrappedWrappingKey);
unwrappedWrappingKey =
- ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
+ ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, authType,
masterWrapMech, pwArg);
}
install:
if (unwrappedWrappingKey) {
*pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
}
@@ -6433,57 +6406,49 @@ ssl_PickSignatureScheme(sslSocket *ss,
}
}
}
PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
return SECFailure;
}
-static SECStatus
-ssl_PickFallbackSignatureScheme(sslSocket *ss, SECKEYPublicKey *pubKey)
-{
- PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
-
- switch (SECKEY_GetPublicKeyType(pubKey)) {
- case rsaKey:
- if (isTLS12) {
- ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1;
- } else {
- ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1md5;
- }
- break;
- case ecKey:
- ss->ssl3.hs.signatureScheme = ssl_sig_ecdsa_sha1;
- break;
- case dsaKey:
- ss->ssl3.hs.signatureScheme = ssl_sig_dsa_sha1;
- break;
- default:
- PORT_Assert(0);
- PORT_SetError(SEC_ERROR_INVALID_KEY);
- return SECFailure;
- }
- return SECSuccess;
-}
-
/* ssl3_PickServerSignatureScheme selects a signature scheme for signing the
* handshake. Most of this is determined by the key pair we are using.
* Prior to TLS 1.2, the MD5/SHA1 combination is always used. With TLS 1.2, a
* client may advertise its support for signature and hash combinations. */
static SECStatus
ssl3_PickServerSignatureScheme(sslSocket *ss)
{
sslKeyPair *keyPair = ss->sec.serverCert->serverKeyPair;
PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
if (!isTLS12 || !ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
/* If the client didn't provide any signature_algorithms extension then
* we can assume that they support SHA-1: RFC5246, Section 7.4.1.4.1. */
- return ssl_PickFallbackSignatureScheme(ss, keyPair->pubKey);
+ switch (SECKEY_GetPublicKeyType(keyPair->pubKey)) {
+ case rsaKey:
+ if (isTLS12) {
+ ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1;
+ } else {
+ ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1md5;
+ }
+ break;
+ case ecKey:
+ ss->ssl3.hs.signatureScheme = ssl_sig_ecdsa_sha1;
+ break;
+ case dsaKey:
+ ss->ssl3.hs.signatureScheme = ssl_sig_dsa_sha1;
+ break;
+ default:
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_INVALID_KEY);
+ return SECFailure;
+ }
+ return SECSuccess;
}
/* Sets error code, if needed. */
return ssl_PickSignatureScheme(ss, keyPair->pubKey, keyPair->privKey,
ss->xtnData.clientSigSchemes,
ss->xtnData.numClientSigScheme,
PR_FALSE /* requireSha1 */);
}
@@ -6491,31 +6456,19 @@ ssl3_PickServerSignatureScheme(sslSocket
static SECStatus
ssl_PickClientSignatureScheme(sslSocket *ss, const SSLSignatureScheme *schemes,
unsigned int numSchemes)
{
SECKEYPrivateKey *privKey = ss->ssl3.clientPrivateKey;
SECKEYPublicKey *pubKey;
SECStatus rv;
- PRBool isTLS13 = (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
pubKey = CERT_ExtractPublicKey(ss->ssl3.clientCertificate);
PORT_Assert(pubKey);
-
- if (!isTLS13 && numSchemes == 0) {
- /* If the server didn't provide any signature algorithms
- * then let's assume they support SHA-1. */
- rv = ssl_PickFallbackSignatureScheme(ss, pubKey);
- SECKEY_DestroyPublicKey(pubKey);
- return rv;
- }
-
- PORT_Assert(schemes && numSchemes > 0);
-
- if (!isTLS13 &&
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
(SECKEY_GetPublicKeyType(pubKey) == rsaKey ||
SECKEY_GetPublicKeyType(pubKey) == dsaKey) &&
SECKEY_PublicKeyStrengthInBits(pubKey) <= 1024) {
/* If the key is a 1024-bit RSA or DSA key, assume conservatively that
* it may be unable to sign SHA-256 hashes. This is the case for older
* Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
* older, DSA key size is at most 1024 bits and the hash function must
* be SHA-1.
@@ -6648,17 +6601,17 @@ ssl3_SetCipherSuite(sslSocket *ss, ssl3C
/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
* ssl3 ServerHello message.
* Caller must hold Handshake and RecvBuf locks.
*/
static SECStatus
ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
{
- PRUint32 temp;
+ PRInt32 temp; /* allow for consume number failure */
PRBool suite_found = PR_FALSE;
int i;
int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
SECStatus rv;
SECItem sidBytes = { siBuffer, NULL, 0 };
PRBool isTLS = PR_FALSE;
SSL3AlertDescription desc = illegal_parameter;
#ifndef TLS_1_3_DRAFT_VERSION
@@ -6691,31 +6644,21 @@ ssl3_HandleServerHello(sslSocket *ss, SS
ss->ssl3.clientPrivateKey = NULL;
}
rv = ssl_ClientReadVersion(ss, &b, &length, &ss->version);
if (rv != SECSuccess) {
goto loser; /* alert has been sent */
}
- /* The server didn't pick 1.3 although we either received a
- * HelloRetryRequest, or we prepared to send early app data. */
- if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
- if (ss->ssl3.hs.helloRetry) {
- /* SSL3_SendAlert() will uncache the SID. */
- desc = illegal_parameter;
- errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
- goto alert_loser;
- }
- if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
- /* SSL3_SendAlert() will uncache the SID. */
- desc = illegal_parameter;
- errCode = SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA;
- goto alert_loser;
- }
+ /* We got a HelloRetryRequest, but the server didn't pick 1.3. Scream. */
+ if (ss->ssl3.hs.helloRetry && ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ desc = illegal_parameter;
+ errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+ goto alert_loser;
}
/* Check that the server negotiated the same version as it did
* in the first handshake. This isn't really the best place for
* us to be getting this version number, but it's what we have.
* (1294697). */
if (ss->firstHsDone && (ss->version != ss->ssl3.crSpec->version)) {
desc = illegal_parameter;
@@ -6773,18 +6716,18 @@ ssl3_HandleServerHello(sslSocket *ss, SS
if (sidBytes.len > SSL3_SESSIONID_BYTES) {
if (isTLS)
desc = decode_error;
goto alert_loser; /* malformed. */
}
}
/* find selected cipher suite in our list. */
- rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, &b, &length);
- if (rv != SECSuccess) {
+ temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
+ if (temp < 0) {
goto loser; /* alert has been sent */
}
i = ssl3_config_match_init(ss);
PORT_Assert(i > 0);
if (i <= 0) {
errCode = PORT_GetError();
goto loser;
}
@@ -6819,18 +6762,18 @@ ssl3_HandleServerHello(sslSocket *ss, SS
if (rv != SECSuccess) {
desc = internal_error;
errCode = PORT_GetError();
goto alert_loser;
}
if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
/* find selected compression method in our list. */
- rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 1, &b, &length);
- if (rv != SECSuccess) {
+ temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
+ if (temp < 0) {
goto loser; /* alert has been sent */
}
suite_found = PR_FALSE;
for (i = 0; i < ssl_compression_method_count; i++) {
if (temp == ssl_compression_methods[i]) {
if (!ssl_CompressionEnabled(ss, ssl_compression_methods[i])) {
break; /* failure */
}
@@ -7062,29 +7005,16 @@ ssl3_HandleServerHelloPart2(sslSocket *s
} while (0);
}
if (sid_match)
SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok);
else
SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses);
- /* We tried to resume a 1.3 session but the server negotiated 1.2. */
- if (ss->statelessResume) {
- PORT_Assert(sid->version == SSL_LIBRARY_VERSION_TLS_1_3);
- PORT_Assert(ss->ssl3.hs.currentSecret);
-
- /* Reset resumption state, only used by 1.3 code. */
- ss->statelessResume = PR_FALSE;
-
- /* Clear TLS 1.3 early data traffic key. */
- PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
- ss->ssl3.hs.currentSecret = NULL;
- }
-
/* throw the old one away */
sid->u.ssl3.keys.resumable = PR_FALSE;
ss->sec.uncache(sid);
ssl_FreeSID(sid);
/* get a new sid */
ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
if (sid == NULL) {
@@ -7341,47 +7271,46 @@ typedef struct dnameNode {
* Called from:
* ssl3_HandleCertificateRequest
* tls13_HandleCertificateRequest
*/
SECStatus
ssl3_ParseCertificateRequestCAs(sslSocket *ss, SSL3Opaque **b, PRUint32 *length,
PLArenaPool *arena, CERTDistNames *ca_list)
{
- PRUint32 remaining;
+ PRInt32 remaining;
int nnames = 0;
dnameNode *node;
- SECStatus rv;
int i;
- rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 2, b, length);
- if (rv != SECSuccess)
+ remaining = ssl3_ConsumeHandshakeNumber(ss, 2, b, length);
+ if (remaining < 0)
return SECFailure; /* malformed, alert has been sent */
- if (remaining > *length)
+ if ((PRUint32)remaining > *length)
goto alert_loser;
ca_list->head = node = PORT_ArenaZNew(arena, dnameNode);
if (node == NULL)
goto no_mem;
while (remaining > 0) {
- PRUint32 len;
+ PRInt32 len;
if (remaining < 2)
goto alert_loser; /* malformed */
- rv = ssl3_ConsumeHandshakeNumber(ss, &len, 2, b, length);
- if (rv != SECSuccess)
+ node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, b, length);
+ if (len <= 0)
return SECFailure; /* malformed, alert has been sent */
- if (len == 0 || remaining < len + 2)
- goto alert_loser; /* malformed */
remaining -= 2;
- node->name.len = len;
+ if (remaining < len)
+ goto alert_loser; /* malformed */
+
node->name.data = *b;
*b += len;
*length -= len;
remaining -= len;
nnames++;
if (remaining <= 0)
break; /* success */
@@ -7419,69 +7348,63 @@ alert_loser:
SECStatus
ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
SSLSignatureScheme **schemesOut,
unsigned int *numSchemesOut,
unsigned char **b, unsigned int *len)
{
SECStatus rv;
SECItem buf;
- SSLSignatureScheme *schemes = NULL;
+ SSLSignatureScheme *schemes;
unsigned int numSchemes = 0;
unsigned int max;
rv = ssl3_ExtConsumeHandshakeVariable(ss, &buf, 2, b, len);
if (rv != SECSuccess) {
return SECFailure;
}
- /* An odd-length value is invalid. */
- if ((buf.len & 1) != 0) {
+ /* An empty or odd-length value is invalid. */
+ if (buf.len == 0 || (buf.len & 1) != 0) {
ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
return SECFailure;
}
- /* Let the caller decide whether to alert here. */
- if (buf.len == 0) {
- goto done;
- }
-
/* Limit the number of schemes we read. */
max = PR_MIN(buf.len / 2, MAX_SIGNATURE_SCHEMES);
if (arena) {
schemes = PORT_ArenaZNewArray(arena, SSLSignatureScheme, max);
} else {
schemes = PORT_ZNewArray(SSLSignatureScheme, max);
}
if (!schemes) {
ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
return SECFailure;
}
for (; max; --max) {
- PRUint32 tmp;
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &buf.data, &buf.len);
- if (rv != SECSuccess) {
+ PRInt32 tmp;
+ tmp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &buf.data, &buf.len);
+ if (tmp < 0) {
PORT_Assert(0);
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
if (ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) {
schemes[numSchemes++] = (SSLSignatureScheme)tmp;
}
}
if (!numSchemes) {
if (!arena) {
PORT_Free(schemes);
}
schemes = NULL;
}
-done:
*schemesOut = schemes;
*numSchemesOut = numSchemes;
return SECSuccess;
}
/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
* a complete ssl3 Certificate Request message.
* Caller must hold Handshake and RecvBuf locks.
@@ -8299,27 +8222,29 @@ ssl3_SelectServerCert(sslSocket *ss)
* b) the right named curve (EC only)
*
* We might want to do some sort of ranking here later. For now, it's all
* based on what order they are configured in. */
for (cursor = PR_NEXT_LINK(&ss->serverCerts);
cursor != &ss->serverCerts;
cursor = PR_NEXT_LINK(cursor)) {
sslServerCert *cert = (sslServerCert *)cursor;
- if (!SSL_CERT_IS(cert, kea_def->authKeyType)) {
+ if (cert->certType.authType != kea_def->authKeyType) {
continue;
}
- if (SSL_CERT_IS_EC(cert) &&
- !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
+ if ((cert->certType.authType == ssl_auth_ecdsa ||
+ cert->certType.authType == ssl_auth_ecdh_rsa ||
+ cert->certType.authType == ssl_auth_ecdh_ecdsa) &&
+ !ssl_NamedGroupEnabled(ss, cert->certType.namedCurve)) {
continue;
}
/* Found one. */
ss->sec.serverCert = cert;
- ss->sec.authType = kea_def->authKeyType;
+ ss->sec.authType = cert->certType.authType;
ss->sec.authKeyBits = cert->serverKeyBits;
/* Don't pick a signature scheme if we aren't going to use it. */
if (kea_def->signKeyType == nullKey) {
return SECSuccess;
}
return ssl3_PickServerSignatureScheme(ss);
}
@@ -8331,17 +8256,17 @@ ssl3_SelectServerCert(sslSocket *ss)
/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
* ssl3 Client Hello message.
* Caller must hold Handshake and RecvBuf locks.
*/
static SECStatus
ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
{
sslSessionID *sid = NULL;
- PRUint32 tmp;
+ PRInt32 tmp;
unsigned int i;
SECStatus rv;
int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
SSL3AlertDescription desc = illegal_parameter;
SSL3AlertLevel level = alert_fatal;
SSL3ProtocolVersion version;
TLSExtension *versionExtension;
SECItem sidBytes = { siBuffer, NULL, 0 };
@@ -8391,18 +8316,18 @@ ssl3_HandleClientHello(sslSocket *ss, SS
*/
ssl3_ResetExtensionData(&ss->xtnData);
ss->statelessResume = PR_FALSE;
if (IS_DTLS(ss)) {
dtls_RehandshakeCleanup(ss);
}
- rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, &b, &length);
- if (rv != SECSuccess)
+ tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
+ if (tmp < 0)
goto loser; /* malformed, alert already sent */
/* Translate the version. */
if (IS_DTLS(ss)) {
ss->clientHelloVersion = version =
dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
} else {
ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
@@ -8445,19 +8370,19 @@ ssl3_HandleClientHello(sslSocket *ss, SS
* we are restarting a previous session until extensions have been
* parsed, since we might have received a SessionTicket extension.
* Note: we allow extensions even when negotiating SSL3 for the sake
* of interoperability (and backwards compatibility).
*/
if (length) {
/* Get length of hello extensions */
- PRUint32 extension_length;
- rv = ssl3_ConsumeHandshakeNumber(ss, &extension_length, 2, &b, &length);
- if (rv != SECSuccess) {
+ PRInt32 extension_length;
+ extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
+ if (extension_length < 0) {
goto loser; /* alert already sent */
}
if (extension_length != length) {
ssl3_DecodeError(ss); /* send alert */
goto loser;
}
rv = ssl3_ParseExtensions(ss, &b, &length);
@@ -8549,17 +8474,17 @@ ssl3_HandleClientHello(sslSocket *ss, SS
/* Now parse the rest of the extensions. */
rv = ssl3_HandleParsedExtensions(ss, client_hello);
if (rv != SECSuccess) {
goto loser; /* malformed */
}
/* If the ClientHello version is less than our maximum version, check for a
* TLS_FALLBACK_SCSV and reject the connection if found. */
- if (ss->vrange.max > ss->version) {
+ if (ss->vrange.max > ss->clientHelloVersion) {
for (i = 0; i + 1 < suites.len; i += 2) {
PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
if (suite_i != TLS_FALLBACK_SCSV)
continue;
desc = inappropriate_fallback;
errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
goto alert_loser;
}
@@ -8833,30 +8758,26 @@ compression_found:
* as if the client had sent us no sid to begin with, and make a new one.
* The exception here is attempts to resume extended_master_secret
* sessions without the extension, which causes an alert.
*/
if (sid != NULL)
do {
ssl3CipherSpec *pwSpec;
SECItem wrappedMS; /* wrapped key */
+ const sslServerCert *serverCert;
if (sid->version != ss->version ||
sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite ||
sid->u.ssl3.compression != ss->ssl3.hs.compression) {
break; /* not an error */
}
- /* server sids don't remember the server cert we previously sent,
- ** but they do remember the slot we originally used, so we
- ** can locate it again, provided that the current ssl socket
- ** has had its server certs configured the same as the previous one.
- */
- ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
- if (!ss->sec.serverCert || !ss->sec.serverCert->serverCert) {
+ serverCert = ssl_FindServerCert(ss, &sid->certType);
+ if (!serverCert || !serverCert->serverCert) {
/* A compatible certificate must not have been configured. It
* might not be the same certificate, but we only find that out
* when the ticket fails to decrypt. */
break;
}
/* [draft-ietf-tls-session-hash-06; Section 5.3]
* o If the original session did not use the "extended_master_secret"
@@ -8894,17 +8815,17 @@ compression_found:
ssl_GetSpecWriteLock(ss);
haveSpecWriteLock = PR_TRUE;
pwSpec = ss->ssl3.pwSpec;
if (sid->u.ssl3.keys.msIsWrapped) {
PK11SymKey *wrapKey; /* wrapping key */
CK_FLAGS keyFlags = 0;
- wrapKey = ssl3_GetWrappingKey(ss, NULL,
+ wrapKey = ssl3_GetWrappingKey(ss, NULL, serverCert,
sid->u.ssl3.masterWrapMech,
ss->pkcs11PinArg);
if (!wrapKey) {
/* we have a SID cache entry, but no wrapping key for it??? */
break;
}
if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
@@ -8953,18 +8874,23 @@ compression_found:
SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes);
ss->ssl3.hs.isResuming = PR_TRUE;
ss->sec.authType = sid->authType;
ss->sec.authKeyBits = sid->authKeyBits;
ss->sec.keaType = sid->keaType;
ss->sec.keaKeyBits = sid->keaKeyBits;
- ss->sec.localCert =
- CERT_DupCertificate(ss->sec.serverCert->serverCert);
+ /* server sids don't remember the server cert we previously sent,
+ ** but they do remember the slot we originally used, so we
+ ** can locate it again, provided that the current ssl socket
+ ** has had its server certs configured the same as the previous one.
+ */
+ ss->sec.serverCert = serverCert;
+ ss->sec.localCert = CERT_DupCertificate(serverCert->serverCert);
/* Copy cached name in to pending spec */
if (sid != NULL &&
sid->version > SSL_LIBRARY_VERSION_3_0 &&
sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
/* Set server name from sid */
SECItem *sidName = &sid->u.ssl3.srvName;
SECItem *pwsName = &ss->ssl3.hs.srvVirtName;
@@ -9672,44 +9598,69 @@ ssl3_EncodeSigAlgs(const sslSocket *ss,
if (p == buf) {
PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
return SECFailure;
}
*len = p - buf;
return SECSuccess;
}
+void
+ssl3_GetCertificateRequestCAs(sslSocket *ss, int *calen, SECItem **names,
+ int *nnames)
+{
+ SECItem *name;
+ CERTDistNames *ca_list;
+ int i;
+
+ *calen = 0;
+ *names = NULL;
+ *nnames = 0;
+
+ /* ssl3.ca_list is initialized to NULL, and never changed. */
+ ca_list = ss->ssl3.ca_list;
+ if (!ca_list) {
+ ca_list = ssl3_server_ca_list;
+ }
+
+ if (ca_list != NULL) {
+ *names = ca_list->names;
+ *nnames = ca_list->nnames;
+ }
+
+ for (i = 0, name = *names; i < *nnames; i++, name++) {
+ *calen += 2 + name->len;
+ }
+}
+
static SECStatus
ssl3_SendCertificateRequest(sslSocket *ss)
{
PRBool isTLS12;
const PRUint8 *certTypes;
SECStatus rv;
int length;
SECItem *names;
- unsigned int calen;
- unsigned int nnames;
+ int calen;
+ int nnames;
SECItem *name;
int i;
int certTypesLength;
PRUint8 sigAlgs[MAX_SIGNATURE_SCHEMES * 2];
unsigned int sigAlgsLength = 0;
SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
- rv = ssl_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
- if (rv != SECSuccess) {
- return rv;
- }
+ ssl3_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
certTypes = certificate_types;
certTypesLength = sizeof certificate_types;
length = 1 + certTypesLength + 2 + calen;
if (isTLS12) {
rv = ssl3_EncodeSigAlgs(ss, sigAlgs, sizeof(sigAlgs), &sigAlgsLength);
if (rv != SECSuccess) {
return rv;
@@ -9973,19 +9924,19 @@ ssl3_HandleRSAClientKeyExchange(sslSocke
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
enc_pms.data = b;
enc_pms.len = length;
if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
- PRUint32 kLen;
- rv = ssl3_ConsumeHandshakeNumber(ss, &kLen, 2, &enc_pms.data, &enc_pms.len);
- if (rv != SECSuccess) {
+ PRInt32 kLen;
+ kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len);
+ if (kLen < 0) {
PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
return SECFailure;
}
if ((unsigned)kLen < enc_pms.len) {
enc_pms.len = kLen;
}
}
@@ -10295,17 +10246,16 @@ loser:
return rv;
}
static SECStatus
ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
{
SECStatus rv;
SECItem ticketData;
- PRUint32 temp;
SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
@@ -10316,29 +10266,24 @@ ssl3_HandleNewSessionTicket(sslSocket *s
PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
return SECFailure;
}
/* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
* until it has verified the server's Finished message." See the comment in
* ssl3_FinishHandshake for more details.
*/
- ss->ssl3.hs.newSessionTicket.received_timestamp = PR_Now();
+ ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time();
if (length < 4) {
(void)SSL3_SendAlert(ss, alert_fatal, decode_error);
PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
return SECFailure;
}
-
- rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 4, &b, &length);
- if (rv != SECSuccess) {
- PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
- return SECFailure;
- }
- ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = temp;
+ ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint =
+ (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length);
rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length);
if (rv != SECSuccess || length != 0) {
(void)SSL3_SendAlert(ss, alert_fatal, decode_error);
PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
return SECFailure; /* malformed */
}
/* If the server sent a zero-length ticket, ignore it and keep the
@@ -10623,30 +10568,31 @@ ssl3_HandleCertificateStatus(sslSocket *
}
return ssl3_AuthCertificate(ss);
}
SECStatus
ssl_ReadCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
{
- PRUint32 status, len;
- SECStatus rv;
+ PRInt32 status, len;
PORT_Assert(!ss->sec.isServer);
/* Consume the CertificateStatusType enum */
- rv = ssl3_ConsumeHandshakeNumber(ss, &status, 1, &b, &length);
- if (rv != SECSuccess || status != 1 /* ocsp */) {
- return ssl3_DecodeError(ss);
- }
-
- rv = ssl3_ConsumeHandshakeNumber(ss, &len, 3, &b, &length);
- if (rv != SECSuccess || len != length) {
- return ssl3_DecodeError(ss);
+ status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
+ if (status != 1 /* ocsp */) {
+ ssl3_DecodeError(ss); /* sets error code */
+ return SECFailure;
+ }
+
+ len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
+ if (len != length) {
+ ssl3_DecodeError(ss); /* sets error code */
+ return SECFailure;
}
#define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
if (length > MAX_CERTSTATUS_LEN) {
ssl3_DecodeError(ss); /* sets error code */
return SECFailure;
}
#undef MAX_CERTSTATUS_LEN
@@ -10693,37 +10639,37 @@ ssl3_HandleCertificate(sslSocket *ss, SS
/* Called from ssl3_HandleCertificate
*/
SECStatus
ssl3_CompleteHandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
{
ssl3CertNode *c;
ssl3CertNode *lastCert = NULL;
- PRUint32 remaining = 0;
- PRUint32 size;
+ PRInt32 remaining = 0;
+ PRInt32 size;
SECStatus rv;
PRBool isServer = ss->sec.isServer;
PRBool isTLS;
SSL3AlertDescription desc;
int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
SECItem certItem;
ssl3_CleanupPeerCerts(ss);
isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
/* It is reported that some TLS client sends a Certificate message
** with a zero-length message body. We'll treat that case like a
** normal no_certificates message to maximize interoperability.
*/
if (length) {
- rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 3, &b, &length);
- if (rv != SECSuccess)
+ remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
+ if (remaining < 0)
goto loser; /* fatal alert already sent by ConsumeHandshake. */
- if (remaining > length)
+ if ((PRUint32)remaining > length)
goto decode_loser;
}
if (!remaining) {
if (!(isTLS && isServer)) {
desc = bad_certificate;
goto alert_loser;
}
@@ -10744,24 +10690,25 @@ ssl3_CompleteHandleCertificate(sslSocket
}
ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (ss->ssl3.peerCertArena == NULL) {
goto loser; /* don't send alerts on memory errors */
}
/* First get the peer cert. */
- if (remaining < 3)
+ remaining -= 3;
+ if (remaining < 0)
goto decode_loser;
- remaining -= 3;
- rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
- if (rv != SECSuccess)
+ size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
+ if (size <= 0)
goto loser; /* fatal alert already sent by ConsumeHandshake. */
- if (size == 0 || remaining < size)
+
+ if (remaining < size)
goto decode_loser;
certItem.data = b;
certItem.len = size;
b += size;
length -= size;
remaining -= size;
@@ -10771,24 +10718,25 @@ ssl3_CompleteHandleCertificate(sslSocket
/* We should report an alert if the cert was bad, but not if the
* problem was just some local problem, like memory error.
*/
goto ambiguous_err;
}
/* Now get all of the CA certs. */
while (remaining > 0) {
- if (remaining < 3)
+ remaining -= 3;
+ if (remaining < 0)
goto decode_loser;
- remaining -= 3;
- rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
- if (rv != SECSuccess)
+ size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
+ if (size <= 0)
goto loser; /* fatal alert already sent by ConsumeHandshake. */
- if (size == 0 || remaining < size)
+
+ if (remaining < size)
goto decode_loser;
certItem.data = b;
certItem.len = size;
b += size;
length -= size;
remaining -= size;
@@ -10807,16 +10755,19 @@ ssl3_CompleteHandleCertificate(sslSocket
if (lastCert) {
lastCert->next = c;
} else {
ss->ssl3.peerCertChain = c;
}
lastCert = c;
}
+ if (remaining != 0)
+ goto decode_loser;
+
SECKEY_UpdateCertPQG(ss->sec.peerCert);
if (!isServer &&
ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
ss->ssl3.hs.ws = wait_certificate_status;
rv = SECSuccess;
} else {
@@ -11094,20 +11045,23 @@ ssl3_ComputeTLSFinished(sslSocket *ss, s
TLSFinished *tlsFinished)
{
SECStatus rv;
CK_TLS_MAC_PARAMS tls_mac_params;
SECItem param = { siBuffer, NULL, 0 };
PK11Context *prf_context;
unsigned int retLen;
- PORT_Assert(spec->master_secret);
if (!spec->master_secret) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
+ const char *label = isServer ? "server finished" : "client finished";
+ unsigned int len = 15;
+ HASH_HashType hashType = ssl3_GetTls12HashType(ss);
+ return ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw,
+ hashes->len, tlsFinished->verify_data,
+ sizeof tlsFinished->verify_data, hashType);
}
if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) {
tls_mac_params.prfMechanism = CKM_TLS_PRF;
} else {
tls_mac_params.prfMechanism = ssl3_GetPrfHashMechanism(ss);
}
tls_mac_params.ulMacLength = 12;
@@ -11130,36 +11084,29 @@ ssl3_ComputeTLSFinished(sslSocket *ss, s
return rv;
}
/* The calling function must acquire and release the appropriate
* lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
* ss->ssl3.crSpec).
*/
SECStatus
-ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
- const char *label, unsigned int labelLen,
- const unsigned char *val, unsigned int valLen,
- unsigned char *out, unsigned int outLen)
+ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label,
+ unsigned int labelLen, const unsigned char *val, unsigned int valLen,
+ unsigned char *out, unsigned int outLen, HASH_HashType tls12HashType)
{
SECStatus rv = SECSuccess;
if (spec->master_secret) {
SECItem param = { siBuffer, NULL, 0 };
CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
PK11Context *prf_context;
unsigned int retLen;
if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
- /* Bug 1312976 non-SHA256 exporters are broken. */
- if (ssl3_GetPrfHashMechanism(ss) != CKM_SHA256) {
- PORT_Assert(0);
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
- }
mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
}
prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
spec->master_secret, ¶m);
if (!prf_context)
return SECFailure;
rv = PK11_DigestBegin(prf_context);
@@ -11347,17 +11294,17 @@ fail:
return rv;
}
/* wrap the master secret, and put it into the SID.
* Caller holds the Spec read lock.
*/
SECStatus
ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid,
- ssl3CipherSpec *spec)
+ ssl3CipherSpec *spec, SSLAuthType authType)
{
PK11SymKey *wrappingKey = NULL;
PK11SlotInfo *symKeySlot;
void *pwArg = ss->pkcs11PinArg;
SECStatus rv = SECFailure;
PRBool isServer = ss->sec.isServer;
CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
@@ -11401,17 +11348,18 @@ ssl3_CacheWrappedMasterSecret(sslSocket
PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
}
}
} else {
/* server socket using session cache. */
mechanism = PK11_GetBestWrapMechanism(symKeySlot);
if (mechanism != CKM_INVALID_MECHANISM) {
wrappingKey =
- ssl3_GetWrappingKey(ss, symKeySlot, mechanism, pwArg);
+ ssl3_GetWrappingKey(ss, symKeySlot, ss->sec.serverCert,
+ mechanism, pwArg);
if (wrappingKey) {
mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
}
}
}
sid->u.ssl3.masterWrapMech = mechanism;
PK11_FreeSlot(symKeySlot);
@@ -11608,17 +11556,19 @@ ssl3_FillInCachedSID(sslSocket *ss, sslS
sid->authType = ss->sec.authType;
sid->authKeyBits = ss->sec.authKeyBits;
sid->keaType = ss->sec.keaType;
sid->keaKeyBits = ss->sec.keaKeyBits;
sid->lastAccessTime = sid->creationTime = ssl_Time();
sid->expirationTime = sid->creationTime + ssl3_sid_timeout;
sid->localCert = CERT_DupCertificate(ss->sec.localCert);
if (ss->sec.isServer) {
- sid->namedCurve = ss->sec.serverCert->namedCurve;
+ memcpy(&sid->certType, &ss->sec.serverCert->certType, sizeof(sid->certType));
+ } else {
+ sid->certType.authType = ssl_auth_null;
}
if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
ss->xtnData.nextProto.data) {
if (SECITEM_CopyItem(
NULL, &sid->u.ssl3.alpnSelection, &ss->xtnData.nextProto) != SECSuccess) {
return SECFailure; /* error already set. */
}
@@ -11632,17 +11582,18 @@ ssl3_FillInCachedSID(sslSocket *ss, sslS
ss->ssl3.crSpec->msItem.len;
memcpy(sid->u.ssl3.keys.wrapped_master_secret,
ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len);
sid->u.ssl3.masterValid = PR_TRUE;
sid->u.ssl3.keys.msIsWrapped = PR_FALSE;
rv = SECSuccess;
} else {
rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid,
- ss->ssl3.crSpec);
+ ss->ssl3.crSpec,
+ ss->ssl3.hs.kea_def->authKeyType);
sid->u.ssl3.keys.msIsWrapped = PR_TRUE;
}
ssl_ReleaseSpecReadLock(ss); /*************************************/
return rv;
}
/* The return type is SECStatus instead of void because this function needs
--- a/security/nss/lib/ssl/ssl3ecc.c
+++ b/security/nss/lib/ssl/ssl3ecc.c
@@ -435,29 +435,33 @@ ssl_GetECGroupForServerSocket(sslSocket
unsigned int requiredECCbits;
PORT_Assert(cert);
if (!cert || !cert->serverKeyPair || !cert->serverKeyPair->pubKey) {
PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
return NULL;
}
- if (SSL_CERT_IS(cert, ssl_auth_rsa_sign) ||
- SSL_CERT_IS(cert, ssl_auth_rsa_pss)) {
+ if (cert->certType.authType == ssl_auth_rsa_sign) {
certKeySize = SECKEY_PublicKeyStrengthInBits(cert->serverKeyPair->pubKey);
- certKeySize = SSL_RSASTRENGTH_TO_ECSTRENGTH(certKeySize);
- } else if (SSL_CERT_IS_EC(cert)) {
+ certKeySize =
+ SSL_RSASTRENGTH_TO_ECSTRENGTH(certKeySize);
+ } else if (cert->certType.authType == ssl_auth_ecdsa ||
+ cert->certType.authType == ssl_auth_ecdh_rsa ||
+ cert->certType.authType == ssl_auth_ecdh_ecdsa) {
+ const sslNamedGroupDef *groupDef = cert->certType.namedCurve;
+
/* We won't select a certificate unless the named curve has been
* negotiated (or supported_curves was absent), double check that. */
- PORT_Assert(cert->namedCurve->keaType == ssl_kea_ecdh);
- PORT_Assert(ssl_NamedGroupEnabled(ss, cert->namedCurve));
- if (!ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
+ PORT_Assert(groupDef->keaType == ssl_kea_ecdh);
+ PORT_Assert(ssl_NamedGroupEnabled(ss, groupDef));
+ if (!ssl_NamedGroupEnabled(ss, groupDef)) {
return NULL;
}
- certKeySize = cert->namedCurve->bits;
+ certKeySize = groupDef->bits;
} else {
PORT_Assert(0);
return NULL;
}
bulkCipher = ssl_GetBulkCipherDef(ss->ssl3.hs.suite_def);
requiredECCbits = bulkCipher->key_size * BPB * 2;
PORT_Assert(requiredECCbits ||
ss->ssl3.hs.suite_def->bulk_cipher_alg == cipher_null);
--- a/security/nss/lib/ssl/ssl3ext.c
+++ b/security/nss/lib/ssl/ssl3ext.c
@@ -169,25 +169,25 @@ ssl3_ClientExtensionAdvertised(const ssl
SECStatus
ssl3_ParseExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length)
{
/* Clean out the extensions list. */
ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
while (*length) {
SECStatus rv;
- PRUint32 extension_type;
+ PRInt32 extension_type;
SECItem extension_data = { siBuffer, NULL, 0 };
TLSExtension *extension;
PRCList *cursor;
/* Get the extension's type field */
- rv = ssl3_ConsumeHandshakeNumber(ss, &extension_type, 2, b, length);
- if (rv != SECSuccess) {
- return SECFailure; /* alert already sent */
+ extension_type = ssl3_ConsumeHandshakeNumber(ss, 2, b, length);
+ if (extension_type < 0) { /* failure to decode extension_type */
+ return SECFailure; /* alert already sent */
}
SSL_TRC(10, ("%d: SSL3[%d]: parsing extension %d",
SSL_GETPID(), ss->fd, extension_type));
/* Check whether an extension has been sent multiple times. */
for (cursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions);
cursor != &ss->ssl3.hs.remoteExtensions;
cursor = PR_NEXT_LINK(cursor)) {
@@ -503,28 +503,28 @@ ssl3_ExtSendAlert(const sslSocket *ss, S
void
ssl3_ExtDecodeError(const sslSocket *ss)
{
(void)ssl3_DecodeError((sslSocket *)ss);
}
SECStatus
-ssl3_ExtConsumeHandshake(const sslSocket *ss, void *v, PRUint32 bytes,
+ssl3_ExtConsumeHandshake(const sslSocket *ss, void *v, PRInt32 bytes,
SSL3Opaque **b, PRUint32 *length)
{
return ssl3_ConsumeHandshake((sslSocket *)ss, v, bytes, b, length);
}
-SECStatus
-ssl3_ExtConsumeHandshakeNumber(const sslSocket *ss, PRUint32 *num,
- PRUint32 bytes, SSL3Opaque **b, PRUint32 *length)
+PRInt32
+ssl3_ExtConsumeHandshakeNumber(const sslSocket *ss, PRInt32 bytes,
+ SSL3Opaque **b, PRUint32 *length)
{
- return ssl3_ConsumeHandshakeNumber((sslSocket *)ss, num, bytes, b, length);
+ return ssl3_ConsumeHandshakeNumber((sslSocket *)ss, bytes, b, length);
}
SECStatus
ssl3_ExtConsumeHandshakeVariable(const sslSocket *ss, SECItem *i,
- PRUint32 bytes, SSL3Opaque **b,
+ PRInt32 bytes, SSL3Opaque **b,
PRUint32 *length)
{
return ssl3_ConsumeHandshakeVariable((sslSocket *)ss, i, bytes, b, length);
}
--- a/security/nss/lib/ssl/ssl3ext.h
+++ b/security/nss/lib/ssl/ssl3ext.h
@@ -140,18 +140,17 @@ SECStatus ssl3_ExtAppendHandshake(const
SECStatus ssl3_ExtAppendHandshakeNumber(const sslSocket *ss, PRInt32 num,
PRInt32 lenSize);
SECStatus ssl3_ExtAppendHandshakeVariable(const sslSocket *ss,
const SSL3Opaque *src, PRInt32 bytes,
PRInt32 lenSize);
void ssl3_ExtSendAlert(const sslSocket *ss, SSL3AlertLevel level,
SSL3AlertDescription desc);
void ssl3_ExtDecodeError(const sslSocket *ss);
-SECStatus ssl3_ExtConsumeHandshake(const sslSocket *ss, void *v, PRUint32 bytes,
+SECStatus ssl3_ExtConsumeHandshake(const sslSocket *ss, void *v, PRInt32 bytes,
SSL3Opaque **b, PRUint32 *length);
-SECStatus ssl3_ExtConsumeHandshakeNumber(const sslSocket *ss, PRUint32 *num,
- PRUint32 bytes, SSL3Opaque **b,
- PRUint32 *length);
+PRInt32 ssl3_ExtConsumeHandshakeNumber(const sslSocket *ss, PRInt32 bytes,
+ SSL3Opaque **b, PRUint32 *length);
SECStatus ssl3_ExtConsumeHandshakeVariable(const sslSocket *ss, SECItem *i,
- PRUint32 bytes, SSL3Opaque **b,
+ PRInt32 bytes, SSL3Opaque **b,
PRUint32 *length);
#endif
--- a/security/nss/lib/ssl/ssl3exthandle.c
+++ b/security/nss/lib/ssl/ssl3exthandle.c
@@ -11,23 +11,31 @@
#include "sslimpl.h"
#include "pk11pub.h"
#include "blapit.h"
#include "prinit.h"
#include "ssl3ext.h"
#include "ssl3exthandle.h"
#include "tls13exthandle.h" /* For tls13_ServerSendStatusRequestXtn. */
+static unsigned char key_name[SESS_TICKET_KEY_NAME_LEN];
+static PK11SymKey *session_ticket_enc_key = NULL;
+static PK11SymKey *session_ticket_mac_key = NULL;
+
+static PRCallOnceType generate_session_keys_once;
+
static SECStatus ssl3_ParseEncryptedSessionTicket(sslSocket *ss,
SECItem *data, EncryptedSessionTicket *enc_session_ticket);
static SECStatus ssl3_AppendToItem(SECItem *item, const unsigned char *buf,
PRUint32 bytes);
static SECStatus ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes);
static SECStatus ssl3_AppendNumberToItem(SECItem *item, PRUint32 num,
PRInt32 lenSize);
+static SECStatus ssl3_GetSessionTicketKeys(sslSocket *ss,
+ PK11SymKey **aes_key, PK11SymKey **mac_key);
static SECStatus ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes);
/*
* Write bytes. Using this function means the SECItem structure
* cannot be freed. The caller is expected to call this function
* on a shallow copy of the structure.
*/
static SECStatus
@@ -63,16 +71,93 @@ ssl3_AppendNumberToItem(SECItem *item, P
*p++ = (PRUint8)(num >> 8);
case 1:
*p = (PRUint8)num;
}
rv = ssl3_AppendToItem(item, &b[0], lenSize);
return rv;
}
+SECStatus
+ssl3_SessionTicketShutdown(void *appData, void *nssData)
+{
+ if (session_ticket_enc_key) {
+ PK11_FreeSymKey(session_ticket_enc_key);
+ session_ticket_enc_key = NULL;
+ }
+ if (session_ticket_mac_key) {
+ PK11_FreeSymKey(session_ticket_mac_key);
+ session_ticket_mac_key = NULL;
+ }
+ PORT_Memset(&generate_session_keys_once, 0,
+ sizeof(generate_session_keys_once));
+ return SECSuccess;
+}
+
+static PRStatus
+ssl3_GenerateSessionTicketKeys(void *data)
+{
+ SECStatus rv;
+ sslSocket *ss = (sslSocket *)data;
+ sslServerCertType certType = { ssl_auth_rsa_decrypt, NULL };
+ const sslServerCert *sc;
+ SECKEYPrivateKey *svrPrivKey;
+ SECKEYPublicKey *svrPubKey;
+
+ sc = ssl_FindServerCert(ss, &certType);
+ if (!sc || !sc->serverKeyPair) {
+ SSL_DBG(("%d: SSL[%d]: No ssl_auth_rsa_decrypt cert and key pair",
+ SSL_GETPID(), ss->fd));
+ goto loser;
+ }
+ svrPrivKey = sc->serverKeyPair->privKey;
+ svrPubKey = sc->serverKeyPair->pubKey;
+ if (svrPrivKey == NULL || svrPubKey == NULL) {
+ SSL_DBG(("%d: SSL[%d]: Pub or priv key(s) is NULL.",
+ SSL_GETPID(), ss->fd));
+ goto loser;
+ }
+
+ /* Get a copy of the session keys from shared memory. */
+ PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX,
+ sizeof(SESS_TICKET_KEY_NAME_PREFIX));
+ if (!ssl_GetSessionTicketKeys(svrPrivKey, svrPubKey, ss->pkcs11PinArg,
+ &key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN],
+ &session_ticket_enc_key, &session_ticket_mac_key))
+ return PR_FAILURE;
+
+ rv = NSS_RegisterShutdown(ssl3_SessionTicketShutdown, NULL);
+ if (rv != SECSuccess)
+ goto loser;
+
+ return PR_SUCCESS;
+
+loser:
+ ssl3_SessionTicketShutdown(NULL, NULL);
+ return PR_FAILURE;
+}
+
+static SECStatus
+ssl3_GetSessionTicketKeys(sslSocket *ss, PK11SymKey **aes_key,
+ PK11SymKey **mac_key)
+{
+ if (PR_CallOnceWithArg(&generate_session_keys_once,
+ ssl3_GenerateSessionTicketKeys, ss) !=
+ PR_SUCCESS)
+ return SECFailure;
+
+ if (session_ticket_enc_key == NULL ||
+ session_ticket_mac_key == NULL)
+ return SECFailure;
+
+ *aes_key = session_ticket_enc_key;
+ *mac_key = session_ticket_mac_key;
+ return SECSuccess;
+}
+
/* Format an SNI extension, using the name from the socket's URL,
* unless that name is a dotted decimal string.
* Used by client and server.
*/
PRInt32
ssl3_SendServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append,
PRUint32 maxBytes)
{
@@ -133,46 +218,46 @@ ssl3_SendServerNameXtn(const sslSocket *
return 4;
}
/* Handle an incoming SNI extension. */
SECStatus
ssl3_HandleServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, SECItem *data)
{
SECItem *names = NULL;
- PRUint32 listLenBytes = 0;
- SECStatus rv;
+ PRInt32 listLenBytes = 0;
if (!ss->sec.isServer) {
return SECSuccess; /* ignore extension */
}
/* Server side - consume client data and register server sender. */
/* do not parse the data if don't have user extension handling function. */
if (!ss->sniSocketConfig) {
return SECSuccess;
}
/* length of server_name_list */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &listLenBytes, 2, &data->data, &data->len);
- if (rv != SECSuccess) {
+ listLenBytes = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
+ if (listLenBytes < 0) {
goto loser; /* alert already sent */
}
if (listLenBytes == 0 || listLenBytes != data->len) {
goto alert_loser;
}
/* Read ServerNameList. */
while (data->len > 0) {
SECItem tmp;
- PRUint32 type;
+ SECStatus rv;
+ PRInt32 type;
/* Read Name Type. */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &type, 1, &data->data, &data->len);
- if (rv != SECSuccess) {
+ type = ssl3_ExtConsumeHandshakeNumber(ss, 1, &data->data, &data->len);
+ if (type < 0) { /* i.e., SECFailure cast to PRint32 */
/* alert sent in ConsumeHandshakeNumber */
goto loser;
}
/* Read ServerName (length and value). */
rv = ssl3_ExtConsumeHandshakeVariable(ss, &tmp, 2, &data->data, &data->len);
if (rv != SECSuccess) {
goto loser;
@@ -282,17 +367,21 @@ ssl3_SendSessionTicketXtn(
* will only be holding the lock when we are the client and when we're
* attempting to resume an existing session.
*/
session_ticket = &sid->u.ssl3.locked.sessionTicket;
if (session_ticket->ticket.data) {
if (xtnData->ticketTimestampVerified) {
extension_length += session_ticket->ticket.len;
- } else if (!append && ssl_TicketTimeValid(session_ticket)) {
+ } else if (!append &&
+ (session_ticket->ticket_lifetime_hint == 0 ||
+ (session_ticket->ticket_lifetime_hint +
+ session_ticket->received_timestamp >
+ ssl_Time()))) {
extension_length += session_ticket->ticket.len;
xtnData->ticketTimestampVerified = PR_TRUE;
}
}
}
if (maxBytes < (PRUint32)extension_length) {
PORT_Assert(0);
@@ -448,32 +537,32 @@ ssl3_SelectAppProtocol(const sslSocket *
xtnData->negotiated[xtnData->numNegotiated++] = ex_type;
return SECITEM_CopyItem(NULL, &xtnData->nextProto, &result);
}
/* handle an incoming ALPN extension at the server */
SECStatus
ssl3_ServerHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, SECItem *data)
{
- PRUint32 count;
+ int count;
SECStatus rv;
/* We expressly don't want to allow ALPN on renegotiation,
* despite it being permitted by the spec. */
if (ss->firstHsDone || data->len == 0) {
/* Clients MUST send a non-empty ALPN extension. */
ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
return SECFailure;
}
/* Unlike NPN, ALPN has extra redundant length information so that
* the extension is the same in both ClientHello and ServerHello. */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &count, 2, &data->data, &data->len);
- if (rv != SECSuccess || count != data->len) {
+ count = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
+ if (count != data->len) {
ssl3_ExtDecodeError(ss);
return SECFailure;
}
if (!ss->nextProtoCallback) {
/* we're not configured for it */
return SECSuccess;
}
@@ -527,17 +616,17 @@ ssl3_ClientHandleNextProtoNegoXtn(const
return ssl3_SelectAppProtocol(ss, xtnData, ex_type, data);
}
SECStatus
ssl3_ClientHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, SECItem *data)
{
SECStatus rv;
- PRUint32 list_len;
+ PRInt32 list_len;
SECItem protocol_name;
if (ssl3_ExtensionNegotiated(ss, ssl_next_proto_nego_xtn)) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
/* The extension data from the server has the following format:
@@ -545,20 +634,19 @@ ssl3_ClientHandleAppProtoXtn(const sslSo
* uint8 len; // where len >= 1
* uint8 protocol_name[len]; */
if (data->len < 4 || data->len > 2 + 1 + 255) {
ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
return SECFailure;
}
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &list_len, 2, &data->data,
- &data->len);
+ list_len = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
/* The list has to be the entire extension. */
- if (rv != SECSuccess || list_len != data->len) {
+ if (list_len != data->len) {
ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
return SECFailure;
}
rv = ssl3_ExtConsumeHandshakeVariable(ss, &protocol_name, 1,
&data->data, &data->len);
/* The list must have exactly one value. */
@@ -870,32 +958,32 @@ ssl3_EncodeSessionTicket(sslSocket *ss,
PRBool ms_is_wrapped;
unsigned char wrapped_ms[SSL3_MASTER_SECRET_LENGTH];
SECItem ms_item = { 0, NULL, 0 };
PRUint32 padding_length;
PRUint32 ticket_length;
PRUint32 cert_length = 0;
PRUint8 length_buf[4];
PRUint32 now;
- unsigned char key_name[SESS_TICKET_KEY_NAME_LEN];
PK11SymKey *aes_key = NULL;
PK11SymKey *mac_key = NULL;
CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC;
PK11Context *aes_ctx;
CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC;
PK11Context *hmac_ctx = NULL;
unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
unsigned int computed_mac_length;
unsigned char iv[AES_BLOCK_SIZE];
SECItem ivItem;
SECItem *srvName = NULL;
PRUint32 srvNameLen = 0;
CK_MECHANISM_TYPE msWrapMech = 0; /* dummy default value,
* must be >= 0 */
ssl3CipherSpec *spec;
+ const sslServerCertType *certType;
SECItem alpnSelection = { siBuffer, NULL, 0 };
SSL_TRC(3, ("%d: SSL3[%d]: send session_ticket handshake",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
@@ -905,17 +993,17 @@ ssl3_EncodeSessionTicket(sslSocket *ss,
/* Get IV and encryption keys */
ivItem.data = iv;
ivItem.len = sizeof(iv);
rv = PK11_GenerateRandom(iv, sizeof(iv));
if (rv != SECSuccess)
goto loser;
- rv = ssl_GetSessionTicketKeys(ss, key_name, &aes_key, &mac_key);
+ rv = ssl3_GetSessionTicketKeys(ss, &aes_key, &mac_key);
if (rv != SECSuccess)
goto loser;
if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
spec = ss->ssl3.cwSpec;
} else {
spec = ss->ssl3.pwSpec;
}
@@ -924,17 +1012,18 @@ ssl3_EncodeSessionTicket(sslSocket *ss,
ms_item.data = spec->msItem.data;
ms_item.len = spec->msItem.len;
ms_is_wrapped = PR_FALSE;
} else {
/* Extract the master secret wrapped. */
sslSessionID sid;
PORT_Memset(&sid, 0, sizeof(sslSessionID));
- rv = ssl3_CacheWrappedMasterSecret(ss, &sid, spec);
+ rv = ssl3_CacheWrappedMasterSecret(ss, &sid, spec,
+ ss->ssl3.hs.kea_def->authKeyType);
if (rv == SECSuccess) {
if (sid.u.ssl3.keys.wrapped_master_secret_len > sizeof(wrapped_ms))
goto loser;
memcpy(wrapped_ms, sid.u.ssl3.keys.wrapped_master_secret,
sid.u.ssl3.keys.wrapped_master_secret_len);
ms_item.data = wrapped_ms;
ms_item.len = sid.u.ssl3.keys.wrapped_master_secret_len;
msWrapMech = sid.u.ssl3.masterWrapMech;
@@ -1017,25 +1106,32 @@ ssl3_EncodeSessionTicket(sslSocket *ss,
rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaType, 1);
if (rv != SECSuccess)
goto loser;
rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaKeyBits, 4);
if (rv != SECSuccess)
goto loser;
/* certificate type */
- PORT_Assert(SSL_CERT_IS(ss->sec.serverCert, ss->sec.authType));
- if (SSL_CERT_IS_EC(ss->sec.serverCert)) {
- const sslServerCert *cert = ss->sec.serverCert;
- PORT_Assert(cert->namedCurve);
- /* EC curves only use the second of the two bytes. */
- PORT_Assert(cert->namedCurve->name < 256);
- rv = ssl3_AppendNumberToItem(&plaintext, cert->namedCurve->name, 1);
- } else {
- rv = ssl3_AppendNumberToItem(&plaintext, 0, 1);
+ certType = &ss->sec.serverCert->certType;
+ PORT_Assert(certType->authType == ss->sec.authType);
+ switch (ss->sec.authType) {
+ case ssl_auth_ecdsa:
+ case ssl_auth_ecdh_rsa:
+ case ssl_auth_ecdh_ecdsa:
+ PORT_Assert(certType->namedCurve);
+ PORT_Assert(certType->namedCurve->keaType == ssl_kea_ecdh);
+ /* EC curves only use the second of the two bytes. */
+ PORT_Assert(certType->namedCurve->name < 256);
+ rv = ssl3_AppendNumberToItem(&plaintext,
+ certType->namedCurve->name, 1);
+ break;
+ default:
+ rv = ssl3_AppendNumberToItem(&plaintext, 0, 1);
+ break;
}
if (rv != SECSuccess)
goto loser;
/* master_secret */
rv = ssl3_AppendNumberToItem(&plaintext, ms_is_wrapped, 1);
if (rv != SECSuccess)
goto loser;
@@ -1252,30 +1348,29 @@ ssl3_ProcessSessionTicketCommon(sslSocke
SessionTicket *parsed_session_ticket = NULL;
sslSessionID *sid = NULL;
SSL3Statistics *ssl3stats;
PRUint32 i;
SECItem extension_data;
EncryptedSessionTicket enc_session_ticket;
unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
unsigned int computed_mac_length;
- unsigned char key_name[SESS_TICKET_KEY_NAME_LEN];
PK11SymKey *aes_key = NULL;
PK11SymKey *mac_key = NULL;
PK11Context *hmac_ctx;
CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC;
PK11Context *aes_ctx;
CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC;
unsigned char *padding;
PRUint32 padding_length;
unsigned char *buffer;
unsigned int buffer_len;
- PRUint32 temp;
+ PRInt32 temp;
SECItem cert_item;
- PRUint32 nameType;
+ PRInt8 nameType = TLS_STE_NO_SERVER_NAME;
SECItem macParam = { siBuffer, NULL, 0 };
SECItem alpn_item;
SECItem ivItem;
/* Turn off stateless session resumption if the client sends a
* SessionTicket extension, even if the extension turns out to be
* malformed (ss->sec.ci.sid is non-NULL when doing session
* renegotiation.)
@@ -1290,17 +1385,17 @@ ssl3_ProcessSessionTicketCommon(sslSocke
extension_data.len = data->len;
if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket) !=
SECSuccess) {
return SECSuccess; /* Pretend it isn't there */
}
/* Get session ticket keys. */
- rv = ssl_GetSessionTicketKeys(ss, key_name, &aes_key, &mac_key);
+ rv = ssl3_GetSessionTicketKeys(ss, &aes_key, &mac_key);
if (rv != SECSuccess) {
SSL_DBG(("%d: SSL[%d]: Unable to get/generate session ticket keys.",
SSL_GETPID(), ss->fd));
goto loser;
}
/* If the ticket sent by the client was generated under a key different
* from the one we have, bypass ticket processing.
@@ -1399,104 +1494,109 @@ ssl3_ProcessSessionTicketCommon(sslSocke
parsed_session_ticket = PORT_ZAlloc(sizeof(SessionTicket));
if (parsed_session_ticket == NULL) {
rv = SECFailure;
goto loser;
}
/* Read ticket_version and reject if the version is wrong */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &buffer_len);
- if (rv != SECSuccess || temp != TLS_EX_SESS_TICKET_VERSION)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
+ if (temp != TLS_EX_SESS_TICKET_VERSION)
goto no_ticket;
parsed_session_ticket->ticket_version = (SSL3ProtocolVersion)temp;
/* Read SSLVersion. */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
parsed_session_ticket->ssl_version = (SSL3ProtocolVersion)temp;
/* Read cipher_suite. */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
parsed_session_ticket->cipher_suite = (ssl3CipherSuite)temp;
/* Read compression_method. */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
parsed_session_ticket->compression_method = (SSLCompressionMethod)temp;
/* Read cipher spec parameters. */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
parsed_session_ticket->authType = (SSLAuthType)temp;
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
- parsed_session_ticket->authKeyBits = temp;
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ parsed_session_ticket->authKeyBits = (PRUint32)temp;
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
parsed_session_ticket->keaType = (SSLKEAType)temp;
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
- parsed_session_ticket->keaKeyBits = temp;
+ parsed_session_ticket->keaKeyBits = (PRUint32)temp;
- /* Read the optional named curve. */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ /* Read certificate slot */
+ parsed_session_ticket->certType.authType = parsed_session_ticket->authType;
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
- if (parsed_session_ticket->authType == ssl_auth_ecdsa ||
- parsed_session_ticket->authType == ssl_auth_ecdh_rsa ||
- parsed_session_ticket->authType == ssl_auth_ecdh_ecdsa) {
- const sslNamedGroupDef *group =
- ssl_LookupNamedGroup((SSLNamedGroup)temp);
- if (!group || group->keaType != ssl_kea_ecdh) {
- goto no_ticket;
- }
- parsed_session_ticket->namedCurve = group;
+ switch (parsed_session_ticket->authType) {
+ case ssl_auth_ecdsa:
+ case ssl_auth_ecdh_rsa:
+ case ssl_auth_ecdh_ecdsa: {
+ const sslNamedGroupDef *group =
+ ssl_LookupNamedGroup((SSLNamedGroup)temp);
+ if (!group || group->keaType != ssl_kea_ecdh) {
+ goto no_ticket;
+ }
+ parsed_session_ticket->certType.namedCurve = group;
+ } break;
+ default:
+ break;
}
/* Read wrapped master_secret. */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
parsed_session_ticket->ms_is_wrapped = (PRBool)temp;
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
parsed_session_ticket->msWrapMech = (CK_MECHANISM_TYPE)temp;
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
parsed_session_ticket->ms_length = (PRUint16)temp;
if (parsed_session_ticket->ms_length == 0 || /* sanity check MS. */
parsed_session_ticket->ms_length >
sizeof(parsed_session_ticket->master_secret))
goto no_ticket;
/* Allow for the wrapped master secret to be longer. */
if (buffer_len < parsed_session_ticket->ms_length)
goto no_ticket;
PORT_Memcpy(parsed_session_ticket->master_secret, buffer,
parsed_session_ticket->ms_length);
buffer += parsed_session_ticket->ms_length;
buffer_len -= parsed_session_ticket->ms_length;
/* Read client_identity */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
parsed_session_ticket->client_identity.client_auth_type =
(ClientAuthenticationType)temp;
switch (parsed_session_ticket->client_identity.client_auth_type) {
case CLIENT_AUTH_ANONYMOUS:
break;
case CLIENT_AUTH_CERTIFICATE:
rv = ssl3_ExtConsumeHandshakeVariable(ss, &cert_item, 3,
@@ -1507,41 +1607,40 @@ ssl3_ProcessSessionTicketCommon(sslSocke
&cert_item);
if (rv != SECSuccess)
goto no_ticket;
break;
default:
goto no_ticket;
}
/* Read timestamp. */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
- parsed_session_ticket->timestamp = temp;
+ parsed_session_ticket->timestamp = (PRUint32)temp;
/* Read server name */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &nameType, 1, &buffer, &buffer_len);
- if (rv != SECSuccess)
- goto no_ticket;
- if ((PRInt8)nameType != TLS_STE_NO_SERVER_NAME) {
+ nameType =
+ ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
+ if (nameType != TLS_STE_NO_SERVER_NAME) {
SECItem name_item;
rv = ssl3_ExtConsumeHandshakeVariable(ss, &name_item, 2, &buffer,
&buffer_len);
if (rv != SECSuccess)
goto no_ticket;
rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->srvName,
&name_item);
if (rv != SECSuccess)
goto no_ticket;
- parsed_session_ticket->srvName.type = (PRUint8)nameType;
+ parsed_session_ticket->srvName.type = nameType;
}
/* Read extendedMasterSecretUsed */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &buffer_len);
- if (rv != SECSuccess)
+ temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
+ if (temp < 0)
goto no_ticket;
PORT_Assert(temp == PR_TRUE || temp == PR_FALSE);
parsed_session_ticket->extendedMasterSecretUsed = (PRBool)temp;
rv = ssl3_ExtConsumeHandshake(ss, &parsed_session_ticket->flags, 4,
&buffer, &buffer_len);
if (rv != SECSuccess)
goto no_ticket;
@@ -1580,17 +1679,18 @@ ssl3_ProcessSessionTicketCommon(sslSocke
/* Copy over parameters. */
sid->version = parsed_session_ticket->ssl_version;
sid->u.ssl3.cipherSuite = parsed_session_ticket->cipher_suite;
sid->u.ssl3.compression = parsed_session_ticket->compression_method;
sid->authType = parsed_session_ticket->authType;
sid->authKeyBits = parsed_session_ticket->authKeyBits;
sid->keaType = parsed_session_ticket->keaType;
sid->keaKeyBits = parsed_session_ticket->keaKeyBits;
- sid->namedCurve = parsed_session_ticket->namedCurve;
+ memcpy(&sid->certType, &parsed_session_ticket->certType,
+ sizeof(sslServerCertType));
if (SECITEM_CopyItem(NULL, &sid->u.ssl3.locked.sessionTicket.ticket,
&extension_data) != SECSuccess)
goto no_ticket;
sid->u.ssl3.locked.sessionTicket.flags = parsed_session_ticket->flags;
if (parsed_session_ticket->ms_length >
sizeof(sid->u.ssl3.keys.wrapped_master_secret))
@@ -2040,18 +2140,17 @@ ssl3_ServerHandleSigAlgsXtn(const sslSoc
if (xtnData->clientSigSchemes) {
PORT_Free(xtnData->clientSigSchemes);
xtnData->clientSigSchemes = NULL;
}
rv = ssl_ParseSignatureSchemes(ss, NULL,
&xtnData->clientSigSchemes,
&xtnData->numClientSigScheme,
&data->data, &data->len);
- if (rv != SECSuccess || xtnData->numClientSigScheme == 0) {
- ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ if (rv != SECSuccess) {
PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
return SECFailure;
}
/* Check for trailing data. */
if (data->len != 0) {
ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
return SECFailure;
@@ -2380,47 +2479,45 @@ ssl3_HandleSupportedPointFormatsXtn(cons
/* Poor client doesn't support uncompressed points. */
PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
return SECFailure;
}
static SECStatus
ssl_UpdateSupportedGroups(sslSocket *ss, SECItem *data)
{
- SECStatus rv;
- PRUint32 list_len;
+ PRInt32 list_len;
unsigned int i;
const sslNamedGroupDef *enabled[SSL_NAMED_GROUP_COUNT] = { 0 };
PORT_Assert(SSL_NAMED_GROUP_COUNT == PR_ARRAY_SIZE(enabled));
if (!data->data || data->len < 4) {
(void)ssl3_DecodeError(ss);
return SECFailure;
}
/* get the length of elliptic_curve_list */
- rv = ssl3_ConsumeHandshakeNumber(ss, &list_len, 2, &data->data, &data->len);
- if (rv != SECSuccess || data->len != list_len || (data->len % 2) != 0) {
+ list_len = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
+ if (list_len < 0 || data->len != list_len || (data->len % 2) != 0) {
(void)ssl3_DecodeError(ss);
return SECFailure;
}
/* disable all groups and remember the enabled groups */
for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
enabled[i] = ss->namedGroupPreferences[i];
ss->namedGroupPreferences[i] = NULL;
}
/* Read groups from data and enable if in |enabled| */
while (data->len) {
const sslNamedGroupDef *group;
- PRUint32 curve_name;
- rv = ssl3_ConsumeHandshakeNumber(ss, &curve_name, 2, &data->data,
- &data->len);
- if (rv != SECSuccess) {
+ PRInt32 curve_name =
+ ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
+ if (curve_name < 0) {
return SECFailure; /* fatal alert already sent */
}
group = ssl_LookupNamedGroup(curve_name);
if (group) {
for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
if (enabled[i] && group == enabled[i]) {
ss->namedGroupPreferences[i] = enabled[i];
break;
--- a/security/nss/lib/ssl/ssl3gthr.c
+++ b/security/nss/lib/ssl/ssl3gthr.c
@@ -27,17 +27,16 @@ ssl3_InitGather(sslGather *gs)
{
SECStatus status;
gs->state = GS_INIT;
gs->writeOffset = 0;
gs->readOffset = 0;
gs->dtlsPacketOffset = 0;
gs->dtlsPacket.len = 0;
- gs->rejectV2Records = PR_FALSE;
status = sslBuffer_Grow(&gs->buf, 4096);
return status;
}
/* Caller must hold RecvBufLock. */
void
ssl3_DestroyGather(sslGather *gs)
{
@@ -143,21 +142,18 @@ ssl3_GatherData(sslSocket *ss, sslGather
if (gs->remainder > 0) {
continue;
}
/* have received entire record header, or entire record. */
switch (gs->state) {
case GS_HEADER:
/* Check for SSLv2 handshakes. Always assume SSLv3 on clients,
- * support SSLv2 handshakes only when ssl2gs != NULL.
- * Always assume v3 after we received the first record. */
- if (!ssl2gs ||
- ss->gs.rejectV2Records ||
- ssl3_isLikelyV3Hello(gs->hdr)) {
+ * support SSLv2 handshakes only when ssl2gs != NULL. */
+ if (!ssl2gs || ssl3_isLikelyV3Hello(gs->hdr)) {
/* Should have a non-SSLv2 record header in gs->hdr. Extract
* the length of the following encrypted data, and then
* read in the rest of the record into gs->inbuf. */
if (ss->ssl3.hs.shortHeaders) {
PRUint16 len = (gs->hdr[0] << 8) | gs->hdr[1];
if (!(len & 0x8000)) {
SSL_DBG(("%d: SSL3[%d]: incorrectly formatted header"));
SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
@@ -182,17 +178,17 @@ ssl3_GatherData(sslSocket *ss, sslGather
ssl2gs->padding = gs->hdr[2];
v2HdrLength++;
}
}
/* This is the max length for an encrypted SSLv3+ fragment. */
if (!v2HdrLength &&
gs->remainder > (MAX_FRAGMENT_LENGTH + 2048)) {
- SSL3_SendAlert(ss, alert_fatal, record_overflow);
+ SSL3_SendAlert(ss, alert_fatal, unexpected_message);
gs->state = GS_INIT;
PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
return SECFailure;
}
gs->state = GS_DATA;
gs->offset = 0;
gs->inbuf.len = 0;
@@ -204,49 +200,30 @@ ssl3_GatherData(sslSocket *ss, sslGather
}
lbp = gs->inbuf.buf;
}
/* When we encounter an SSLv2 hello we've read 2 or 3 bytes too
* many into the gs->hdr[] buffer. Copy them over into inbuf so
* that we can properly process the hello record later. */
if (v2HdrLength) {
- /* Reject v2 records that don't even carry enough data to
- * resemble a valid ClientHello header. */
- if (gs->remainder < SSL_HL_CLIENT_HELLO_HBYTES) {
- SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
- PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
- return SECFailure;
- }
-
- PORT_Assert(lbp);
gs->inbuf.len = 5 - v2HdrLength;
PORT_Memcpy(lbp, gs->hdr + v2HdrLength, gs->inbuf.len);
gs->remainder -= gs->inbuf.len;
lbp += gs->inbuf.len;
}
- if (gs->remainder > 0) {
- break; /* End this case. Continue around the loop. */
- }
-
- /* FALL THROUGH if (gs->remainder == 0) as we just received
- * an empty record and there's really no point in calling
- * ssl_DefRecv() with buf=NULL and len=0. */
+ break; /* End this case. Continue around the loop. */
case GS_DATA:
/*
** SSL3 record has been completely received.
*/
SSL_TRC(10, ("%d: SSL[%d]: got record of %d bytes",
SSL_GETPID(), ss->fd, gs->inbuf.len));
-
- /* reject any v2 records from now on */
- ss->gs.rejectV2Records = PR_TRUE;
-
gs->state = GS_INIT;
return 1;
}
}
return rv;
}
--- a/security/nss/lib/ssl/ssl3prot.h
+++ b/security/nss/lib/ssl/ssl3prot.h
@@ -282,17 +282,17 @@ typedef struct {
/*
* TLS extension related data structures and constants.
*/
/* SessionTicket extension related data structures. */
/* NewSessionTicket handshake message. */
typedef struct {
- PRTime received_timestamp;
+ PRUint32 received_timestamp;
PRUint32 ticket_lifetime_hint;
PRUint32 flags;
PRUint32 ticket_age_add;
PRUint32 max_early_data_size;
SECItem ticket;
} NewSessionTicket;
typedef enum {
--- a/security/nss/lib/ssl/sslcert.c
+++ b/security/nss/lib/ssl/sslcert.c
@@ -8,121 +8,69 @@
#include "ssl.h"
#include "sslimpl.h"
#include "secoid.h" /* for SECOID_GetAlgorithmTag */
#include "pk11func.h" /* for PK11_ReferenceSlot */
#include "nss.h" /* for NSS_RegisterShutdown */
#include "prinit.h" /* for PR_CallOnceWithArg */
-/* This global item is used only in servers. It is is initialized by
- * SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
- */
-static struct {
- PRCallOnceType setup;
- CERTDistNames *names;
-} ssl_server_ca_list;
+static const PRCallOnceType pristineCallOnce;
+static PRCallOnceType setupServerCAListOnce;
static SECStatus
-ssl_ServerCAListShutdown(void *appData, void *nssData)
+serverCAListShutdown(void *appData, void *nssData)
{
- PORT_Assert(ssl_server_ca_list.names);
- if (ssl_server_ca_list.names) {
- CERT_FreeDistNames(ssl_server_ca_list.names);
+ PORT_Assert(ssl3_server_ca_list);
+ if (ssl3_server_ca_list) {
+ CERT_FreeDistNames(ssl3_server_ca_list);
+ ssl3_server_ca_list = NULL;
}
- PORT_Memset(&ssl_server_ca_list, 0, sizeof(ssl_server_ca_list));
+ setupServerCAListOnce = pristineCallOnce;
return SECSuccess;
}
static PRStatus
-ssl_SetupCAListOnce(void *arg)
+serverCAListSetup(void *arg)
{
CERTCertDBHandle *dbHandle = (CERTCertDBHandle *)arg;
- SECStatus rv = NSS_RegisterShutdown(ssl_ServerCAListShutdown, NULL);
+ SECStatus rv = NSS_RegisterShutdown(serverCAListShutdown, NULL);
PORT_Assert(SECSuccess == rv);
if (SECSuccess == rv) {
- ssl_server_ca_list.names = CERT_GetSSLCACerts(dbHandle);
+ ssl3_server_ca_list = CERT_GetSSLCACerts(dbHandle);
return PR_SUCCESS;
}
return PR_FAILURE;
}
-SECStatus
-ssl_SetupCAList(sslSocket *ss)
-{
- if (PR_SUCCESS != PR_CallOnceWithArg(&ssl_server_ca_list.setup,
- &ssl_SetupCAListOnce,
- (void *)(ss->dbHandle))) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
- }
- return SECSuccess;
-}
-
-SECStatus
-ssl_GetCertificateRequestCAs(sslSocket *ss, unsigned int *calen,
- SECItem **names, unsigned int *nnames)
-{
- SECItem *name;
- CERTDistNames *ca_list;
- unsigned int i;
-
- *calen = 0;
- *names = NULL;
- *nnames = 0;
-
- /* ssl3.ca_list is initialized to NULL, and never changed. */
- ca_list = ss->ssl3.ca_list;
- if (!ca_list) {
- if (ssl_SetupCAList(ss) != SECSuccess) {
- return SECFailure;
- }
- ca_list = ssl_server_ca_list.names;
- }
-
- if (ca_list != NULL) {
- *names = ca_list->names;
- *nnames = ca_list->nnames;
- }
-
- for (i = 0, name = *names; i < *nnames; i++, name++) {
- *calen += 2 + name->len;
- }
- return SECSuccess;
-}
-
sslServerCert *
-ssl_NewServerCert()
+ssl_NewServerCert(const sslServerCertType *certType)
{
sslServerCert *sc = PORT_ZNew(sslServerCert);
if (!sc) {
return NULL;
}
- sc->authTypes = 0;
- sc->namedCurve = NULL;
+ memcpy(&sc->certType, certType, sizeof(sc->certType));
sc->serverCert = NULL;
sc->serverCertChain = NULL;
sc->certStatusArray = NULL;
sc->signedCertTimestamps.len = 0;
return sc;
}
sslServerCert *
ssl_CopyServerCert(const sslServerCert *oc)
{
sslServerCert *sc;
- sc = ssl_NewServerCert();
+ sc = ssl_NewServerCert(&oc->certType);
if (!sc) {
return NULL;
}
- sc->authTypes = oc->authTypes;
- sc->namedCurve = oc->namedCurve;
-
if (oc->serverCert && oc->serverCertChain) {
sc->serverCert = CERT_DupCertificate(oc->serverCert);
if (!sc->serverCert)
goto loser;
sc->serverCertChain = CERT_DupCertList(oc->serverCertChain);
if (!sc->serverCertChain)
goto loser;
} else {
@@ -176,41 +124,88 @@ ssl_FreeServerCert(sslServerCert *sc)
SECITEM_FreeArray(sc->certStatusArray, PR_TRUE);
}
if (sc->signedCertTimestamps.len) {
SECITEM_FreeItem(&sc->signedCertTimestamps, PR_FALSE);
}
PORT_ZFree(sc, sizeof(*sc));
}
-const sslServerCert *
-ssl_FindServerCert(const sslSocket *ss, SSLAuthType authType,
- const sslNamedGroupDef *namedCurve)
+sslServerCert *
+ssl_FindServerCert(const sslSocket *ss,
+ const sslServerCertType *certType)
{
PRCList *cursor;
for (cursor = PR_NEXT_LINK(&ss->serverCerts);
cursor != &ss->serverCerts;
cursor = PR_NEXT_LINK(cursor)) {
sslServerCert *cert = (sslServerCert *)cursor;
- if (!SSL_CERT_IS(cert, authType)) {
+ if (cert->certType.authType != certType->authType) {
continue;
}
- if (SSL_CERT_IS_EC(cert)) {
- /* Note: For deprecated APIs, we need to be able to find and
- match a slot with any named curve. */
- if (namedCurve && cert->namedCurve != namedCurve) {
- continue;
- }
+ switch (cert->certType.authType) {
+ case ssl_auth_ecdsa:
+ case ssl_auth_ecdh_rsa:
+ case ssl_auth_ecdh_ecdsa:
+ /* Note: For deprecated APIs, we need to be able to find and
+ match a slot with any named curve. */
+ if (certType->namedCurve &&
+ cert->certType.namedCurve != certType->namedCurve) {
+ continue;
+ }
+ break;
+ default:
+ break;
}
return cert;
}
return NULL;
}
+sslServerCert *
+ssl_FindServerCertByAuthType(const sslSocket *ss, SSLAuthType authType)
+{
+ sslServerCertType certType;
+ certType.authType = authType;
+ /* Setting the named curve to NULL ensures that all EC certificates
+ * are matched when searching for this slot. */
+ certType.namedCurve = NULL;
+ return ssl_FindServerCert(ss, &certType);
+}
+
+SECStatus
+ssl_OneTimeCertSetup(sslSocket *ss, const sslServerCert *sc)
+{
+ if (PR_SUCCESS != PR_CallOnceWithArg(&setupServerCAListOnce,
+ &serverCAListSetup,
+ (void *)(ss->dbHandle))) {
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+/* Determine which slot a certificate fits into. SSLAuthType is known, but
+ * extra information needs to be worked out from the cert and key. */
+static void
+ssl_PopulateCertType(sslServerCertType *certType, SSLAuthType authType,
+ CERTCertificate *cert, sslKeyPair *keyPair)
+{
+ certType->authType = authType;
+ switch (authType) {
+ case ssl_auth_ecdsa:
+ case ssl_auth_ecdh_rsa:
+ case ssl_auth_ecdh_ecdsa:
+ certType->namedCurve = ssl_ECPubKey2NamedGroup(keyPair->pubKey);
+ break;
+ default:
+ break;
+ }
+}
+
static SECStatus
ssl_PopulateServerCert(sslServerCert *sc, CERTCertificate *cert,
const CERTCertificateList *certChain)
{
if (sc->serverCert) {
CERT_DestroyCertificate(sc->serverCert);
}
if (sc->serverCertChain) {
@@ -232,53 +227,31 @@ ssl_PopulateServerCert(sslServerCert *sc
PR_TRUE);
}
return sc->serverCertChain ? SECSuccess : SECFailure;
}
static SECStatus
ssl_PopulateKeyPair(sslServerCert *sc, sslKeyPair *keyPair)
{
+ /* Copy over the key pair. */
if (sc->serverKeyPair) {
ssl_FreeKeyPair(sc->serverKeyPair);
- sc->serverKeyPair = NULL;
}
if (keyPair) {
- KeyType keyType = SECKEY_GetPublicKeyType(keyPair->pubKey);
- PORT_Assert(keyType == SECKEY_GetPrivateKeyType(keyPair->privKey));
-
- if (keyType == ecKey) {
- sc->namedCurve = ssl_ECPubKey2NamedGroup(keyPair->pubKey);
- if (!sc->namedCurve) {
- /* Unsupported curve. */
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
- }
- }
-
/* Get the size of the cert's public key, and remember it. */
sc->serverKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->pubKey);
if (sc->serverKeyBits == 0) {
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
SECKEY_CacheStaticFlags(keyPair->privKey);
sc->serverKeyPair = ssl_GetKeyPairRef(keyPair);
-
- if (SSL_CERT_IS(sc, ssl_auth_rsa_decrypt)) {
- /* This will update the global session ticket key pair with this
- * key, if a value hasn't been set already. */
- if (ssl_MaybeSetSessionTicketKeyPair(keyPair) != SECSuccess) {
- return SECFailure;
- }
- }
} else {
sc->serverKeyPair = NULL;
- sc->namedCurve = NULL;
}
return SECSuccess;
}
static SECStatus
ssl_PopulateOCSPResponses(sslServerCert *sc,
const SECItemArray *stapledOCSPResponses)
{
@@ -303,92 +276,84 @@ ssl_PopulateSignedCertTimestamps(sslServ
}
if (signedCertTimestamps && signedCertTimestamps->len) {
return SECITEM_CopyItem(NULL, &sc->signedCertTimestamps,
signedCertTimestamps);
}
return SECSuccess;
}
-/* Find any existing certificates that overlap with the new certificate and
- * either remove any supported authentication types that overlap with the new
- * certificate or - if they have no types left - remove them entirely. */
-static void
-ssl_ClearMatchingCerts(sslSocket *ss, sslAuthTypeMask authTypes,
- const sslNamedGroupDef *namedCurve)
+static SECStatus
+ssl_ConfigCert(sslSocket *ss, CERTCertificate *cert,
+ sslKeyPair *keyPair, const SSLExtraServerCertData *data)
{
- PRCList *cursor = PR_NEXT_LINK(&ss->serverCerts);
-
- while (cursor != &ss->serverCerts) {
- sslServerCert *sc = (sslServerCert *)cursor;
- cursor = PR_NEXT_LINK(cursor);
- if ((sc->authTypes & authTypes) == 0) {
- continue;
- }
- /* namedCurve will be NULL only for legacy functions. */
- if (namedCurve != NULL && sc->namedCurve != namedCurve) {
- continue;
- }
-
- sc->authTypes &= ~authTypes;
- if (sc->authTypes == 0) {
- PR_REMOVE_LINK(&sc->link);
- ssl_FreeServerCert(sc);
- }
- }
-}
-
-static SECStatus
-ssl_ConfigCert(sslSocket *ss, sslAuthTypeMask authTypes,
- CERTCertificate *cert, sslKeyPair *keyPair,
- const SSLExtraServerCertData *data)
-{
+ sslServerCert *oldsc;
+ sslServerCertType certType;
SECStatus rv;
sslServerCert *sc = NULL;
int error_code = SEC_ERROR_NO_MEMORY;
PORT_Assert(cert);
PORT_Assert(keyPair);
PORT_Assert(data);
- PORT_Assert(authTypes);
+ PORT_Assert(data->authType != ssl_auth_null);
- if (!cert || !keyPair || !data || !authTypes) {
+ if (!cert || !keyPair || !data || data->authType == ssl_auth_null) {
error_code = SEC_ERROR_INVALID_ARGS;
goto loser;
}
- sc = ssl_NewServerCert();
+ ssl_PopulateCertType(&certType, data->authType, cert, keyPair);
+
+ /* Delete any existing certificate that matches this one, since we can only
+ * use one certificate of a given type. */
+ oldsc = ssl_FindServerCert(ss, &certType);
+ if (oldsc) {
+ PR_REMOVE_LINK(&oldsc->link);
+ ssl_FreeServerCert(oldsc);
+ }
+ sc = ssl_NewServerCert(&certType);
if (!sc) {
goto loser;
}
- sc->authTypes = authTypes;
rv = ssl_PopulateServerCert(sc, cert, data->certChain);
if (rv != SECSuccess) {
goto loser;
}
rv = ssl_PopulateKeyPair(sc, keyPair);
if (rv != SECSuccess) {
- error_code = PORT_GetError();
+ error_code = SEC_ERROR_INVALID_ARGS;
goto loser;
}
rv = ssl_PopulateOCSPResponses(sc, data->stapledOCSPResponses);
if (rv != SECSuccess) {
goto loser;
}
rv = ssl_PopulateSignedCertTimestamps(sc, data->signedCertTimestamps);
if (rv != SECSuccess) {
goto loser;
}
- ssl_ClearMatchingCerts(ss, sc->authTypes, sc->namedCurve);
PR_APPEND_LINK(&sc->link, &ss->serverCerts);
+
+ /* This one-time setup depends on having the certificate in place. */
+ rv = ssl_OneTimeCertSetup(ss, sc);
+ if (rv != SECSuccess) {
+ PR_REMOVE_LINK(&sc->link);
+ error_code = PORT_GetError();
+ goto loser;
+ }
return SECSuccess;
loser:
- ssl_FreeServerCert(sc);
+ if (sc) {
+ ssl_FreeServerCert(sc);
+ }
+ /* This is the only way any of the calls above can fail, except the one time
+ * setup, which doesn't land here. */
PORT_SetError(error_code);
return SECFailure;
}
static SSLAuthType
ssl_GetEcdhAuthType(CERTCertificate *cert)
{
SECOidTag sigTag = SECOID_GetAlgorithmTag(&cert->signature);
@@ -412,100 +377,153 @@ ssl_GetEcdhAuthType(CERTCertificate *cer
case SEC_OID_ANSIX962_ECDSA_SIGNATURE_RECOMMENDED_DIGEST:
case SEC_OID_ANSIX962_ECDSA_SIGNATURE_SPECIFIED_DIGEST:
return ssl_auth_ecdh_ecdsa;
default:
return ssl_auth_null;
}
}
-/* This function examines the type of certificate and its key usage and
- * chooses which authTypes apply. For some certificates
- * this can mean that multiple authTypes.
+/* This function examines the key usages of the given RSA-PKCS1 certificate
+ * and configures one or multiple server certificates based on that data.
*
- * If the targetAuthType is not ssl_auth_null, then only that type will be used.
- * If that choice is invalid, then this function will fail. */
-static sslAuthTypeMask
-ssl_GetCertificateAuthTypes(CERTCertificate *cert, SSLAuthType targetAuthType)
+ * If the data argument contains an authType value other than ssl_auth_null,
+ * then only that slot will be used. If that choice is invalid,
+ * then this will fail. */
+static SECStatus
+ssl_ConfigRsaPkcs1CertByUsage(sslSocket *ss, CERTCertificate *cert,
+ sslKeyPair *keyPair,
+ SSLExtraServerCertData *data)
{
- sslAuthTypeMask authTypes = 0;
+ SECStatus rv = SECFailure;
+
+ PRBool ku_sig = (PRBool)(cert->keyUsage & KU_DIGITAL_SIGNATURE);
+ PRBool ku_enc = (PRBool)(cert->keyUsage & KU_KEY_ENCIPHERMENT);
+
+ if ((data->authType == ssl_auth_rsa_sign && ku_sig) ||
+ (data->authType == ssl_auth_rsa_pss && ku_sig) ||
+ (data->authType == ssl_auth_rsa_decrypt && ku_enc)) {
+ return ssl_ConfigCert(ss, cert, keyPair, data);
+ }
+
+ if (data->authType != ssl_auth_null || !(ku_sig || ku_enc)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (ku_sig) {
+ data->authType = ssl_auth_rsa_sign;
+ rv = ssl_ConfigCert(ss, cert, keyPair, data);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+
+ /* This certificate is RSA, assume that it's also PSS. */
+ data->authType = ssl_auth_rsa_pss;
+ rv = ssl_ConfigCert(ss, cert, keyPair, data);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ }
+
+ if (ku_enc) {
+ /* If ku_sig=true we configure signature and encryption slots with the
+ * same cert. This is bad form, but there are enough dual-usage RSA
+ * certs that we can't really break by limiting this to one type. */
+ data->authType = ssl_auth_rsa_decrypt;
+ rv = ssl_ConfigCert(ss, cert, keyPair, data);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ }
+
+ return rv;
+}
+
+/* This function examines the type of certificate and its key usage and
+ * configures a certificate based on that information. For some certificates
+ * this can mean that multiple server certificates are configured.
+ *
+ * If the data argument contains an authType value other than ssl_auth_null,
+ * then only that slot will be used. If that choice is invalid,
+ * then this will fail. */
+static SECStatus
+ssl_ConfigCertByUsage(sslSocket *ss, CERTCertificate *cert,
+ sslKeyPair *keyPair, const SSLExtraServerCertData *data)
+{
+ SECStatus rv = SECFailure;
+ SSLExtraServerCertData arg;
SECOidTag tag;
+ PORT_Assert(data);
+ /* Take a (shallow) copy so that we can play with it */
+ memcpy(&arg, data, sizeof(arg));
+
tag = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
switch (tag) {
case SEC_OID_X500_RSA_ENCRYPTION:
case SEC_OID_PKCS1_RSA_ENCRYPTION:
- if (cert->keyUsage & KU_DIGITAL_SIGNATURE) {
- authTypes |= 1 << ssl_auth_rsa_sign;
- /* This certificate is RSA, assume that it's also PSS. */
- authTypes |= 1 << ssl_auth_rsa_pss;
- }
-
- if (cert->keyUsage & KU_KEY_ENCIPHERMENT) {
- /* If ku_sig=true we configure signature and encryption slots with the
- * same cert. This is bad form, but there are enough dual-usage RSA
- * certs that we can't really break by limiting this to one type. */
- authTypes |= 1 << ssl_auth_rsa_decrypt;
- }
- break;
+ return ssl_ConfigRsaPkcs1CertByUsage(ss, cert, keyPair, &arg);
case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
if (cert->keyUsage & KU_DIGITAL_SIGNATURE) {
- authTypes |= 1 << ssl_auth_rsa_pss;
+ arg.authType = ssl_auth_rsa_pss;
}
break;
case SEC_OID_ANSIX9_DSA_SIGNATURE:
if (cert->keyUsage & KU_DIGITAL_SIGNATURE) {
- authTypes |= 1 << ssl_auth_dsa;
+ arg.authType = ssl_auth_dsa;
}
break;
case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
- if (cert->keyUsage & KU_DIGITAL_SIGNATURE) {
- authTypes |= 1 << ssl_auth_ecdsa;
- }
- /* Again, bad form to have dual usage and we don't prevent it. */
if (cert->keyUsage & KU_KEY_ENCIPHERMENT) {
- authTypes |= 1 << ssl_GetEcdhAuthType(cert);
+ if ((cert->keyUsage & KU_DIGITAL_SIGNATURE) &&
+ arg.authType == ssl_auth_null) {
+ /* See above regarding bad practice. */
+ arg.authType = ssl_auth_ecdsa;
+ rv = ssl_ConfigCert(ss, cert, keyPair, &arg);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ }
+
+ arg.authType = ssl_GetEcdhAuthType(cert);
+ } else if (cert->keyUsage & KU_DIGITAL_SIGNATURE) {
+ arg.authType = ssl_auth_ecdsa;
}
break;
default:
break;
}
/* Check that we successfully picked an authType */
- if (targetAuthType != ssl_auth_null) {
- authTypes &= 1 << targetAuthType;
+ if (arg.authType == ssl_auth_null) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
}
- return authTypes;
+ /* |data->authType| has to either agree or be ssl_auth_null. */
+ if (data && data->authType != ssl_auth_null &&
+ data->authType != arg.authType) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ return ssl_ConfigCert(ss, cert, keyPair, &arg);
}
/* This function adopts pubKey and destroys it if things go wrong. */
static sslKeyPair *
-ssl_MakeKeyPairForCert(SECKEYPrivateKey *key, CERTCertificate *cert)
+ssl_MakeKeyPairForCert(SECKEYPrivateKey *key, SECKEYPublicKey *pubKey)
{
sslKeyPair *keyPair = NULL;
- SECKEYPublicKey *pubKey = NULL;
SECKEYPrivateKey *privKeyCopy = NULL;
PK11SlotInfo *bestSlot;
- pubKey = CERT_ExtractPublicKey(cert);
- if (!pubKey) {
- PORT_SetError(SEC_ERROR_NO_MEMORY);
- return NULL;
- }
-
- if (SECKEY_GetPublicKeyType(pubKey) != SECKEY_GetPrivateKeyType(key)) {
- SECKEY_DestroyPublicKey(pubKey);
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
- return NULL;
- }
-
if (key->pkcs11Slot) {
bestSlot = PK11_ReferenceSlot(key->pkcs11Slot);
if (bestSlot) {
privKeyCopy = PK11_CopyTokenPrivKeyToSessionPrivKey(bestSlot, key);
PK11_FreeSlot(bestSlot);
}
}
if (!privKeyCopy) {
@@ -522,41 +540,43 @@ ssl_MakeKeyPairForCert(SECKEYPrivateKey
}
if (privKeyCopy) {
keyPair = ssl_NewKeyPair(privKeyCopy, pubKey);
}
if (!keyPair) {
if (privKeyCopy) {
SECKEY_DestroyPrivateKey(privKeyCopy);
}
- SECKEY_DestroyPublicKey(pubKey);
- PORT_SetError(SEC_ERROR_NO_MEMORY);
+ /* We adopted the public key, so we're responsible. */
+ if (pubKey) {
+ SECKEY_DestroyPublicKey(pubKey);
+ }
}
return keyPair;
}
/* Configure a certificate and private key.
*
- * This function examines the certificate and key to determine the type (or
- * types) of authentication the certificate supports. As long as certificates
- * are different (different authTypes and maybe keys in different ec groups),
- * then this function can be called multiple times.
+ * This function examines the certificate and key to determine which slot (or
+ * slots) to place the information in. As long as certificates are different
+ * (based on having different values of sslServerCertType), then this function
+ * can be called multiple times and the certificates will all be remembered.
*/
SECStatus
SSL_ConfigServerCert(PRFileDesc *fd, CERTCertificate *cert,
SECKEYPrivateKey *key,
const SSLExtraServerCertData *data, unsigned int data_len)
{
sslSocket *ss;
+ SECKEYPublicKey *pubKey;
sslKeyPair *keyPair;
SECStatus rv;
SSLExtraServerCertData dataCopy = {
ssl_auth_null, NULL, NULL, NULL
};
- sslAuthTypeMask authTypes;
ss = ssl_FindSocket(fd);
if (!ss) {
return SECFailure;
}
if (!cert || !key) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
@@ -566,33 +586,31 @@ SSL_ConfigServerCert(PRFileDesc *fd, CER
if (data) {
if (data_len > sizeof(dataCopy)) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
PORT_Memcpy(&dataCopy, data, data_len);
}
- authTypes = ssl_GetCertificateAuthTypes(cert, dataCopy.authType);
- if (!authTypes) {
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ pubKey = CERT_ExtractPublicKey(cert);
+ if (!pubKey) {
return SECFailure;
}
- keyPair = ssl_MakeKeyPairForCert(key, cert);
+ keyPair = ssl_MakeKeyPairForCert(key, pubKey);
if (!keyPair) {
+ /* pubKey is adopted by ssl_MakeKeyPairForCert() */
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
return SECFailure;
}
- rv = ssl_ConfigCert(ss, authTypes, cert, keyPair, &dataCopy);
+ rv = ssl_ConfigCertByUsage(ss, cert, keyPair, &dataCopy);
ssl_FreeKeyPair(keyPair);
- if (rv != SECSuccess) {
- return SECFailure;
- }
- return SECSuccess;
+ return rv;
}
/*******************************************************************/
/* Deprecated functions.
*
* The remainder of this file contains deprecated functions for server
* certificate configuration. These configure certificates incorrectly, but in
* a way that allows old code to continue working without change. All these
@@ -607,292 +625,351 @@ SSL_ConfigSecureServer(PRFileDesc *fd, C
return SSL_ConfigSecureServerWithCertChain(fd, cert, NULL, key, kea);
}
/* This implements a limited check that is consistent with the checks performed
* by older versions of NSS. This is less rigorous than the checks in
* ssl_ConfigCertByUsage(), only checking against the type of key and ignoring
* things like usage. */
static PRBool
-ssl_CertSuitableForAuthType(CERTCertificate *cert, sslAuthTypeMask authTypes)
+ssl_CertSuitableForAuthType(CERTCertificate *cert, SSLAuthType authType)
{
SECOidTag tag = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
- sslAuthTypeMask mask = 0;
- switch (tag) {
- case SEC_OID_X500_RSA_ENCRYPTION:
- case SEC_OID_PKCS1_RSA_ENCRYPTION:
- mask |= 1 << ssl_auth_rsa_decrypt;
- mask |= 1 << ssl_auth_rsa_sign;
- break;
- case SEC_OID_ANSIX9_DSA_SIGNATURE:
- mask |= 1 << ssl_auth_dsa;
- break;
- case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
- mask |= 1 << ssl_auth_ecdsa;
- mask |= 1 << ssl_auth_ecdh_rsa;
- mask |= 1 << ssl_auth_ecdh_ecdsa;
- break;
+ switch (authType) {
+ case ssl_auth_rsa_decrypt:
+ case ssl_auth_rsa_sign:
+ return tag == SEC_OID_X500_RSA_ENCRYPTION ||
+ tag == SEC_OID_PKCS1_RSA_ENCRYPTION;
+ case ssl_auth_dsa:
+ return tag == SEC_OID_ANSIX9_DSA_SIGNATURE;
+ case ssl_auth_ecdsa:
+ case ssl_auth_ecdh_rsa:
+ case ssl_auth_ecdh_ecdsa:
+ return tag == SEC_OID_ANSIX962_EC_PUBLIC_KEY;
+ case ssl_auth_null:
+ case ssl_auth_kea:
+ case ssl_auth_rsa_pss: /* not supported with deprecated APIs */
+ return PR_FALSE;
default:
- break;
+ PORT_Assert(0);
+ return PR_FALSE;
}
- PORT_Assert(authTypes);
- /* Simply test that no inappropriate auth types are set. */
- return (authTypes & ~mask) == 0;
}
-/* Lookup a cert for the legacy configuration functions. An exact match on
- * authTypes and ignoring namedCurve will ensure that values configured using
- * legacy functions are overwritten by other legacy functions. */
-static sslServerCert *
-ssl_FindCertWithMask(sslSocket *ss, sslAuthTypeMask authTypes)
-{
- PRCList *cursor;
-
- for (cursor = PR_NEXT_LINK(&ss->serverCerts);
- cursor != &ss->serverCerts;
- cursor = PR_NEXT_LINK(cursor)) {
- sslServerCert *cert = (sslServerCert *)cursor;
- if (cert->authTypes == authTypes) {
- return cert;
- }
- }
- return NULL;
-}
-
-/* This finds an existing server cert in a matching slot that can be reused.
- * Failing that, it removes any other certs that might conflict and makes a new
+/* This finds an existing server cert slot and unlinks it, or it makes a new
* server cert slot of the right type. */
static sslServerCert *
-ssl_FindOrMakeCert(sslSocket *ss, sslAuthTypeMask authTypes)
+ssl_FindOrMakeCertType(sslSocket *ss, SSLAuthType authType)
{
sslServerCert *sc;
+ sslServerCertType certType;
- /* Reuse a perfect match. Note that there is a problem here with use of
- * multiple EC certificates that have keys on different curves: these
- * deprecated functions will match the first found and overwrite that
- * certificate, potentially leaving the other values with a duplicate curve.
- * Configuring multiple EC certificates are only possible with the new
- * functions, so this is not something that is worth fixing. */
- sc = ssl_FindCertWithMask(ss, authTypes);
+ certType.authType = authType;
+ /* Setting the named curve to NULL ensures that all EC certificates
+ * are matched when searching for this slot. */
+ certType.namedCurve = NULL;
+ sc = ssl_FindServerCert(ss, &certType);
if (sc) {
PR_REMOVE_LINK(&sc->link);
return sc;
}
- /* Ignore the namedCurve parameter. Like above, this means that legacy
- * functions will clobber values set with the new functions blindly. */
- ssl_ClearMatchingCerts(ss, authTypes, NULL);
-
- sc = ssl_NewServerCert();
- if (sc) {
- sc->authTypes = authTypes;
- }
- return sc;
+ return ssl_NewServerCert(&certType);
}
-static sslAuthTypeMask
-ssl_KeaTypeToAuthTypeMask(SSLKEAType keaType)
+static void
+ssl_RemoveCertAndKeyByAuthType(sslSocket *ss, SSLAuthType authType)
{
- switch (keaType) {
- case ssl_kea_rsa:
- return (1 << ssl_auth_rsa_decrypt) |
- (1 << ssl_auth_rsa_sign);
+ sslServerCert *sc;
- case ssl_kea_dh:
- return 1 << ssl_auth_dsa;
-
- case ssl_kea_ecdh:
- return (1 << ssl_auth_ecdsa) |
- (1 << ssl_auth_ecdh_rsa) |
- (1 << ssl_auth_ecdh_ecdsa);
-
- default:
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ sc = ssl_FindServerCertByAuthType(ss, authType);
+ if (sc) {
+ (void)ssl_PopulateServerCert(sc, NULL, NULL);
+ (void)ssl_PopulateKeyPair(sc, NULL);
+ /* Leave the entry linked here because the old API expects that. There
+ * might be OCSP stapling values or signed certificate timestamps still
+ * present that will subsequently be used. */
+ /* For ECC certificates, also leave the namedCurve parameter on the slot
+ * unchanged; the value will be updated when a key is added. */
}
- return 0;
}
static SECStatus
-ssl_AddCertChain(sslSocket *ss, CERTCertificate *cert,
- const CERTCertificateList *certChainOpt,
- SECKEYPrivateKey *key, sslAuthTypeMask authTypes)
+ssl_AddCertAndKeyByAuthType(sslSocket *ss, SSLAuthType authType,
+ CERTCertificate *cert,
+ const CERTCertificateList *certChainOpt,
+ sslKeyPair *keyPair)
{
sslServerCert *sc;
- sslKeyPair *keyPair;
SECStatus rv;
- PRErrorCode err = SEC_ERROR_NO_MEMORY;
- if (!ssl_CertSuitableForAuthType(cert, authTypes)) {
+ if (!ssl_CertSuitableForAuthType(cert, authType)) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
- sc = ssl_FindOrMakeCert(ss, authTypes);
+ sc = ssl_FindOrMakeCertType(ss, authType);
if (!sc) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ return SECFailure;
+ }
+ rv = ssl_PopulateKeyPair(sc, keyPair);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
goto loser;
}
-
+ /* Now that we have a key pair, update the details of the slot. Many of the
+ * legacy functions create a slot with a namedCurve of NULL, which
+ * makes the slot unusable; this corrects that. */
+ ssl_PopulateCertType(&sc->certType, authType, cert, keyPair);
rv = ssl_PopulateServerCert(sc, cert, certChainOpt);
if (rv != SECSuccess) {
- goto loser;
- }
-
- keyPair = ssl_MakeKeyPairForCert(key, cert);
- if (!keyPair) {
- /* Error code is set by ssl_MakeKeyPairForCert */
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
goto loser;
}
- rv = ssl_PopulateKeyPair(sc, keyPair);
- ssl_FreeKeyPair(keyPair);
- if (rv != SECSuccess) {
- err = PORT_GetError();
- goto loser;
+ PR_APPEND_LINK(&sc->link, &ss->serverCerts);
+ return ssl_OneTimeCertSetup(ss, sc);
+loser:
+ ssl_FreeServerCert(sc);
+ return SECFailure;
+}
+
+static SECStatus
+ssl_AddCertsByKEA(sslSocket *ss, CERTCertificate *cert,
+ const CERTCertificateList *certChainOpt,
+ SECKEYPrivateKey *key, SSLKEAType certType)
+{
+ SECKEYPublicKey *pubKey;
+ sslKeyPair *keyPair;
+ SECStatus rv;
+
+ pubKey = CERT_ExtractPublicKey(cert);
+ if (!pubKey) {
+ return SECFailure;
+ }
+
+ keyPair = ssl_MakeKeyPairForCert(key, pubKey);
+ if (!keyPair) {
+ /* Note: pubKey is adopted or freed by ssl_MakeKeyPairForCert()
+ * depending on whether it succeeds or not. */
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ return SECFailure;
}
- PR_APPEND_LINK(&sc->link, &ss->serverCerts);
- return SECSuccess;
+ switch (certType) {
+ case ssl_kea_rsa:
+ rv = ssl_AddCertAndKeyByAuthType(ss, ssl_auth_rsa_decrypt,
+ cert, certChainOpt, keyPair);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = ssl_AddCertAndKeyByAuthType(ss, ssl_auth_rsa_sign,
+ cert, certChainOpt, keyPair);
+ break;
+
+ case ssl_kea_dh:
+ rv = ssl_AddCertAndKeyByAuthType(ss, ssl_auth_dsa,
+ cert, certChainOpt, keyPair);
+ break;
-loser:
- ssl_FreeServerCert(sc);
- PORT_SetError(err);
- return SECFailure;
+ case ssl_kea_ecdh:
+ rv = ssl_AddCertAndKeyByAuthType(ss, ssl_auth_ecdsa,
+ cert, certChainOpt, keyPair);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = ssl_AddCertAndKeyByAuthType(ss, ssl_GetEcdhAuthType(cert),
+ cert, certChainOpt, keyPair);
+ break;
+
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ break;
+ }
+
+ ssl_FreeKeyPair(keyPair);
+ return rv;
}
/* Public deprecated function */
SECStatus
SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert,
const CERTCertificateList *certChainOpt,
SECKEYPrivateKey *key, SSLKEAType certType)
{
sslSocket *ss;
- sslAuthTypeMask authTypes;
ss = ssl_FindSocket(fd);
if (!ss) {
return SECFailure;
}
if (!cert != !key) { /* Configure both, or neither */
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
- authTypes = ssl_KeaTypeToAuthTypeMask(certType);
- if (!authTypes) {
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
- return SECFailure;
- }
+ if (!cert) {
+ switch (certType) {
+ case ssl_kea_rsa:
+ ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_rsa_decrypt);
+ ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_rsa_sign);
+ break;
- if (!cert) {
- sslServerCert *sc = ssl_FindCertWithMask(ss, authTypes);
- if (sc) {
- (void)ssl_PopulateServerCert(sc, NULL, NULL);
- (void)ssl_PopulateKeyPair(sc, NULL);
- /* Leave the entry linked here because the old API expects that.
- * There might be OCSP stapling values or signed certificate
- * timestamps still present that will subsequently be used. */
+ case ssl_kea_dh:
+ ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_dsa);
+ break;
+
+ case ssl_kea_ecdh:
+ ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_ecdsa);
+ ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_ecdh_rsa);
+ ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_ecdh_ecdsa);
+ break;
+
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
}
return SECSuccess;
}
- return ssl_AddCertChain(ss, cert, certChainOpt, key, authTypes);
+ return ssl_AddCertsByKEA(ss, cert, certChainOpt, key, certType);
+}
+
+static SECStatus
+ssl_SetOCSPResponsesInSlot(sslSocket *ss, SSLAuthType authType,
+ const SECItemArray *responses)
+{
+ sslServerCert *sc;
+ SECStatus rv;
+
+ sc = ssl_FindOrMakeCertType(ss, authType);
+ if (!sc) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ return SECFailure;
+ }
+ rv = ssl_PopulateOCSPResponses(sc, responses);
+ if (rv == SECSuccess) {
+ PR_APPEND_LINK(&sc->link, &ss->serverCerts);
+ } else {
+ ssl_FreeServerCert(sc);
+ }
+ return rv;
}
/* Public deprecated function */
SECStatus
SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses,
SSLKEAType certType)
{
sslSocket *ss;
- sslServerCert *sc;
- sslAuthTypeMask authTypes;
SECStatus rv;
ss = ssl_FindSocket(fd);
if (!ss) {
SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetStapledOCSPResponses",
SSL_GETPID(), fd));
return SECFailure;
}
- authTypes = ssl_KeaTypeToAuthTypeMask(certType);
- if (!authTypes) {
- SSL_DBG(("%d: SSL[%d]: invalid cert type in SSL_SetStapledOCSPResponses",
- SSL_GETPID(), fd));
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ switch (certType) {
+ case ssl_kea_rsa:
+ rv = ssl_SetOCSPResponsesInSlot(ss, ssl_auth_rsa_decrypt, responses);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ return ssl_SetOCSPResponsesInSlot(ss, ssl_auth_rsa_sign, responses);
+
+ case ssl_kea_dh:
+ return ssl_SetOCSPResponsesInSlot(ss, ssl_auth_dsa, responses);
+
+ case ssl_kea_ecdh:
+ rv = ssl_SetOCSPResponsesInSlot(ss, ssl_auth_ecdsa, responses);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = ssl_SetOCSPResponsesInSlot(ss, ssl_auth_ecdh_rsa, responses);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ return ssl_SetOCSPResponsesInSlot(ss, ssl_auth_ecdh_ecdsa, responses);
+
+ default:
+ SSL_DBG(("%d: SSL[%d]: invalid cert type in SSL_SetStapledOCSPResponses",
+ SSL_GETPID(), fd));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+}
+
+static SECStatus
+ssl_SetSignedTimestampsInSlot(sslSocket *ss, SSLAuthType authType,
+ const SECItem *scts)
+{
+ sslServerCert *sc;
+ SECStatus rv;
+
+ sc = ssl_FindOrMakeCertType(ss, authType);
+ if (!sc) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
return SECFailure;
}
-
- if (!responses) {
- sc = ssl_FindCertWithMask(ss, authTypes);
- if (sc) {
- (void)ssl_PopulateOCSPResponses(sc, NULL);
- }
- return SECSuccess;
- }
-
- sc = ssl_FindOrMakeCert(ss, authTypes);
- if (!sc) {
- return SECFailure;
- }
-
- rv = ssl_PopulateOCSPResponses(sc, responses);
+ rv = ssl_PopulateSignedCertTimestamps(sc, scts);
if (rv == SECSuccess) {
PR_APPEND_LINK(&sc->link, &ss->serverCerts);
} else {
ssl_FreeServerCert(sc);
}
return rv;
}
/* Public deprecated function */
SECStatus
SSL_SetSignedCertTimestamps(PRFileDesc *fd, const SECItem *scts,
SSLKEAType certType)
{
sslSocket *ss;
- sslServerCert *sc;
- sslAuthTypeMask authTypes;
SECStatus rv;
ss = ssl_FindSocket(fd);
if (!ss) {
SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSignedCertTimestamps",
SSL_GETPID(), fd));
return SECFailure;
}
- authTypes = ssl_KeaTypeToAuthTypeMask(certType);
- if (!authTypes) {
- SSL_DBG(("%d: SSL[%d]: invalid cert type in SSL_SetSignedCertTimestamps",
- SSL_GETPID(), fd));
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
- return SECFailure;
- }
+ switch (certType) {
+ case ssl_kea_rsa:
+ rv = ssl_SetSignedTimestampsInSlot(ss, ssl_auth_rsa_decrypt, scts);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ return ssl_SetSignedTimestampsInSlot(ss, ssl_auth_rsa_sign, scts);
+
+ case ssl_kea_dh:
+ return ssl_SetSignedTimestampsInSlot(ss, ssl_auth_dsa, scts);
- if (!scts) {
- sc = ssl_FindCertWithMask(ss, authTypes);
- if (sc) {
- (void)ssl_PopulateSignedCertTimestamps(sc, NULL);
- }
- return SECSuccess;
- }
+ case ssl_kea_ecdh:
+ rv = ssl_SetSignedTimestampsInSlot(ss, ssl_auth_ecdsa, scts);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = ssl_SetSignedTimestampsInSlot(ss, ssl_auth_ecdh_rsa, scts);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ return ssl_SetSignedTimestampsInSlot(ss, ssl_auth_ecdh_ecdsa, scts);
- sc = ssl_FindOrMakeCert(ss, authTypes);
- if (!sc) {
- return SECFailure;
+ default:
+ SSL_DBG(("%d: SSL[%d]: invalid cert type in SSL_SetSignedCertTimestamps",
+ SSL_GETPID(), fd));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
}
-
- rv = ssl_PopulateSignedCertTimestamps(sc, scts);
- if (rv == SECSuccess) {
- PR_APPEND_LINK(&sc->link, &ss->serverCerts);
- } else {
- ssl_FreeServerCert(sc);
- }
- return rv;
}
/* Public deprecated function. */
SSLKEAType
NSS_FindCertKEAType(CERTCertificate *cert)
{
int tag;
--- a/security/nss/lib/ssl/sslcert.h
+++ b/security/nss/lib/ssl/sslcert.h
@@ -8,53 +8,52 @@
#ifndef __sslcert_h_
#define __sslcert_h_
#include "cert.h"
#include "secitem.h"
#include "keyhi.h"
-/* This type is a bitvector that is indexed by SSLAuthType values. Note that
- * the bit for ssl_auth_null(0) - the least significant bit - isn't used. */
-typedef PRUint16 sslAuthTypeMask;
-PR_STATIC_ASSERT(sizeof(sslAuthTypeMask) * 8 >= ssl_auth_size);
-
-typedef struct sslServerCertStr {
- PRCList link; /* The linked list link */
-
- /* The auth types that this certificate provides. */
- sslAuthTypeMask authTypes;
+/* The following struct identifies a single slot into which a certificate can be
+** loaded. The authType field determines the basic slot, then additional
+** parameters further narrow the slot.
+**
+** An EC key (ssl_auth_ecdsa or ssl_auth_ecdh_*) is assigned to a slot based on
+** the named curve of the key.
+*/
+typedef struct sslServerCertTypeStr {
+ SSLAuthType authType;
/* For ssl_auth_ecdsa and ssl_auth_ecdh_*. This is only the named curve
* of the end-entity certificate key. The keys in other certificates in
* the chain aren't directly relevant to the operation of TLS (though it
* might make certificate validation difficult, libssl doesn't care). */
const sslNamedGroupDef *namedCurve;
+} sslServerCertType;
+
+typedef struct sslServerCertStr {
+ PRCList link; /* The linked list link */
+
+ sslServerCertType certType; /* The certificate slot this occupies */
/* Configuration state for server sockets */
CERTCertificate *serverCert;
CERTCertificateList *serverCertChain;
sslKeyPair *serverKeyPair;
unsigned int serverKeyBits;
/* Each certificate needs its own status. */
SECItemArray *certStatusArray;
/* Serialized signed certificate timestamps to be sent to the client
** in a TLS extension (server only). Each certificate needs its own
** timestamps item.
*/
SECItem signedCertTimestamps;
} sslServerCert;
-#define SSL_CERT_IS(c, t) ((c)->authTypes & (1 << (t)))
-#define SSL_CERT_IS_ONLY(c, t) ((c)->authTypes == (1 << (t)))
-#define SSL_CERT_IS_EC(c) \
- ((c)->authTypes & ((1 << ssl_auth_ecdsa) | \
- (1 << ssl_auth_ecdh_rsa) | \
- (1 << ssl_auth_ecdh_ecdsa)))
-
-extern sslServerCert *ssl_NewServerCert();
+extern sslServerCert *ssl_NewServerCert(const sslServerCertType *slot);
extern sslServerCert *ssl_CopyServerCert(const sslServerCert *oc);
-extern const sslServerCert *ssl_FindServerCert(
- const sslSocket *ss, SSLAuthType authType,
- const sslNamedGroupDef *namedCurve);
+extern sslServerCert *ssl_FindServerCert(const sslSocket *ss,
+ const sslServerCertType *slot);
+extern sslServerCert *ssl_FindServerCertByAuthType(const sslSocket *ss,
+ SSLAuthType authType);
extern void ssl_FreeServerCert(sslServerCert *sc);
#endif /* __sslcert_h_ */
--- a/security/nss/lib/ssl/ssldef.c
+++ b/security/nss/lib/ssl/ssldef.c
@@ -61,18 +61,16 @@ ssl_DefShutdown(sslSocket *ss, int how)
}
int
ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags)
{
PRFileDesc *lower = ss->fd->lower;
int rv;
- PORT_Assert(buf && len > 0);
-
rv = lower->methods->recv(lower, (void *)buf, len, flags, ss->rTimeout);
if (rv < 0) {
DEFINE_ERROR
MAP_ERROR(PR_SOCKET_SHUTDOWN_ERROR, PR_CONNECT_RESET_ERROR)
} else if (rv > len) {
PORT_Assert(rv <= len);
PORT_SetError(PR_BUFFER_OVERFLOW_ERROR);
rv = SECFailure;
--- a/security/nss/lib/ssl/sslerr.h
+++ b/security/nss/lib/ssl/sslerr.h
@@ -239,16 +239,15 @@ typedef enum {
SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION = (SSL_ERROR_BASE + 152),
SSL_ERROR_TOO_MANY_RECORDS = (SSL_ERROR_BASE + 153),
SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST = (SSL_ERROR_BASE + 154),
SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST = (SSL_ERROR_BASE + 155),
SSL_ERROR_BAD_2ND_CLIENT_HELLO = (SSL_ERROR_BASE + 156),
SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION = (SSL_ERROR_BASE + 157),
SSL_ERROR_MALFORMED_PSK_KEY_EXCHANGE_MODES = (SSL_ERROR_BASE + 158),
SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES = (SSL_ERROR_BASE + 159),
- SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA = (SSL_ERROR_BASE + 160),
SSL_ERROR_END_OF_LIST /* let the c compiler determine the value of this. */
} SSLErrorCodes;
#endif /* NO_SECURITY_ERROR_ENUM */
/* clang-format on */
#endif /* __SSL_ERR_H_ */
--- a/security/nss/lib/ssl/sslimpl.h
+++ b/security/nss/lib/ssl/sslimpl.h
@@ -29,17 +29,17 @@
#include "nssrwlk.h"
#include "prthread.h"
#include "prclist.h"
#include "private/pprthred.h"
#include "sslt.h" /* for some formerly private types, now public */
typedef struct sslSocketStr sslSocket;
-typedef struct ssl3CipherSpecStr ssl3CipherSpec;
+
#include "ssl3ext.h"
/* to make some of these old enums public without namespace pollution,
** it was necessary to prepend ssl_ to the names.
** These #defines preserve compatibility with the old code here in libssl.
*/
typedef SSLMACAlgorithm SSL3MACAlgorithm;
@@ -120,18 +120,17 @@ typedef enum { SSLAppOpRead = 0,
#define SSL3_SESSIONID_BYTES 32
#define SSL_MIN_CHALLENGE_BYTES 16
#define SSL_MAX_CHALLENGE_BYTES 32
#define SSL3_MASTER_SECRET_LENGTH 48
/* number of wrap mechanisms potentially used to wrap master secrets. */
-#define SSL_NUM_WRAP_MECHS 15
-#define SSL_NUM_WRAP_KEYS 6
+#define SSL_NUM_WRAP_MECHS 16
/* This makes the cert cache entry exactly 4k. */
#define SSL_MAX_CACHED_CERT_LEN 4060
#ifndef BPB
#define BPB 8 /* Bits Per Byte */
#endif
@@ -196,19 +195,16 @@ struct ssl3CertNodeStr {
typedef SECStatus (*sslHandshakeFunc)(sslSocket *ss);
typedef void (*sslSessionIDCacheFunc)(sslSessionID *sid);
typedef void (*sslSessionIDUncacheFunc)(sslSessionID *sid);
typedef sslSessionID *(*sslSessionIDLookupFunc)(const PRIPv6Addr *addr,
unsigned char *sid,
unsigned int sidLen,
CERTCertDBHandle *dbHandle);
-typedef void (*sslCipherSpecChangedFunc)(void *arg,
- PRBool sending,
- ssl3CipherSpec *newSpec);
/* Socket ops */
struct sslSocketOpsStr {
int (*connect)(sslSocket *, const PRNetAddr *);
PRFileDesc *(*accept)(sslSocket *, PRNetAddr *);
int (*bind)(sslSocket *, const PRNetAddr *);
int (*listen)(sslSocket *, int);
int (*shutdown)(sslSocket *, int);
@@ -366,20 +362,16 @@ struct sslGatherStr {
*/
unsigned char hdr[13];
/* Buffer for DTLS data read off the wire as a single datagram */
sslBuffer dtlsPacket;
/* the start of the buffered DTLS record in dtlsPacket */
unsigned int dtlsPacketOffset;
-
- /* tracks whether we've seen a v3-type record before and must reject
- * any further v2-type records. */
- PRBool rejectV2Records;
};
/* sslGather.state */
#define GS_INIT 0
#define GS_HEADER 1
#define GS_DATA 2
/*
@@ -472,17 +464,17 @@ typedef struct DTLSRecvdRecordsStr {
sslSequenceNumber right;
} DTLSRecvdRecords;
/*
** These are the "specs" in the "ssl3" struct.
** Access to the pointers to these specs, and all the specs' contents
** (direct and indirect) is protected by the reader/writer lock ss->specLock.
*/
-struct ssl3CipherSpecStr {
+typedef struct {
PRCList link;
const ssl3BulkCipherDef *cipher_def;
const ssl3MACDef *mac_def;
SSLCompressionMethod compression_method;
int mac_size;
SSLCipher encode;
SSLCipher decode;
SSLAEADCipher aead;
@@ -502,17 +494,17 @@ struct ssl3CipherSpecStr {
ssl3KeyMaterial client;
ssl3KeyMaterial server;
SECItem msItem;
DTLSEpoch epoch;
DTLSRecvdRecords recvdRecords;
PRUint8 refCt;
const char *phase;
-};
+} ssl3CipherSpec;
typedef enum { never_cached,
in_client_cache,
in_server_cache,
invalid_cache /* no longer in any cache. */
} Cached;
#include "sslcert.h"
@@ -526,20 +518,20 @@ struct sslSessionIDStr {
int references;
PRUint32 lastAccessTime; /* seconds since Jan 1, 1970 */
/* The rest of the members, except for the members of u.ssl3.locked, may
* be modified only when the sid is not in any cache.
*/
CERTCertificate *peerCert;
- SECItemArray peerCertStatus; /* client only */
- const char *peerID; /* client only */
- const char *urlSvrName; /* client only */
- const sslNamedGroupDef *namedCurve; /* (server) for certificate lookup */
+ SECItemArray peerCertStatus; /* client only */
+ const char *peerID; /* client only */
+ const char *urlSvrName; /* client only */
+ sslServerCertType certType;
CERTCertificate *localCert;
PRIPv6Addr addr;
PRUint16 port;
SSL3ProtocolVersion version;
PRUint32 creationTime; /* seconds since Jan 1, 1970 */
@@ -897,21 +889,16 @@ struct ssl3StateStr {
** The following Specs and Spec pointers must be protected using the
** Spec Lock.
*/
ssl3CipherSpec *crSpec; /* current read spec. */
ssl3CipherSpec *prSpec; /* pending read spec. */
ssl3CipherSpec *cwSpec; /* current write spec. */
ssl3CipherSpec *pwSpec; /* pending write spec. */
- /* Internal callback for when we do a cipher suite change. Used for
- * debugging in TLS 1.3. This can only be set by non-public functions. */
- sslCipherSpecChangedFunc changedCipherSpecFunc;
- void *changedCipherSpecArg;
-
CERTCertificate *clientCertificate; /* used by client */
SECKEYPrivateKey *clientPrivateKey; /* used by client */
CERTCertificateList *clientCertChain; /* used by client */
PRBool sendEmptyCert; /* used by client */
int policy;
/* This says what cipher suites we can do, and should
* be either SSL_ALLOWED or SSL_RESTRICTED
@@ -979,32 +966,31 @@ struct ssl3DHParamsStr {
typedef struct SSLWrappedSymWrappingKeyStr {
SSL3Opaque wrappedSymmetricWrappingkey[512];
CK_MECHANISM_TYPE symWrapMechanism;
/* unwrapped symmetric wrapping key uses this mechanism */
CK_MECHANISM_TYPE asymWrapMechanism;
/* mechanism used to wrap the SymmetricWrappingKey using
* server's public and/or private keys. */
- PRInt16 wrapMechIndex;
- PRUint16 wrapKeyIndex;
+ SSLAuthType authType; /* type of keys used to wrap SymWrapKey*/
+ PRInt32 symWrapMechIndex;
PRUint16 wrappedSymKeyLen;
} SSLWrappedSymWrappingKey;
typedef struct SessionTicketStr {
PRUint16 ticket_version;
SSL3ProtocolVersion ssl_version;
ssl3CipherSuite cipher_suite;
SSLCompressionMethod compression_method;
SSLAuthType authType;
PRUint32 authKeyBits;
SSLKEAType keaType;
PRUint32 keaKeyBits;
- const sslNamedGroupDef *namedCurve; /* For certificate lookup. */
-
+ sslServerCertType certType;
/*
* msWrapMech contains a meaningful value only if ms_is_wrapped is true.
*/
PRUint8 ms_is_wrapped;
CK_MECHANISM_TYPE msWrapMech;
PRUint16 ms_length;
SSL3Opaque master_secret[48];
PRBool extendedMasterSecretUsed;
@@ -1225,16 +1211,17 @@ struct sslSocketStr {
/* All the global data items declared here should be protected using the
** ssl_global_data_lock, which is a reader/writer lock.
*/
extern NSSRWLock *ssl_global_data_lock;
extern char ssl_debug;
extern char ssl_trace;
extern FILE *ssl_trace_iob;
extern FILE *ssl_keylog_iob;
+extern CERTDistNames *ssl3_server_ca_list;
extern PRUint32 ssl_sid_timeout;
extern PRUint32 ssl3_sid_timeout;
extern const char *const ssl3_cipherName[];
extern sslSessionIDLookupFunc ssl_sid_lookup;
extern sslSessionIDCacheFunc ssl_sid_cache;
extern sslSessionIDUncacheFunc ssl_sid_uncache;
@@ -1655,23 +1642,22 @@ extern SECStatus ssl3_AppendHandshake(ss
extern SECStatus ssl3_AppendHandshakeHeader(sslSocket *ss,
SSL3HandshakeType t, PRUint32 length);
extern SECStatus ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num,
PRInt32 lenSize);
extern SECStatus ssl3_AppendHandshakeVariable(sslSocket *ss,
const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize);
extern SECStatus ssl3_AppendSignatureAndHashAlgorithm(
sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash);
-extern SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes,
+extern SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes,
SSL3Opaque **b, PRUint32 *length);
-extern SECStatus ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num,
- PRUint32 bytes, SSL3Opaque **b,
- PRUint32 *length);
+extern PRInt32 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes,
+ SSL3Opaque **b, PRUint32 *length);
extern SECStatus ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i,
- PRUint32 bytes, SSL3Opaque **b,
+ PRInt32 bytes, SSL3Opaque **b,
PRUint32 *length);
extern PRUint8 *ssl_EncodeUintX(PRUint64 value, unsigned int bytes,
PRUint8 *to);
extern PRBool ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme);
extern SECStatus ssl_CheckSignatureSchemeConsistency(
sslSocket *ss, SSLSignatureScheme scheme, CERTCertificate *cert);
extern SECStatus ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
SSLSignatureScheme **schemesOut,
@@ -1680,29 +1666,31 @@ extern SECStatus ssl_ParseSignatureSchem
unsigned int *len);
extern SECStatus ssl_ConsumeSignatureScheme(
sslSocket *ss, SSL3Opaque **b, PRUint32 *length, SSLSignatureScheme *out);
extern SECStatus ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash,
SECKEYPrivateKey *key, SECItem *buf);
extern SECStatus ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme,
SSL3Hashes *hash, SECItem *buf);
extern SECStatus ssl3_CacheWrappedMasterSecret(
- sslSocket *ss, sslSessionID *sid, ssl3CipherSpec *spec);
+ sslSocket *ss, sslSessionID *sid,
+ ssl3CipherSpec *spec, SSLAuthType authType);
extern void ssl3_FreeSniNameArray(TLSExtensionData *xtnData);
/* Hello Extension related routines. */
extern void ssl3_SetSIDSessionTicket(sslSessionID *sid,
/*in/out*/ NewSessionTicket *session_ticket);
SECStatus ssl3_EncodeSessionTicket(sslSocket *ss,
const NewSessionTicket *ticket_input,
SECItem *ticket_data);
-SECStatus ssl_MaybeSetSessionTicketKeyPair(const sslKeyPair *keyPair);
-SECStatus ssl_GetSessionTicketKeys(sslSocket *ss, unsigned char *keyName,
- PK11SymKey **encKey, PK11SymKey **macKey);
-void ssl_ResetSessionTicketKeys();
+extern PRBool ssl_GetSessionTicketKeys(SECKEYPrivateKey *svrPrivKey,
+ SECKEYPublicKey *svrPubKey, void *pwArg,
+ unsigned char *keyName, PK11SymKey **aesKey,
+ PK11SymKey **macKey);
+extern SECStatus ssl3_SessionTicketShutdown(void *appData, void *nssData);
/* Tell clients to consider tickets valid for this long. */
#define TLS_EX_SESS_TICKET_LIFETIME_HINT (2 * 24 * 60 * 60) /* 2 days */
#define TLS_EX_SESS_TICKET_VERSION (0x0103)
extern SECStatus ssl3_ValidateNextProtoNego(const unsigned char *data,
unsigned int length);
@@ -1710,30 +1698,30 @@ extern SECStatus ssl3_ValidateNextProtoN
extern PRFileDesc *ssl_NewPRSocket(sslSocket *ss, PRFileDesc *fd);
extern void ssl_FreePRSocket(PRFileDesc *fd);
/* Internal config function so SSL3 can initialize the present state of
* various ciphers */
extern int ssl3_config_match_init(sslSocket *);
/* calls for accessing wrapping keys across processes. */
-extern SECStatus
-ssl_GetWrappingKey(unsigned int symWrapMechIndex, unsigned int wrapKeyIndex,
+extern PRBool
+ssl_GetWrappingKey(PRInt32 symWrapMechIndex, SSLAuthType authType,
SSLWrappedSymWrappingKey *wswk);
/* The caller passes in the new value it wants
* to set. This code tests the wrapped sym key entry in the file on disk.
* If it is uninitialized, this function writes the caller's value into
* the disk entry, and returns false.
* Otherwise, it overwrites the caller's wswk with the value obtained from
* the disk, and returns PR_TRUE.
* This is all done while holding the locks/semaphores necessary to make
* the operation atomic.
*/
-extern SECStatus
+extern PRBool
ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk);
/* get rid of the symmetric wrapping key references. */
extern SECStatus SSL3_ShutdownServerCache(void);
extern SECStatus ssl_InitSymWrapKeysLock(void);
extern SECStatus ssl_FreeSymWrapKeysLock(void);
@@ -1788,18 +1776,18 @@ SECStatus ssl3_HandleNoCertificate(sslSo
SECStatus ssl3_SendEmptyCertificate(sslSocket *ss);
void ssl3_CleanupPeerCerts(sslSocket *ss);
SECStatus ssl3_SendCertificateStatus(sslSocket *ss);
SECStatus ssl3_AuthCertificate(sslSocket *ss);
SECStatus ssl_ReadCertificateStatus(sslSocket *ss, SSL3Opaque *b,
PRUint32 length);
SECStatus ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint8 *buf,
unsigned maxLen, PRUint32 *len);
-SECStatus ssl_GetCertificateRequestCAs(sslSocket *ss, unsigned int *calenp,
- SECItem **namesp, unsigned int *nnamesp);
+void ssl3_GetCertificateRequestCAs(sslSocket *ss, int *calenp, SECItem **namesp,
+ int *nnamesp);
SECStatus ssl3_ParseCertificateRequestCAs(sslSocket *ss, SSL3Opaque **b,
PRUint32 *length, PLArenaPool *arena,
CERTDistNames *ca_list);
SECStatus ssl3_CompleteHandleCertificateRequest(
sslSocket *ss, const SSLSignatureScheme *signatureSchemes,
unsigned int signatureSchemeCount, CERTDistNames *ca_list);
SECStatus ssl3_SendServerHello(sslSocket *ss);
SECStatus ssl3_ComputeHandshakeHashes(sslSocket *ss,
@@ -1809,16 +1797,17 @@ SECStatus ssl3_ComputeHandshakeHashes(ss
SECStatus ssl_CreateECDHEphemeralKeyPair(const sslSocket *ss,
const sslNamedGroupDef *ecGroup,
sslEphemeralKeyPair **keyPair);
SECStatus ssl_CreateStaticECDHEKey(sslSocket *ss,
const sslNamedGroupDef *ecGroup);
SECStatus ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags);
PK11SymKey *ssl3_GetWrappingKey(sslSocket *ss,
PK11SlotInfo *masterSecretSlot,
+ const sslServerCert *serverCert,
CK_MECHANISM_TYPE masterWrapMech,
void *pwArg);
SECStatus ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid);
const ssl3CipherSuiteDef *ssl_LookupCipherSuiteDef(ssl3CipherSuite suite);
const ssl3BulkCipherDef *
ssl_GetBulkCipherDef(const ssl3CipherSuiteDef *cipher_def);
SECStatus ssl3_SelectServerCert(sslSocket *ss);
SECStatus ssl_PickSignatureScheme(sslSocket *ss,
@@ -1841,30 +1830,30 @@ SECStatus ssl3_SetCipherSuite(sslSocket
#ifdef DEBUG
extern void ssl3_CheckCipherSuiteOrderConsistency();
#endif
extern int ssl_MapLowLevelError(int hiLevelError);
extern PRUint32 ssl_Time(void);
-extern PRBool ssl_TicketTimeValid(const NewSessionTicket *ticket);
extern void SSL_AtomicIncrementLong(long *x);
SECStatus ssl3_ApplyNSSPolicy(void);
extern HASH_HashType
ssl3_GetTls12HashType(sslSocket *ss);
extern SECStatus
-ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
+ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec,
const char *label, unsigned int labelLen,
const unsigned char *val, unsigned int valLen,
- unsigned char *out, unsigned int outLen);
+ unsigned char *out, unsigned int outLen,
+ HASH_HashType tls12HashType);
#ifdef TRACE
#define SSL_TRACE(msg) ssl_Trace msg
#else
#define SSL_TRACE(msg)
#endif
void ssl_Trace(const char *format, ...);
--- a/security/nss/lib/ssl/sslinfo.c
+++ b/security/nss/lib/ssl/sslinfo.c
@@ -135,19 +135,16 @@ SSL_GetPreliminaryChannelInfo(PRFileDesc
}
memset(&inf, 0, sizeof(inf));
inf.length = PR_MIN(sizeof(inf), len);
inf.valuesSet = ss->ssl3.hs.preliminaryInfo;
inf.protocolVersion = ss->version;
inf.cipherSuite = ss->ssl3.hs.cipher_suite;
- inf.canSendEarlyData = !ss->sec.isServer &&
- (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) &&
- !ss->firstHsDone;
memcpy(info, &inf, inf.length);
return SECSuccess;
}
/* name */
#define CS_(x) x, #x
#define CS(x) CS_(TLS_##x)
@@ -453,18 +450,19 @@ SSL_ExportKeyingMaterial(PRFileDesc *fd,
/* Allow TLS keying material to be exported sooner, when the master
* secret is available and we have sent ChangeCipherSpec.
*/
ssl_GetSpecReadLock(ss);
if (!ss->ssl3.cwSpec->master_secret && !ss->ssl3.cwSpec->msItem.len) {
PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
rv = SECFailure;
} else {
- rv = ssl3_TLSPRFWithMasterSecret(ss, ss->ssl3.cwSpec, label, labelLen,
- val, valLen, out, outLen);
+ HASH_HashType ht = ssl3_GetTls12HashType(ss);
+ rv = ssl3_TLSPRFWithMasterSecret(ss->ssl3.cwSpec, label, labelLen, val,
+ valLen, out, outLen, ht);
}
ssl_ReleaseSpecReadLock(ss);
PORT_ZFree(val, valLen);
return rv;
}
SECStatus
--- a/security/nss/lib/ssl/sslmutex.c
+++ b/security/nss/lib/ssl/sslmutex.c
@@ -55,18 +55,17 @@ single_process_sslMutex_Lock(sslMutex* p
if (!pMutex->u.sslLock) {
PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
return SECFailure;
}
PR_Lock(pMutex->u.sslLock);
return SECSuccess;
}
-#if defined(LINUX) || defined(AIX) || defined(BEOS) || defined(BSDI) || \
- (defined(NETBSD) && __NetBSD_Version__ < 500000000) || defined(OPENBSD) || defined(__GLIBC__)
+#if defined(LINUX) || defined(AIX) || defined(BEOS) || defined(BSDI) || (defined(NETBSD) && __NetBSD_Version__ < 500000000) || defined(OPENBSD)
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include "unix_err.h"
#include "pratom.h"
--- a/security/nss/lib/ssl/sslmutex.h
+++ b/security/nss/lib/ssl/sslmutex.h
@@ -44,18 +44,17 @@ typedef struct {
#endif
PRLock *sslLock;
HANDLE sslMutx;
} u;
} sslMutex;
typedef int sslPID;
-#elif defined(LINUX) || defined(AIX) || defined(BEOS) || defined(BSDI) || \
- (defined(NETBSD) && __NetBSD_Version__ < 500000000) || defined(OPENBSD) || defined(__GLIBC__)
+#elif defined(LINUX) || defined(AIX) || defined(BEOS) || defined(BSDI) || (defined(NETBSD) && __NetBSD_Version__ < 500000000) || defined(OPENBSD)
#include <sys/types.h>
#include "prtypes.h"
typedef struct {
PRBool isMultiProcess;
union {
PRLock *sslLock;
--- a/security/nss/lib/ssl/sslnonce.c
+++ b/security/nss/lib/ssl/sslnonce.c
@@ -1,9 +1,8 @@
-/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file implements the CLIENT Session ID cache.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "cert.h"
@@ -456,30 +455,16 @@ ssl_Time(void)
now = PR_Now();
LL_I2L(ll, 1000000L);
LL_DIV(now, now, ll);
LL_L2UI(myTime, now);
#endif
return myTime;
}
-PRBool
-ssl_TicketTimeValid(const NewSessionTicket *ticket)
-{
- PRTime endTime;
-
- if (ticket->ticket_lifetime_hint == 0) {
- return PR_TRUE;
- }
-
- endTime = ticket->received_timestamp +
- (PRTime)(ticket->ticket_lifetime_hint * PR_USEC_PER_MSEC);
- return endTime > PR_Now();
-}
-
void
ssl3_SetSIDSessionTicket(sslSessionID *sid,
/*in/out*/ NewSessionTicket *newSessionTicket)
{
PORT_Assert(sid);
PORT_Assert(newSessionTicket);
PORT_Assert(newSessionTicket->ticket.data);
PORT_Assert(newSessionTicket->ticket.len != 0);
--- a/security/nss/lib/ssl/sslsnce.c
+++ b/security/nss/lib/ssl/sslsnce.c
@@ -1,9 +1,8 @@
-/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This file implements the SERVER Session ID cache.
* NOTE: The contents of this file are NOT used by the client.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* Note: ssl_FreeSID() in sslnonce.c gets used for both client and server
@@ -29,17 +28,17 @@
* struct {
* cacheDescriptor desc;
* sidCacheLock sidCacheLocks[ numSIDCacheLocks];
* sidCacheLock keyCacheLock;
* sidCacheLock certCacheLock;
* sidCacheSet sidCacheSets[ numSIDCacheSets ];
* sidCacheEntry sidCacheData[ numSIDCacheEntries];
* certCacheEntry certCacheData[numCertCacheEntries];
- * SSLWrappedSymWrappingKey keyCacheData[SSL_NUM_WRAP_KEYS][SSL_NUM_WRAP_MECHS];
+ * SSLWrappedSymWrappingKey keyCacheData[ssl_auth_size][SSL_NUM_WRAP_MECHS];
* PRUint8 keyNameSuffix[SESS_TICKET_KEY_VAR_NAME_LEN]
* encKeyCacheEntry ticketEncKey; // Wrapped
* encKeyCacheEntry ticketMacKey; // Wrapped
* PRBool ticketKeysValid;
* sidCacheLock srvNameCacheLock;
* srvNameCacheEntry srvNameData[ numSrvNameCacheEntries ];
* } cacheMemCacheData;
*/
@@ -50,17 +49,16 @@
#include "cert.h"
#include "ssl.h"
#include "sslimpl.h"
#include "sslproto.h"
#include "pk11func.h"
#include "base64.h"
#include "keyhi.h"
#include "blapit.h"
-#include "nss.h" /* for NSS_RegisterShutdown */
#include "sechash.h"
#include <stdio.h>
#if defined(XP_UNIX) || defined(XP_BEOS)
#include <syslog.h>
#include <fcntl.h>
@@ -106,17 +104,17 @@ struct sidCacheEntryStr {
/* 2 */ PRUint16 compression; /* SSLCompressionMethod */
/* 54 */ ssl3SidKeys keys; /* keys, wrapped as needed. */
/* 4 */ PRUint32 masterWrapMech;
/* 4 */ PRInt32 certIndex;
/* 4 */ PRInt32 srvNameIndex;
/* 32 */ PRUint8 srvNameHash[SHA256_LENGTH]; /* SHA256 name hash */
- /* 2 */ PRUint16 namedCurve;
+ /* 2 */ PRUint16 certTypeArgs;
/*104 */} ssl3;
/* force sizeof(sidCacheEntry) to be a multiple of cache line size */
struct {
/*120 */ PRUint8 filler[120]; /* 72+120==192, a multiple of 16 */
} forceSize;
} u;
};
@@ -437,22 +435,27 @@ ConvertFromSID(sidCacheEntry *to, sslSes
to->u.ssl3.compression = (PRUint16)from->u.ssl3.compression;
to->u.ssl3.keys = from->u.ssl3.keys;
to->u.ssl3.masterWrapMech = from->u.ssl3.masterWrapMech;
to->sessionIDLength = from->u.ssl3.sessionIDLength;
to->u.ssl3.certIndex = -1;
to->u.ssl3.srvNameIndex = -1;
PORT_Memcpy(to->sessionID, from->u.ssl3.sessionID,
to->sessionIDLength);
- to->u.ssl3.namedCurve = 0U;
- if (from->authType == ssl_auth_ecdsa ||
- from->authType == ssl_auth_ecdh_rsa ||
- from->authType == ssl_auth_ecdh_ecdsa) {
- PORT_Assert(from->namedCurve);
- to->u.ssl3.namedCurve = (PRUint16)from->namedCurve->name;
+ to->u.ssl3.certTypeArgs = 0U;
+ switch (from->authType) {
+ case ssl_auth_ecdsa:
+ case ssl_auth_ecdh_rsa:
+ case ssl_auth_ecdh_ecdsa:
+ PORT_Assert(from->certType.namedCurve);
+ to->u.ssl3.certTypeArgs =
+ (PRUint16)from->certType.namedCurve->name;
+ break;
+ default:
+ break;
}
SSL_TRC(8, ("%d: SSL3: ConvertSID: time=%d addr=0x%08x%08x%08x%08x "
"cipherSuite=%d",
myPid, to->creationTime, to->addr.pr_s6_addr32[0],
to->addr.pr_s6_addr32[1], to->addr.pr_s6_addr32[2],
to->addr.pr_s6_addr32[3], to->u.ssl3.cipherSuite));
}
@@ -518,21 +521,26 @@ ConvertToSID(sidCacheEntry *from,
derCert.len = pcce->certLength;
derCert.data = pcce->cert;
to->peerCert = CERT_NewTempCertificate(dbHandle, &derCert, NULL,
PR_FALSE, PR_TRUE);
if (to->peerCert == NULL)
goto loser;
}
- if (from->authType == ssl_auth_ecdsa ||
- from->authType == ssl_auth_ecdh_rsa ||
- from->authType == ssl_auth_ecdh_ecdsa) {
- to->namedCurve =
- ssl_LookupNamedGroup((SSLNamedGroup)from->u.ssl3.namedCurve);
+ to->certType.authType = from->authType;
+ switch (from->authType) {
+ case ssl_auth_ecdsa:
+ case ssl_auth_ecdh_rsa:
+ case ssl_auth_ecdh_ecdsa:
+ to->certType.namedCurve =
+ ssl_LookupNamedGroup((SSLNamedGroup)from->u.ssl3.certTypeArgs);
+ break;
+ default:
+ break;
}
to->version = from->version;
to->creationTime = from->creationTime;
to->lastAccessTime = from->lastAccessTime;
to->expirationTime = from->expirationTime;
to->cached = in_server_cache;
to->addr = from->addr;
@@ -970,17 +978,17 @@ InitCache(cacheDesc *cache, int maxCache
}
ptr = (ptrdiff_t)(cache->certCacheData + cache->numCertCacheEntries);
ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
cache->keyCacheData = (SSLWrappedSymWrappingKey *)ptr;
cache->certCacheSize =
(char *)cache->keyCacheData - (char *)cache->certCacheData;
- cache->numKeyCacheEntries = SSL_NUM_WRAP_KEYS * SSL_NUM_WRAP_MECHS;
+ cache->numKeyCacheEntries = ssl_auth_size * SSL_NUM_WRAP_MECHS;
ptr = (ptrdiff_t)(cache->keyCacheData + cache->numKeyCacheEntries);
ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
cache->keyCacheSize = (char *)ptr - (char *)cache->keyCacheData;
cache->ticketKeyNameSuffix = (PRUint8 *)ptr;
ptr = (ptrdiff_t)(cache->ticketKeyNameSuffix +
SESS_TICKET_KEY_VAR_NAME_LEN);
@@ -1595,312 +1603,97 @@ StopLockPoller(cacheDesc *cache)
return SECSuccess;
}
#endif
/************************************************************************
* Code dealing with shared wrapped symmetric wrapping keys below *
************************************************************************/
-/* The asymmetric key we use for wrapping the symmetric ticket keys. This is a
- * global structure that can be initialized without a socket. Access is
- * synchronized on the reader-writer lock. This is setup either by calling
- * SSL_SetSessionTicketKeyPair() or by configuring a certificate of the
- * ssl_auth_rsa_decrypt type. */
-static struct {
- PRCallOnceType setup;
- PRRWLock *lock;
- SECKEYPublicKey *pubKey;
- SECKEYPrivateKey *privKey;
- PRBool configured;
-} ssl_session_ticket_key_pair;
-
-/* The symmetric ticket keys. This requires a socket to construct and requires
- * that the global structure be initialized before use. */
-static struct {
- PRCallOnceType setup;
- unsigned char keyName[SESS_TICKET_KEY_NAME_LEN];
- PK11SymKey *encKey;
- PK11SymKey *macKey;
-} ssl_session_ticket_keys;
-
-static void
-ssl_CleanupSessionTicketKeyPair()
-{
- if (ssl_session_ticket_key_pair.pubKey) {
- PORT_Assert(ssl_session_ticket_key_pair.privKey);
- SECKEY_DestroyPublicKey(ssl_session_ticket_key_pair.pubKey);
- SECKEY_DestroyPrivateKey(ssl_session_ticket_key_pair.privKey);
- }
-}
-
-void
-ssl_ResetSessionTicketKeys()
-{
- if (ssl_session_ticket_keys.encKey) {
- PORT_Assert(ssl_session_ticket_keys.macKey);
- PK11_FreeSymKey(ssl_session_ticket_keys.encKey);
- PK11_FreeSymKey(ssl_session_ticket_keys.macKey);
- }
- PORT_Memset(&ssl_session_ticket_keys, 0,
- sizeof(ssl_session_ticket_keys));
-}
-
-static SECStatus
-ssl_SessionTicketShutdown(void *appData, void *nssData)
-{
- ssl_CleanupSessionTicketKeyPair();
- PR_DestroyRWLock(ssl_session_ticket_key_pair.lock);
- PORT_Memset(&ssl_session_ticket_key_pair, 0,
- sizeof(ssl_session_ticket_key_pair));
-
- ssl_ResetSessionTicketKeys();
- return SECSuccess;
-}
-
-static PRStatus
-ssl_SessionTicketSetup(void)
-{
- SECStatus rv = NSS_RegisterShutdown(ssl_SessionTicketShutdown, NULL);
- if (rv != SECSuccess) {
- return PR_FAILURE;
- }
- ssl_session_ticket_key_pair.lock = PR_NewRWLock(PR_RWLOCK_RANK_NONE, NULL);
- if (!ssl_session_ticket_key_pair.lock) {
- return PR_FAILURE;
- }
- return PR_SUCCESS;
-}
-
-/* Configure a session ticket key pair. |explicitConfig| is set to true for
- * calls to SSL_SetSessionTicketKeyPair(), false for implicit configuration.
- * This assumes that the setup has been run. */
-static SECStatus
-ssl_SetSessionTicketKeyPair(SECKEYPublicKey *pubKey,
- SECKEYPrivateKey *privKey,
- PRBool explicitConfig)
-{
- SECKEYPublicKey *pubKeyCopy;
- SECKEYPrivateKey *privKeyCopy;
-
- PORT_Assert(ssl_session_ticket_key_pair.lock);
-
- pubKeyCopy = SECKEY_CopyPublicKey(pubKey);
- if (!pubKeyCopy) {
- PORT_SetError(SEC_ERROR_NO_MEMORY);
- return SECFailure;
- }
-
- privKeyCopy = SECKEY_CopyPrivateKey(privKey);
- if (!privKeyCopy) {
- SECKEY_DestroyPublicKey(pubKeyCopy);
- PORT_SetError(SEC_ERROR_NO_MEMORY);
- return SECFailure;
- }
-
- PR_RWLock_Wlock(ssl_session_ticket_key_pair.lock);
- ssl_CleanupSessionTicketKeyPair();
- ssl_session_ticket_key_pair.pubKey = pubKeyCopy;
- ssl_session_ticket_key_pair.privKey = privKeyCopy;
- ssl_session_ticket_key_pair.configured = explicitConfig;
- PR_RWLock_Unlock(ssl_session_ticket_key_pair.lock);
- return SECSuccess;
-}
-
-SECStatus
-SSL_SetSessionTicketKeyPair(SECKEYPublicKey *pubKey,
- SECKEYPrivateKey *privKey)
-{
- if (SECKEY_GetPublicKeyType(pubKey) != rsaKey ||
- SECKEY_GetPrivateKeyType(privKey) != rsaKey) {
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
- return SECFailure;
- }
-
- if (PR_SUCCESS != PR_CallOnce(&ssl_session_ticket_key_pair.setup,
- &ssl_SessionTicketSetup)) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
- }
-
- return ssl_SetSessionTicketKeyPair(pubKey, privKey, PR_TRUE);
-}
-
-/* When configuring a server cert, we should save the RSA key in case it is
- * needed for ticket encryption. This saves the latest copy, unless there has
- * been an explicit call to SSL_SetSessionTicketKeyPair(). */
-SECStatus
-ssl_MaybeSetSessionTicketKeyPair(const sslKeyPair *keyPair)
-{
- PRBool configured;
-
- if (PR_SUCCESS != PR_CallOnce(&ssl_session_ticket_key_pair.setup,
- &ssl_SessionTicketSetup)) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
- }
-
- PR_RWLock_Rlock(ssl_session_ticket_key_pair.lock);
- configured = ssl_session_ticket_key_pair.configured;
- PR_RWLock_Unlock(ssl_session_ticket_key_pair.lock);
- if (configured) {
- return SECSuccess;
- }
- return ssl_SetSessionTicketKeyPair(keyPair->pubKey,
- keyPair->privKey, PR_FALSE);
-}
-
-static SECStatus
-ssl_GetSessionTicketKeyPair(SECKEYPublicKey **pubKey,
- SECKEYPrivateKey **privKey)
-{
- if (PR_SUCCESS != PR_CallOnce(&ssl_session_ticket_key_pair.setup,
- &ssl_SessionTicketSetup)) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
- }
-
- PR_RWLock_Rlock(ssl_session_ticket_key_pair.lock);
- *pubKey = ssl_session_ticket_key_pair.pubKey;
- *privKey = ssl_session_ticket_key_pair.privKey;
- PR_RWLock_Unlock(ssl_session_ticket_key_pair.lock);
- if (!*pubKey) {
- PORT_Assert(!*privKey);
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
- }
- PORT_Assert(*privKey);
- return SECSuccess;
-}
-
+/* If now is zero, it implies that the lock is not held, and must be
+** aquired here.
+*/
static PRBool
-ssl_GenerateSessionTicketKeys(void *pwArg, unsigned char *keyName,
- PK11SymKey **aesKey, PK11SymKey **macKey);
-
-static PRStatus
-ssl_GenerateSessionTicketKeysOnce(void *arg)
-{
- SECStatus rv;
-
- /* Get a copy of the session keys from shared memory. */
- PORT_Memcpy(ssl_session_ticket_keys.keyName,
- SESS_TICKET_KEY_NAME_PREFIX,
- sizeof(SESS_TICKET_KEY_NAME_PREFIX));
- /* This function calls ssl_GetSessionTicketKeyPair(), which initializes the
- * key pair stuff. That allows this to use the same shutdown function. */
- rv = ssl_GenerateSessionTicketKeys(arg, ssl_session_ticket_keys.keyName,
- &ssl_session_ticket_keys.encKey,
- &ssl_session_ticket_keys.macKey);
- if (rv != SECSuccess) {
- return PR_FAILURE;
- }
-
- return PR_SUCCESS;
-}
-
-SECStatus
-ssl_GetSessionTicketKeys(sslSocket *ss, unsigned char *keyName,
- PK11SymKey **encKey, PK11SymKey **macKey)
-{
- if (PR_SUCCESS != PR_CallOnceWithArg(&ssl_session_ticket_keys.setup,
- &ssl_GenerateSessionTicketKeysOnce,
- ss->pkcs11PinArg)) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
- }
-
- if (!ssl_session_ticket_keys.encKey || !ssl_session_ticket_keys.macKey) {
- return SECFailure;
- }
-
- PORT_Memcpy(keyName, ssl_session_ticket_keys.keyName,
- sizeof(ssl_session_ticket_keys.keyName));
- *encKey = ssl_session_ticket_keys.encKey;
- *macKey = ssl_session_ticket_keys.macKey;
- return SECSuccess;
-}
-
-/* If lockTime is zero, it implies that the lock is not held, and must be
- * aquired here.
- */
-static SECStatus
-getSvrWrappingKey(unsigned int symWrapMechIndex,
- unsigned int wrapKeyIndex,
+getSvrWrappingKey(PRInt32 symWrapMechIndex,
+ SSLAuthType authType,
SSLWrappedSymWrappingKey *wswk,
cacheDesc *cache,
PRUint32 lockTime)
{
- PRUint32 ndx = (wrapKeyIndex * SSL_NUM_WRAP_MECHS) + symWrapMechIndex;
+ PRUint32 ndx = (authType * SSL_NUM_WRAP_MECHS) + symWrapMechIndex;
SSLWrappedSymWrappingKey *pwswk = cache->keyCacheData + ndx;
PRUint32 now = 0;
- PRBool rv = SECFailure;
+ PRBool rv = PR_FALSE;
if (!cache->cacheMem) { /* cache is uninitialized */
PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED);
- return SECFailure;
+ return rv;
}
if (!lockTime) {
- now = LockSidCacheLock(cache->keyCacheLock, 0);
- if (!now) {
- return SECFailure;
+ lockTime = now = LockSidCacheLock(cache->keyCacheLock, now);
+ if (!lockTime) {
+ return rv;
}
}
- if (pwswk->wrapKeyIndex == wrapKeyIndex &&
- pwswk->wrapMechIndex == symWrapMechIndex &&
+ if (pwswk->authType == authType &&
+ pwswk->symWrapMechIndex == symWrapMechIndex &&
pwswk->wrappedSymKeyLen != 0) {
*wswk = *pwswk;
- rv = SECSuccess;
+ rv = PR_TRUE;
}
if (now) {
UnlockSidCacheLock(cache->keyCacheLock);
}
return rv;
}
-SECStatus
-ssl_GetWrappingKey(unsigned int wrapMechIndex,
- unsigned int wrapKeyIndex,
+PRBool
+ssl_GetWrappingKey(PRInt32 symWrapMechIndex,
+ SSLAuthType authType,
SSLWrappedSymWrappingKey *wswk)
{
- PORT_Assert(wrapMechIndex < SSL_NUM_WRAP_MECHS);
- PORT_Assert(wrapKeyIndex < SSL_NUM_WRAP_KEYS);
- if (wrapMechIndex >= SSL_NUM_WRAP_MECHS ||
- wrapKeyIndex >= SSL_NUM_WRAP_KEYS) {
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
- return SECFailure;
+ PRBool rv;
+
+ PORT_Assert((unsigned)authType < ssl_auth_size);
+ PORT_Assert((unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS);
+ if ((unsigned)authType < ssl_auth_size &&
+ (unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS) {
+ rv = getSvrWrappingKey(symWrapMechIndex, authType, wswk,
+ &globalCache, 0);
+ } else {
+ rv = PR_FALSE;
}
- return getSvrWrappingKey(wrapMechIndex, wrapKeyIndex, wswk,
- &globalCache, 0);
+ return rv;
}
/* Wrap and cache a session ticket key. */
-static SECStatus
+static PRBool
WrapTicketKey(SECKEYPublicKey *svrPubKey, PK11SymKey *symKey,
const char *keyName, encKeyCacheEntry *cacheEntry)
{
SECItem wrappedKey = { siBuffer, NULL, 0 };
wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
PORT_Assert(wrappedKey.len <= sizeof(cacheEntry->bytes));
if (wrappedKey.len > sizeof(cacheEntry->bytes))
return PR_FALSE;
wrappedKey.data = cacheEntry->bytes;
if (PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, symKey, &wrappedKey) !=
SECSuccess) {
SSL_DBG(("%d: SSL[%s]: Unable to wrap session ticket %s.",
SSL_GETPID(), "unknown", keyName));
- return SECFailure;
+ return PR_FALSE;
}
cacheEntry->length = wrappedKey.len;
- return SECSuccess;
+ return PR_TRUE;
}
-static SECStatus
+static PRBool
GenerateTicketKeys(void *pwArg, unsigned char *keyName, PK11SymKey **aesKey,
PK11SymKey **macKey)
{
PK11SlotInfo *slot;
CK_MECHANISM_TYPE mechanismArray[2];
PK11SymKey *aesKeyTmp = NULL;
PK11SymKey *macKeyTmp = NULL;
cacheDesc *cache = &globalCache;
@@ -1914,17 +1707,17 @@ GenerateTicketKeys(void *pwArg, unsigned
ticketKeyNameSuffix = cache->ticketKeyNameSuffix;
}
if (PK11_GenerateRandom(ticketKeyNameSuffix,
SESS_TICKET_KEY_VAR_NAME_LEN) !=
SECSuccess) {
SSL_DBG(("%d: SSL[%s]: Unable to generate random key name bytes.",
SSL_GETPID(), "unknown"));
- return SECFailure;
+ goto loser;
}
mechanismArray[0] = CKM_AES_CBC;
mechanismArray[1] = CKM_SHA256_HMAC;
slot = PK11_GetBestSlotMultiple(mechanismArray, 2, pwArg);
if (slot) {
aesKeyTmp = PK11_KeyGen(slot, mechanismArray[0], NULL,
@@ -1937,63 +1730,59 @@ GenerateTicketKeys(void *pwArg, unsigned
if (aesKeyTmp == NULL || macKeyTmp == NULL) {
SSL_DBG(("%d: SSL[%s]: Unable to generate session ticket keys.",
SSL_GETPID(), "unknown"));
goto loser;
}
PORT_Memcpy(keyName, ticketKeyNameSuffix, SESS_TICKET_KEY_VAR_NAME_LEN);
*aesKey = aesKeyTmp;
*macKey = macKeyTmp;
- return SECSuccess;
+ return PR_TRUE;
loser:
if (aesKeyTmp)
PK11_FreeSymKey(aesKeyTmp);
if (macKeyTmp)
PK11_FreeSymKey(macKeyTmp);
- return SECFailure;
+ return PR_FALSE;
}
-static SECStatus
+static PRBool
GenerateAndWrapTicketKeys(SECKEYPublicKey *svrPubKey, void *pwArg,
unsigned char *keyName, PK11SymKey **aesKey,
PK11SymKey **macKey)
{
PK11SymKey *aesKeyTmp = NULL;
PK11SymKey *macKeyTmp = NULL;
cacheDesc *cache = &globalCache;
- SECStatus rv;
- rv = GenerateTicketKeys(pwArg, keyName, &aesKeyTmp, &macKeyTmp);
- if (rv != SECSuccess) {
- return SECFailure;
+ if (!GenerateTicketKeys(pwArg, keyName, &aesKeyTmp, &macKeyTmp)) {
+ goto loser;
}
if (cache->cacheMem) {
/* Export the keys to the shared cache in wrapped form. */
- rv = WrapTicketKey(svrPubKey, aesKeyTmp, "enc key", cache->ticketEncKey);
- if (rv != SECSuccess) {
+ if (!WrapTicketKey(svrPubKey, aesKeyTmp, "enc key", cache->ticketEncKey))
goto loser;
- }
- rv = WrapTicketKey(svrPubKey, macKeyTmp, "mac key", cache->ticketMacKey);
- if (rv != SECSuccess) {
+ if (!WrapTicketKey(svrPubKey, macKeyTmp, "mac key", cache->ticketMacKey))
goto loser;
- }
}
*aesKey = aesKeyTmp;
*macKey = macKeyTmp;
- return SECSuccess;
+ return PR_TRUE;
loser:
- PK11_FreeSymKey(aesKeyTmp);
- PK11_FreeSymKey(macKeyTmp);
- return SECFailure;
+ if (aesKeyTmp)
+ PK11_FreeSymKey(aesKeyTmp);
+ if (macKeyTmp)
+ PK11_FreeSymKey(macKeyTmp);
+ return PR_FALSE;
}
-static SECStatus
+static PRBool
UnwrapCachedTicketKeys(SECKEYPrivateKey *svrPrivKey, unsigned char *keyName,
PK11SymKey **aesKey, PK11SymKey **macKey)
{
SECItem wrappedKey = { siBuffer, NULL, 0 };
PK11SymKey *aesKeyTmp = NULL;
PK11SymKey *macKeyTmp = NULL;
cacheDesc *cache = &globalCache;
@@ -2016,109 +1805,115 @@ UnwrapCachedTicketKeys(SECKEYPrivateKey
}
SSL_DBG(("%d: SSL[%s]: Successfully unwrapped session ticket keys.",
SSL_GETPID(), "unknown"));
PORT_Memcpy(keyName, cache->ticketKeyNameSuffix,
SESS_TICKET_KEY_VAR_NAME_LEN);
*aesKey = aesKeyTmp;
*macKey = macKeyTmp;
- return SECSuccess;
+ return PR_TRUE;
loser:
if (aesKeyTmp)
PK11_FreeSymKey(aesKeyTmp);
if (macKeyTmp)
PK11_FreeSymKey(macKeyTmp);
- return SECFailure;
+ return PR_FALSE;
}
-static SECStatus
-ssl_GenerateSessionTicketKeys(void *pwArg, unsigned char *keyName,
- PK11SymKey **encKey, PK11SymKey **macKey)
+PRBool
+ssl_GetSessionTicketKeys(SECKEYPrivateKey *svrPrivKey,
+ SECKEYPublicKey *svrPubKey, void *pwArg,
+ unsigned char *keyName, PK11SymKey **aesKey,
+ PK11SymKey **macKey)
{
- SECKEYPrivateKey *svrPrivKey;
- SECKEYPublicKey *svrPubKey;
- PRUint32 now;
- SECStatus rv;
+ PRUint32 now = 0;
+ PRBool rv = PR_FALSE;
+ PRBool keysGenerated = PR_FALSE;
cacheDesc *cache = &globalCache;
- rv = ssl_GetSessionTicketKeyPair(&svrPubKey, &svrPrivKey);
- if (rv != SECSuccess || !cache->cacheMem) {
- /* No key pair for wrapping, or the cache is uninitialized. Generate
- * keys and return them without caching. */
- return GenerateTicketKeys(pwArg, keyName, encKey, macKey);
+ if (!cache->cacheMem) {
+ /* cache is uninitialized. Generate keys and return them
+ * without caching. */
+ return GenerateTicketKeys(pwArg, keyName, aesKey, macKey);
}
- now = LockSidCacheLock(cache->keyCacheLock, 0);
+ now = LockSidCacheLock(cache->keyCacheLock, now);
if (!now)
- return SECFailure;
+ return rv;
- if (*(cache->ticketKeysValid)) {
- rv = UnwrapCachedTicketKeys(svrPrivKey, keyName, encKey, macKey);
- } else {
+ if (!*(cache->ticketKeysValid)) {
/* Keys do not exist, create them. */
- rv = GenerateAndWrapTicketKeys(svrPubKey, pwArg, keyName,
- encKey, macKey);
- if (rv == SECSuccess) {
- *(cache->ticketKeysValid) = 1;
- }
+ if (!GenerateAndWrapTicketKeys(svrPubKey, pwArg, keyName,
+ aesKey, macKey))
+ goto loser;
+ keysGenerated = PR_TRUE;
+ *(cache->ticketKeysValid) = 1;
}
+
+ rv = PR_TRUE;
+
+loser:
UnlockSidCacheLock(cache->keyCacheLock);
+ if (rv && !keysGenerated)
+ rv = UnwrapCachedTicketKeys(svrPrivKey, keyName, aesKey, macKey);
return rv;
}
/* The caller passes in the new value it wants
* to set. This code tests the wrapped sym key entry in the shared memory.
* If it is uninitialized, this function writes the caller's value into
* the disk entry, and returns false.
* Otherwise, it overwrites the caller's wswk with the value obtained from
* the disk, and returns PR_TRUE.
* This is all done while holding the locks/mutexes necessary to make
* the operation atomic.
*/
-SECStatus
+PRBool
ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk)
{
cacheDesc *cache = &globalCache;
- PRBool rv = SECFailure;
+ PRBool rv = PR_FALSE;
+ SSLAuthType authType = wswk->authType;
+ /* type of keys used to wrap SymWrapKey*/
+ PRInt32 symWrapMechIndex = wswk->symWrapMechIndex;
PRUint32 ndx;
- PRUint32 now;
+ PRUint32 now = 0;
SSLWrappedSymWrappingKey myWswk;
if (!cache->cacheMem) { /* cache is uninitialized */
PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED);
- return SECFailure;
+ return 0;
}
- PORT_Assert(wswk->wrapMechIndex < SSL_NUM_WRAP_MECHS);
- PORT_Assert(wswk->wrapKeyIndex < SSL_NUM_WRAP_KEYS);
- if (wswk->wrapMechIndex >= SSL_NUM_WRAP_MECHS ||
- wswk->wrapKeyIndex >= SSL_NUM_WRAP_KEYS) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
- }
+ PORT_Assert((unsigned)authType < ssl_auth_size);
+ if ((unsigned)authType >= ssl_auth_size)
+ return 0;
- ndx = (wswk->wrapKeyIndex * SSL_NUM_WRAP_MECHS) + wswk->wrapMechIndex;
+ PORT_Assert((unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS);
+ if ((unsigned)symWrapMechIndex >= SSL_NUM_WRAP_MECHS)
+ return 0;
+
+ ndx = (authType * SSL_NUM_WRAP_MECHS) + symWrapMechIndex;
PORT_Memset(&myWswk, 0, sizeof myWswk); /* eliminate UMRs. */
- now = LockSidCacheLock(cache->keyCacheLock, 0);
- if (!now) {
- return SECFailure;
+ now = LockSidCacheLock(cache->keyCacheLock, now);
+ if (now) {
+ rv = getSvrWrappingKey(wswk->symWrapMechIndex, wswk->authType,
+ &myWswk, cache, now);
+ if (rv) {
+ /* we found it on disk, copy it out to the caller. */
+ PORT_Memcpy(wswk, &myWswk, sizeof *wswk);
+ } else {
+ /* Wasn't on disk, and we're still holding the lock, so write it. */
+ cache->keyCacheData[ndx] = *wswk;
+ }
+ UnlockSidCacheLock(cache->keyCacheLock);
}
- rv = getSvrWrappingKey(wswk->wrapMechIndex, wswk->wrapKeyIndex,
- &myWswk, cache, now);
- if (rv == SECSuccess) {
- /* we found it on disk, copy it out to the caller. */
- PORT_Memcpy(wswk, &myWswk, sizeof *wswk);
- } else {
- /* Wasn't on disk, and we're still holding the lock, so write it. */
- cache->keyCacheData[ndx] = *wswk;
- }
- UnlockSidCacheLock(cache->keyCacheLock);
return rv;
}
#else /* MAC version or other platform */
#include "seccomon.h"
#include "cert.h"
#include "ssl.h"
@@ -2146,39 +1941,41 @@ SSL_ConfigMPServerSIDCache(int maxCacheE
SECStatus
SSL_InheritMPServerSIDCache(const char *envString)
{
PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_InheritMPServerSIDCache)");
return SECFailure;
}
-SECStatus
-ssl_GetWrappingKey(unsigned int wrapMechIndex,
- unsigned int wrapKeyIndex,
+PRBool
+ssl_GetWrappingKey(PRInt32 symWrapMechIndex,
+ SSLAuthType authType,
SSLWrappedSymWrappingKey *wswk)
{
+ PRBool rv = PR_FALSE;
PR_ASSERT(!"SSL servers are not supported on this platform. (ssl_GetWrappingKey)");
- return SECFailure;
+ return rv;
}
/* This is a kind of test-and-set. The caller passes in the new value it wants
* to set. This code tests the wrapped sym key entry in the shared memory.
* If it is uninitialized, this function writes the caller's value into
* the disk entry, and returns false.
* Otherwise, it overwrites the caller's wswk with the value obtained from
* the disk, and returns PR_TRUE.
* This is all done while holding the locks/mutexes necessary to make
* the operation atomic.
*/
-SECStatus
+PRBool
ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk)
{
+ PRBool rv = PR_FALSE;
PR_ASSERT(!"SSL servers are not supported on this platform. (ssl_SetWrappingKey)");
- return SECFailure;
+ return rv;
}
PRUint32
SSL_GetMaxServerCacheLocks(void)
{
PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_GetMaxServerCacheLocks)");
return -1;
}
--- a/security/nss/lib/ssl/sslt.h
+++ b/security/nss/lib/ssl/sslt.h
@@ -293,22 +293,16 @@ typedef struct SSLPreliminaryChannelInfo
/* A bitfield over SSLPreliminaryValueSet that describes which
* preliminary values are set (see ssl_preinfo_*). */
PRUint32 valuesSet;
/* Protocol version: test (valuesSet & ssl_preinfo_version) */
PRUint16 protocolVersion;
/* Cipher suite: test (valuesSet & ssl_preinfo_cipher_suite) */
PRUint16 cipherSuite;
- /* The following fields were added in NSS 3.29. */
- /* |canSendEarlyData| is true when a 0-RTT is enabled. This can only be
- * true after sending the ClientHello and before the handshake completes.
- */
- PRBool canSendEarlyData;
-
/* When adding new fields to this structure, please document the
* NSS version in which they were added. */
} SSLPreliminaryChannelInfo;
typedef struct SSLCipherSuiteInfoStr {
/* On return, SSL_GetCipherSuitelInfo sets |length| to the smaller of
* the |len| argument and the length of the struct used by NSS.
* Callers must ensure the application uses a version of NSS that
--- a/security/nss/lib/ssl/tls13con.c
+++ b/security/nss/lib/ssl/tls13con.c
@@ -127,17 +127,17 @@ const char kHkdfPurposeIv[] = "iv";
const SSL3ProtocolVersion kTlsRecordVersion = SSL_LIBRARY_VERSION_TLS_1_0;
const SSL3ProtocolVersion kDtlsRecordVersion = SSL_LIBRARY_VERSION_TLS_1_1;
/* Belt and suspenders in case we ever add a TLS 1.4. */
PR_STATIC_ASSERT(SSL_LIBRARY_VERSION_MAX_SUPPORTED <=
SSL_LIBRARY_VERSION_TLS_1_3);
-/* Use this instead of FATAL_ERROR when no alert shall be sent. */
+/* Use this instead of FATAL_ERROR when an alert isn't possible. */
#define LOG_ERROR(ss, prError) \
do { \
SSL_TRC(3, ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)", \
SSL_GETPID(), ss->fd, prError, __func__, __FILE__, __LINE__)); \
PORT_SetError(prError); \
} while (0)
/* Log an error and generate an alert because something is irreparably wrong. */
@@ -158,31 +158,25 @@ tls13_FatalError(sslSocket *ss, PRErrorC
#ifdef TRACE
#define STATE_CASE(a) \
case a: \
return #a
static char *
tls13_HandshakeState(SSL3WaitState st)
{
switch (st) {
- STATE_CASE(idle_handshake);
STATE_CASE(wait_client_hello);
STATE_CASE(wait_client_cert);
- STATE_CASE(wait_client_key);
STATE_CASE(wait_cert_verify);
- STATE_CASE(wait_change_cipher);
STATE_CASE(wait_finished);
STATE_CASE(wait_server_hello);
- STATE_CASE(wait_certificate_status);
STATE_CASE(wait_server_cert);
- STATE_CASE(wait_server_key);
STATE_CASE(wait_cert_request);
- STATE_CASE(wait_hello_done);
- STATE_CASE(wait_new_session_ticket);
STATE_CASE(wait_encrypted_extensions);
+ STATE_CASE(idle_handshake);
default:
break;
}
PORT_Assert(0);
return "unknown";
}
#endif
@@ -427,17 +421,20 @@ tls13_SetupClientHello(sslSocket *ss)
sid->version < SSL_LIBRARY_VERSION_TLS_1_3) {
return SECSuccess;
}
/* The caller must be holding sid->u.ssl3.lock for reading. */
session_ticket = &sid->u.ssl3.locked.sessionTicket;
PORT_Assert(session_ticket && session_ticket->ticket.data);
- if (ssl_TicketTimeValid(session_ticket)) {
+ if (session_ticket->ticket_lifetime_hint == 0 ||
+ (session_ticket->ticket_lifetime_hint +
+ session_ticket->received_timestamp >
+ ssl_Time())) {
ss->statelessResume = PR_TRUE;
}
if (ss->statelessResume) {
SECStatus rv;
PORT_Assert(ss->sec.ci.sid);
rv = tls13_RecoverWrappedSharedSecret(ss, ss->sec.ci.sid);
@@ -623,19 +620,23 @@ tls13_RecoverWrappedSharedSecret(sslSock
PORT_Assert(0); /* I think this can't happen. */
return SECFailure;
}
/* Now find the hash used as the PRF for the previous handshake. */
hashType = tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite);
/* If we are the server, we compute the wrapping key, but if we
- * are the client, its coordinates are stored with the ticket. */
+ * are the client, it's coordinates are stored with the ticket. */
if (ss->sec.isServer) {
- wrapKey = ssl3_GetWrappingKey(ss, NULL,
+ const sslServerCert *serverCert;
+
+ serverCert = ssl_FindServerCert(ss, &sid->certType);
+ PORT_Assert(serverCert);
+ wrapKey = ssl3_GetWrappingKey(ss, NULL, serverCert,
sid->u.ssl3.masterWrapMech,
ss->pkcs11PinArg);
} else {
PK11SlotInfo *slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
sid->u.ssl3.masterSlotID);
if (!slot)
return SECFailure;
@@ -928,17 +929,17 @@ tls13_CanResume(sslSocket *ss, const ssl
if (tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite) != tls13_GetHashForCipherSuite(ss->ssl3.hs.cipher_suite)) {
return PR_FALSE;
}
/* Server sids don't remember the server cert we previously sent, but they
* do remember the type of certificate we originally used, so we can locate
* it again, provided that the current ssl socket has had its server certs
* configured the same as the previous one. */
- sc = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
+ sc = ssl_FindServerCert(ss, &sid->certType);
if (!sc || !sc->serverCert) {
return PR_FALSE;
}
return PR_TRUE;
}
static PRBool
@@ -1152,40 +1153,16 @@ tls13_NegotiateKeyExchange(sslSocket *ss
}
PORT_Assert(preferredGroup == entry->group);
*clientShare = entry;
return SECSuccess;
}
-SSLAuthType
-ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme)
-{
- switch (scheme) {
- case ssl_sig_rsa_pkcs1_sha1:
- case ssl_sig_rsa_pkcs1_sha256:
- case ssl_sig_rsa_pkcs1_sha384:
- case ssl_sig_rsa_pkcs1_sha512:
- /* We report PSS signatures as being just RSA signatures. */
- case ssl_sig_rsa_pss_sha256:
- case ssl_sig_rsa_pss_sha384:
- case ssl_sig_rsa_pss_sha512:
- return ssl_auth_rsa_sign;
- case ssl_sig_ecdsa_secp256r1_sha256:
- case ssl_sig_ecdsa_secp384r1_sha384:
- case ssl_sig_ecdsa_secp521r1_sha512:
- case ssl_sig_ecdsa_sha1:
- return ssl_auth_ecdsa;
- default:
- PORT_Assert(0);
- }
- return ssl_auth_null;
-}
-
SECStatus
tls13_SelectServerCert(sslSocket *ss)
{
PRCList *cursor;
SECStatus rv;
if (!ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
FATAL_ERROR(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION,
@@ -1199,31 +1176,32 @@ tls13_SelectServerCert(sslSocket *ss)
*
* We might want to do some sort of ranking here later. For now, it's all
* based on what order they are configured in. */
for (cursor = PR_NEXT_LINK(&ss->serverCerts);
cursor != &ss->serverCerts;
cursor = PR_NEXT_LINK(cursor)) {
sslServerCert *cert = (sslServerCert *)cursor;
- if (SSL_CERT_IS_ONLY(cert, ssl_auth_rsa_decrypt)) {
+ if (cert->certType.authType == ssl_auth_rsa_pss ||
+ cert->certType.authType == ssl_auth_rsa_decrypt) {
continue;
}
rv = ssl_PickSignatureScheme(ss,
cert->serverKeyPair->pubKey,
cert->serverKeyPair->privKey,
ss->xtnData.clientSigSchemes,
ss->xtnData.numClientSigScheme,
PR_FALSE);
if (rv == SECSuccess) {
/* Found one. */
ss->sec.serverCert = cert;
- ss->sec.authType = ss->ssl3.hs.kea_def_mutable.authKeyType =
- ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
+ ss->sec.authType = cert->certType.authType;
+ ss->ssl3.hs.kea_def_mutable.authKeyType = cert->certType.authType;
ss->sec.authKeyBits = cert->serverKeyBits;
return SECSuccess;
}
}
FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM,
handshake_failure);
return SECFailure;
@@ -1244,16 +1222,18 @@ tls13_NegotiateAuthentication(sslSocket
SSL_TRC(3, ("%d: TLS13[%d]: selected certificate authentication",
SSL_GETPID(), ss->fd));
/* We've now established that we need to sign.... */
rv = tls13_SelectServerCert(ss);
if (rv != SECSuccess) {
return SECFailure;
}
+ ss->ssl3.hs.kea_def_mutable.authKeyType =
+ ss->sec.serverCert->certType.authType;
return SECSuccess;
}
/* Called from ssl3_HandleClientHello after we have parsed the
* ClientHello and are sure that we are going to do TLS 1.3
* or fail. */
SECStatus
tls13_HandleClientHelloPart2(sslSocket *ss,
@@ -1355,33 +1335,30 @@ tls13_HandleClientHelloPart2(sslSocket *
/* Check that the negotiated SNI and the cached SNI match. */
if (SECITEM_CompareItem(&sid->u.ssl3.srvName,
&ss->ssl3.hs.srvVirtName) != SECEqual) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO,
handshake_failure);
goto loser;
}
- ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType,
- sid->namedCurve);
- PORT_Assert(ss->sec.serverCert);
-
rv = tls13_RecoverWrappedSharedSecret(ss, sid);
if (rv != SECSuccess) {
SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
goto loser;
}
tls13_RestoreCipherInfo(ss, sid);
+ ss->sec.serverCert = ssl_FindServerCert(ss, &sid->certType);
+ PORT_Assert(ss->sec.serverCert);
ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
if (sid->peerCert != NULL) {
ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
}
-
ssl3_RegisterExtensionSender(
ss, &ss->xtnData,
ssl_tls13_pre_shared_key_xtn, tls13_ServerSendPreSharedKeyXtn);
tls13_NegotiateZeroRtt(ss, sid);
} else {
if (sid) { /* we had a sid, but it's no longer valid, free it */
SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
@@ -1632,38 +1609,35 @@ tls13_HandleClientKeyShare(sslSocket *ss
* DistinguishedName certificate_authorities<0..2^16-1>;
* CertificateExtension certificate_extensions<0..2^16-1>;
* } CertificateRequest;
*/
static SECStatus
tls13_SendCertificateRequest(sslSocket *ss)
{
SECStatus rv;
- unsigned int calen;
+ int calen;
SECItem *names;
- unsigned int nnames;
+ int nnames;
SECItem *name;
int i;
PRUint8 sigSchemes[MAX_SIGNATURE_SCHEMES * 2];
unsigned int sigSchemesLength = 0;
int length;
SSL_TRC(3, ("%d: TLS13[%d]: begin send certificate_request",
SSL_GETPID(), ss->fd));
rv = ssl3_EncodeSigAlgs(ss, sigSchemes, sizeof(sigSchemes),
&sigSchemesLength);
if (rv != SECSuccess) {
return rv;
}
- rv = ssl_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
- if (rv != SECSuccess) {
- return rv;
- }
+ ssl3_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
length = 1 + 0 /* length byte for empty request context */ +
2 + sigSchemesLength + 2 + calen + 2;
rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length);
if (rv != SECSuccess) {
return rv; /* err set by AppendHandshake. */
}
rv = ssl3_AppendHandshakeNumber(ss, 0, 1);
@@ -1691,17 +1665,17 @@ tls13_SendCertificateRequest(sslSocket *
return SECSuccess;
}
SECStatus
tls13_HandleHelloRetryRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
{
SECStatus rv;
- PRUint32 tmp;
+ PRInt32 tmp;
SSL3ProtocolVersion version;
SSL_TRC(3, ("%d: TLS13[%d]: handle hello retry request",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
@@ -1740,18 +1714,18 @@ tls13_HandleHelloRetryRequest(sslSocket
}
if (version > ss->vrange.max || version < SSL_LIBRARY_VERSION_TLS_1_3) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST,
protocol_version);
return SECFailure;
}
/* Extensions. */
- rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, &b, &length);
- if (rv != SECSuccess) {
+ tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
+ if (tmp < 0) {
return SECFailure; /* error code already set */
}
/* Extensions must be non-empty and use the remainder of the message.
* This means that a HelloRetryRequest cannot be a no-op: we must have an
* extension, it must be one that we understand and recognize as being valid
* for HelloRetryRequest, and all the extensions we permit cause us to
* modify our ClientHello in some way. */
if (!tmp || tmp != length) {
@@ -1779,17 +1753,17 @@ tls13_HandleHelloRetryRequest(sslSocket
static SECStatus
tls13_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
{
SECStatus rv;
TLS13CertificateRequest *certRequest = NULL;
SECItem context = { siBuffer, NULL, 0 };
PLArenaPool *arena;
- PRUint32 extensionsLength;
+ PRInt32 extensionsLength;
SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_request sequence",
SSL_GETPID(), ss->fd));
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
/* Client */
@@ -1826,30 +1800,30 @@ tls13_HandleCertificateRequest(sslSocket
goto loser;
certRequest->arena = arena;
certRequest->ca_list.arena = arena;
rv = ssl_ParseSignatureSchemes(ss, arena,
&certRequest->signatureSchemes,
&certRequest->signatureSchemeCount,
&b, &length);
- if (rv != SECSuccess || certRequest->signatureSchemeCount == 0) {
+ if (rv != SECSuccess) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST,
decode_error);
goto loser;
}
rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, arena,
&certRequest->ca_list);
if (rv != SECSuccess)
goto loser; /* alert already sent */
/* Verify that the extensions length is correct. */
- rv = ssl3_ConsumeHandshakeNumber(ss, &extensionsLength, 2, &b, &length);
- if (rv != SECSuccess) {
+ extensionsLength = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
+ if (extensionsLength < 0) {
goto loser; /* alert already sent */
}
if (extensionsLength != length) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST,
illegal_parameter);
goto loser;
}
@@ -2802,20 +2776,16 @@ tls13_SetCipherSpec(sslSocket *ss, Traff
*specp = spec; /* Overwrite. */
ssl_ReleaseSpecWriteLock(ss);
SSL_TRC(3, ("%d: TLS13[%d]: %s installed key for phase='%s'.%d dir=%s",
SSL_GETPID(), ss->fd, SSL_ROLE(ss),
spec->phase, spec->epoch,
direction == CipherSpecRead ? "read" : "write"));
- if (ss->ssl3.changedCipherSpecFunc) {
- ss->ssl3.changedCipherSpecFunc(ss->ssl3.changedCipherSpecArg,
- direction == CipherSpecWrite, spec);
- }
return SECSuccess;
}
static SECStatus
tls13_ComputeHandshakeHashes(sslSocket *ss,
SSL3Hashes *hashes)
{
SECStatus rv;
@@ -2951,17 +2921,16 @@ tls13_WriteNonce(ssl3KeyMaterial *keys,
PORT_Assert(nonceLen == 12);
memcpy(nonce, keys->write_iv, 12);
/* XOR the last 8 bytes of the IV with the sequence number. */
PORT_Assert(seqNumLen == 8);
for (i = 0; i < 8; ++i) {
nonce[4 + i] ^= seqNumBuf[i];
}
- PRINT_BUF(50, (NULL, "Nonce", nonce, nonceLen));
}
/* Implement the SSLAEADCipher interface defined in sslimpl.h.
*
* That interface takes the additional data (see below) and reinterprets that as
* a sequence number. In TLS 1.3 there is no additional data so this value is
* just the encoded sequence number.
*/
@@ -3041,33 +3010,33 @@ tls13_ChaCha20Poly1305(ssl3KeyMaterial *
CKM_NSS_CHACHA20_POLY1305,
(unsigned char *)&aeadParams, sizeof(aeadParams));
}
static SECStatus
tls13_HandleEncryptedExtensions(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
{
SECStatus rv;
- PRUint32 innerLength;
+ PRInt32 innerLength;
SECItem oldNpn = { siBuffer, NULL, 0 };
PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
SSL_TRC(3, ("%d: TLS13[%d]: handle encrypted extensions",
SSL_GETPID(), ss->fd));
rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS,
wait_encrypted_extensions);
if (rv != SECSuccess) {
return SECFailure;
}
- rv = ssl3_ConsumeHandshakeNumber(ss, &innerLength, 2, &b, &length);
- if (rv != SECSuccess) {
+ innerLength = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
+ if (innerLength < 0) {
return SECFailure; /* Alert already sent. */
}
if (innerLength != length) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
illegal_parameter);
return SECFailure;
}
@@ -3309,17 +3278,26 @@ tls13_HandleCertificateVerify(sslSocket
rv = ssl3_VerifySignedHashes(ss, sigScheme, &tbsHash, &signed_hash);
if (rv != SECSuccess) {
FATAL_ERROR(ss, PORT_GetError(), decrypt_error);
return SECFailure;
}
/* Set the auth type. */
if (!ss->sec.isServer) {
- ss->sec.authType = ssl_SignatureSchemeToAuthType(sigScheme);
+ switch (ssl_SignatureSchemeToKeyType(sigScheme)) {
+ case rsaKey:
+ ss->sec.authType = ssl_auth_rsa_sign;
+ break;
+ case ecKey:
+ ss->sec.authType = ssl_auth_ecdsa;
+ break;
+ default:
+ PORT_Assert(PR_FALSE);
+ }
}
/* Request a client certificate now if one was requested. */
if (ss->ssl3.hs.certificateRequest) {
TLS13CertificateRequest *req = ss->ssl3.hs.certificateRequest;
PORT_Assert(!ss->sec.isServer);
rv = ssl3_CompleteHandleCertificateRequest(ss, req->signatureSchemes,
@@ -3890,16 +3868,17 @@ loser:
}
return SECFailure;
}
static SECStatus
tls13_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
{
SECStatus rv;
+ PRInt32 tmp;
PRUint32 utmp;
NewSessionTicket ticket = { 0 };
SECItem data;
SECItem ticket_data;
SSL_TRC(3, ("%d: TLS13[%d]: handle new session ticket message",
SSL_GETPID(), ss->fd));
@@ -3909,24 +3888,24 @@ tls13_HandleNewSessionTicket(sslSocket *
return SECFailure;
}
if (!ss->firstHsDone || ss->sec.isServer) {
FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET,
unexpected_message);
return SECFailure;
}
- ticket.received_timestamp = PR_Now();
- rv = ssl3_ConsumeHandshakeNumber(ss, &ticket.ticket_lifetime_hint, 4, &b,
- &length);
- if (rv != SECSuccess) {
+ ticket.received_timestamp = ssl_Time();
+ tmp = ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length);
+ if (tmp < 0) {
FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
decode_error);
return SECFailure;
}
+ ticket.ticket_lifetime_hint = (PRUint32)tmp;
ticket.ticket.type = siBuffer;
rv = ssl3_ConsumeHandshake(ss, &utmp, sizeof(utmp),
&b, &length);
if (rv != SECSuccess) {
PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
return SECFailure;
}
@@ -4337,17 +4316,18 @@ tls13_MaybeDo0RTTHandshake(sslSocket *ss
/* Null spec... */
ssl_GetSpecReadLock(ss);
ss->ssl3.hs.nullSpec = ss->ssl3.cwSpec;
tls13_CipherSpecAddRef(ss->ssl3.hs.nullSpec);
ssl_ReleaseSpecReadLock(ss);
/* Cipher suite already set in tls13_SetupClientHello. */
- ss->ssl3.hs.preliminaryInfo = 0;
+ ss->ssl3.hs.preliminaryInfo = 0; /* TODO(ekr@rtfm.com) Fill this in.
+ * bug 1281255. */
rv = tls13_DeriveSecret(ss, ss->ssl3.hs.currentSecret,
kHkdfLabelClient,
kHkdfLabelEarlyTrafficSecret,
NULL,
&ss->ssl3.hs.clientEarlyTrafficSecret);
if (rv != SECSuccess)
return SECFailure;
--- a/security/nss/lib/ssl/tls13exthandle.c
+++ b/security/nss/lib/ssl/tls13exthandle.c
@@ -203,23 +203,23 @@ tls13_ClientSendKeyShareXtn(const sslSoc
loser:
return -1;
}
static SECStatus
tls13_HandleKeyShareEntry(const sslSocket *ss, TLSExtensionData *xtnData, SECItem *data)
{
SECStatus rv;
- PRUint32 group;
+ PRInt32 group;
const sslNamedGroupDef *groupDef;
TLS13KeyShareEntry *ks = NULL;
SECItem share = { siBuffer, NULL, 0 };
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &group, 2, &data->data, &data->len);
- if (rv != SECSuccess) {
+ group = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
+ if (group < 0) {
PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
goto loser;
}
groupDef = ssl_LookupNamedGroup(group);
rv = ssl3_ExtConsumeHandshakeVariable(ss, &share, 2, &data->data,
&data->len);
if (rv != SECSuccess) {
goto loser;
@@ -251,20 +251,21 @@ loser:
* share is processed in tls13_HandleServerKeyShare(). */
SECStatus
tls13_ClientHandleKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, SECItem *data)
{
SECStatus rv;
PORT_Assert(PR_CLIST_IS_EMPTY(&xtnData->remoteKeyShares));
PORT_Assert(!ss->sec.isServer);
-
- /* The server must not send this extension when negotiating < TLS 1.3. */
if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
- PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
+ /* This can't happen because the extension processing
+ * code filters out TLS 1.3 extensions when not in
+ * TLS 1.3 mode. */
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
return SECFailure;
}
SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension",
SSL_GETPID(), ss->fd));
rv = tls13_HandleKeyShareEntry(ss, xtnData, data);
if (rv != SECSuccess) {
@@ -279,27 +280,27 @@ tls13_ClientHandleKeyShareXtn(const sslS
return SECSuccess;
}
SECStatus
tls13_ClientHandleKeyShareXtnHrr(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, SECItem *data)
{
SECStatus rv;
- PRUint32 tmp;
+ PRInt32 tmp;
const sslNamedGroupDef *group;
PORT_Assert(!ss->sec.isServer);
PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension in HRR",
SSL_GETPID(), ss->fd));
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &data->data, &data->len);
- if (rv != SECSuccess) {
+ tmp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
+ if (tmp < 0) {
return SECFailure; /* error code already set */
}
if (data->len) {
ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST);
return SECFailure;
}
@@ -329,33 +330,33 @@ tls13_ClientHandleKeyShareXtnHrr(const s
/* Handle an incoming KeyShare extension at the server and copy to
* |xtnData->remoteKeyShares| for future use. The key
* share is processed in tls13_HandleClientKeyShare(). */
SECStatus
tls13_ServerHandleKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, SECItem *data)
{
SECStatus rv;
- PRUint32 length;
+ PRInt32 length;
PORT_Assert(ss->sec.isServer);
PORT_Assert(PR_CLIST_IS_EMPTY(&xtnData->remoteKeyShares));
if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
return SECSuccess;
}
SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension",
SSL_GETPID(), ss->fd));
/* Redundant length because of TLS encoding (this vector consumes
* the entire extension.) */
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &length, 2, &data->data,
- &data->len);
- if (rv != SECSuccess)
+ length = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data,
+ &data->len);
+ if (length < 0)
goto loser;
if (length != data->len) {
/* Check for consistency */
PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
goto loser;
}
while (data->len) {
@@ -481,17 +482,17 @@ tls13_ClientSendPreSharedKeyXtn(const ss
if (maxBytes < (PRUint32)extension_length) {
PORT_Assert(0);
return 0;
}
if (append) {
SECStatus rv;
- PRTime age;
+ PRUint32 age;
unsigned int prefixLength;
PRUint8 binder[TLS13_MAX_FINISHED_SIZE];
unsigned int binderLen;
/* extension_type */
rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_tls13_pre_shared_key_xtn, 2);
if (rv != SECSuccess)
goto loser;
@@ -502,18 +503,17 @@ tls13_ClientSendPreSharedKeyXtn(const ss
if (rv != SECSuccess)
goto loser;
rv = ssl3_ExtAppendHandshakeVariable(ss, session_ticket->ticket.data,
session_ticket->ticket.len, 2);
if (rv != SECSuccess)
goto loser;
/* Obfuscated age. */
- age = PR_Now() - session_ticket->received_timestamp;
- age /= PR_USEC_PER_MSEC;
+ age = ssl_Time() - session_ticket->received_timestamp;
age += session_ticket->ticket_age_add;
rv = ssl3_ExtAppendHandshakeNumber(ss, age, 4);
if (rv != SECSuccess)
goto loser;
/* Now the binders. */
prefixLength = ss->ssl3.hs.messages.len;
rv = tls13_ComputePskBinder(CONST_CAST(sslSocket, ss), PR_TRUE,
@@ -679,30 +679,28 @@ tls13_ServerSendPreSharedKeyXtn(const ss
}
/* Handle a TLS 1.3 PreSharedKey Extension. We only accept PSKs
* that contain session tickets. */
SECStatus
tls13_ClientHandlePreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type,
SECItem *data)
{
- PRUint32 index;
- SECStatus rv;
+ PRInt32 index;
SSL_TRC(3, ("%d: SSL3[%d]: handle pre_shared_key extension",
SSL_GETPID(), ss->fd));
- /* The server must not send this extension when negotiating < TLS 1.3. */
+ /* If we are doing < TLS 1.3, then ignore this. */
if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
- PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
- return SECFailure;
+ return SECSuccess;
}
- rv = ssl3_ExtConsumeHandshakeNumber(ss, &index, 2, &data->data, &data->len);
- if (rv != SECSuccess)
+ index = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
+ if (index < 0)
return SECFailure;
/* This should be the end of the extension. */
if (data->len) {
PORT_SetError(SSL_ERROR_MALFORMED_PRE_SHARED_KEY);
return SECFailure;
}
@@ -743,20 +741,20 @@ tls13_ClientSendEarlyDataXtn(const sslSo
if (append) {
rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_tls13_early_data_xtn, 2);
if (rv != SECSuccess)
return -1;
rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2);
if (rv != SECSuccess)
return -1;
+ }
- xtnData->advertised[xtnData->numAdvertised++] =
- ssl_tls13_early_data_xtn;
- }
+ xtnData->advertised[xtnData->numAdvertised++] =
+ ssl_tls13_early_data_xtn;
return extension_length;
}
SECStatus
tls13_ServerHandleEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type,
SECItem *data)
{
@@ -811,17 +809,17 @@ tls13_ServerSendEarlyDataXtn(const sslSo
/* This will only be called if we also offered the extension. */
SECStatus
tls13_ClientHandleEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type,
SECItem *data)
{
SSL_TRC(3, ("%d: TLS13[%d]: handle early_data extension",
SSL_GETPID(), ss->fd));
- /* The server must not send this extension when negotiating < TLS 1.3. */
+ /* If we are doing < TLS 1.3, then ignore this. */
if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
return SECFailure;
}
if (data->len) {
PORT_SetError(SSL_ERROR_MALFORMED_EARLY_DATA);
return SECFailure;
@@ -838,17 +836,17 @@ tls13_ClientHandleTicketEarlyDataInfoXtn
SECItem *data)
{
PRUint32 utmp;
SECStatus rv;
SSL_TRC(3, ("%d: TLS13[%d]: handle early_data_info extension",
SSL_GETPID(), ss->fd));
- /* The server must not send this extension when negotiating < TLS 1.3. */
+ /* If we are doing < TLS 1.3, then ignore this. */
if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
return SECFailure;
}
rv = ssl3_ExtConsumeHandshake(ss, &utmp, sizeof(utmp),
&data->data, &data->len);
if (rv != SECSuccess) {
@@ -1088,23 +1086,16 @@ tls13_SendShortHeaderXtn(const sslSocket
if (ss->opt.enable0RttData) {
return 0;
}
if (IS_DTLS(ss)) {
return 0;
}
- /* Don't send this if TLS 1.3 isn't at least possible. */
- if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
- /* This should only happen on the client. */
- PORT_Assert(!ss->sec.isServer);
- return 0;
- }
-
SSL_TRC(3, ("%d: TLS13[%d]: send short_header extension",
SSL_GETPID(), ss->fd));
if (maxBytes < extension_len) {
PORT_Assert(0);
return 0;
}
@@ -1126,20 +1117,20 @@ tls13_SendShortHeaderXtn(const sslSocket
return extension_len;
}
SECStatus
tls13_HandleShortHeaderXtn(
const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type,
SECItem *data)
{
- SSL_TRC(3, ("%d: TLS13[%d]: handle short_header extension",
+ SSL_TRC(3, ("%d: TLS13[%d]: handle early_data extension",
SSL_GETPID(), ss->fd));
- /* The client might have asked for this, but we didn't negotiate TLS 1.3. */
+ /* If we are doing < TLS 1.3, then ignore this. */
if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
return SECSuccess;
}
/* Presently this is incompatible with 0-RTT. We will fix if
* it becomes more than an experiment. */
if (ss->opt.enable0RttData) {
return SECSuccess;
--- a/security/nss/lib/util/nssutil.def
+++ b/security/nss/lib/util/nssutil.def
@@ -285,14 +285,8 @@ NSSUTIL_ArgParseModuleSpecEx;
;+};
;+NSSUTIL_3.24 { # NSS Utilities 3.24 release
;+ global:
PORT_InitCheapArena;
PORT_DestroyCheapArena;
;+ local:
;+ *;
;+};
-;+NSSUTIL_3.25 { # NSS Utilities 3.25 release
-;+ global:
-SEC_ASN1DecoderSetMaximumElementSize;
-;+ local:
-;+ *;
-;+};
--- a/security/nss/lib/util/nssutil.h
+++ b/security/nss/lib/util/nssutil.h
@@ -14,22 +14,22 @@
/*
* NSS utilities's major version, minor version, patch level, build number,
* and whether this is a beta release.
*
* The format of the version string should be
* "<major version>.<minor version>[.<patch level>[.<build number>]][ <Beta>]"
*/
-#define NSSUTIL_VERSION "3.30 Beta"
+#define NSSUTIL_VERSION "3.28.1"
#define NSSUTIL_VMAJOR 3
-#define NSSUTIL_VMINOR 30
-#define NSSUTIL_VPATCH 0
+#define NSSUTIL_VMINOR 28
+#define NSSUTIL_VPATCH 1
#define NSSUTIL_VBUILD 0
-#define NSSUTIL_BETA PR_TRUE
+#define NSSUTIL_BETA PR_FALSE
SEC_BEGIN_PROTOS
/*
* Returns a const string of the UTIL library version.
*/
extern const char *NSSUTIL_GetVersion(void);
--- a/security/nss/lib/util/pkcs11n.h
+++ b/security/nss/lib/util/pkcs11n.h
@@ -217,22 +217,16 @@
/* TLS extended master secret derivation */
#define CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE (CKM_NSS + 25)
#define CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH (CKM_NSS + 26)
#define CKM_NSS_CHACHA20_KEY_GEN (CKM_NSS + 27)
#define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 28)
-/* Additional PKCS #12 PBE algorithms defined in v1.1 */
-#define CKM_NSS_PKCS12_PBE_SHA224_HMAC_KEY_GEN (CKM_NSS + 29)
-#define CKM_NSS_PKCS12_PBE_SHA256_HMAC_KEY_GEN (CKM_NSS + 30)
-#define CKM_NSS_PKCS12_PBE_SHA384_HMAC_KEY_GEN (CKM_NSS + 31)
-#define CKM_NSS_PKCS12_PBE_SHA512_HMAC_KEY_GEN (CKM_NSS + 32)
-
/*
* HISTORICAL:
* Do not attempt to use these. They are only used by NETSCAPE's internal
* PKCS #11 interface. Most of these are place holders for other mechanism
* and will change in the future.
*/
#define CKM_NETSCAPE_PBE_SHA1_DES_CBC 0x80000002UL
#define CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC 0x80000003UL
--- a/security/nss/lib/util/secasn1.h
+++ b/security/nss/lib/util/secasn1.h
@@ -49,28 +49,16 @@ extern void SEC_ASN1DecoderSetFilterProc
extern void SEC_ASN1DecoderClearFilterProc(SEC_ASN1DecoderContext *cx);
extern void SEC_ASN1DecoderSetNotifyProc(SEC_ASN1DecoderContext *cx,
SEC_ASN1NotifyProc fn,
void *arg);
extern void SEC_ASN1DecoderClearNotifyProc(SEC_ASN1DecoderContext *cx);
-/* Sets the maximum size that should be allocated for a single ASN.1
- * element. Set to 0 to indicate there is no limit.
- *
- * Note: This does not set the maximum size overall that may be allocated
- * while parsing, nor does it guarantee that the decoder won't allocate
- * more than |max_size| while parsing an individual element; rather, it
- * merely guarantees that any individual allocation for returned data
- * should not exceed |max_size|.
-*/
-extern void SEC_ASN1DecoderSetMaximumElementSize(SEC_ASN1DecoderContext *cx,
- unsigned long max_size);
-
extern SECStatus SEC_ASN1Decode(PLArenaPool *pool, void *dest,
const SEC_ASN1Template *t,
const char *buf, long len);
/* Both classic ASN.1 and QuickDER have a feature that removes leading zeroes
out of SEC_ASN1_INTEGER if the caller sets siUnsignedInteger in the type
field of the target SECItem prior to calling the decoder. Otherwise, the
type field is ignored and untouched. For SECItem that are dynamically
--- a/security/nss/lib/util/secasn1d.c
+++ b/security/nss/lib/util/secasn1d.c
@@ -287,27 +287,16 @@ struct sec_DecoderContext_struct {
* give us a pool pointer?
*/
void *their_mark; /* free on error */
#endif
sec_asn1d_state *current;
sec_asn1d_parse_status status;
- /* The maximum size the caller is willing to allow a single element
- * to be before returning an error.
- *
- * In the case of an indefinite length element, this is the sum total
- * of all child elements.
- *
- * In the case of a definite length element, this represents the maximum
- * size of the top-level element.
- */
- unsigned long max_element_size;
-
SEC_ASN1NotifyProc notify_proc; /* call before/after handling field */
void *notify_arg; /* argument to notify_proc */
PRBool during_notify; /* true during call to notify_proc */
SEC_ASN1WriteProc filter_proc; /* pass field bytes to this */
void *filter_arg; /* argument to that function */
PRBool filter_only; /* do not allocate/store fields */
};
@@ -1294,23 +1283,16 @@ sec_asn1d_prepare_for_contents(sec_asn1d
*/
if (state->subitems_head != NULL) {
PORT_Assert(state->underlying_kind == SEC_ASN1_ANY);
for (subitem = state->subitems_head;
subitem != NULL; subitem = subitem->next)
alloc_len += subitem->len;
}
- if (state->top->max_element_size > 0 &&
- alloc_len > state->top->max_element_size) {
- PORT_SetError(SEC_ERROR_OUTPUT_LEN);
- state->top->status = decodeError;
- return;
- }
-
item->data = (unsigned char *)sec_asn1d_zalloc(poolp, alloc_len);
if (item->data == NULL) {
state->top->status = decodeError;
break;
}
len = 0;
for (subitem = state->subitems_head;
@@ -1409,23 +1391,16 @@ sec_asn1d_prepare_for_contents(sec_asn1d
default:
/*
* We are allocating for a simple leaf item.
*/
if (state->contents_length) {
if (state->dest != NULL) {
item = (SECItem *)(state->dest);
item->len = 0;
- if (state->top->max_element_size > 0 &&
- state->contents_length > state->top->max_element_size) {
- PORT_SetError(SEC_ERROR_OUTPUT_LEN);
- state->top->status = decodeError;
- return;
- }
-
if (state->top->filter_only) {
item->data = NULL;
} else {
item->data = (unsigned char *)
sec_asn1d_zalloc(state->top->their_pool,
state->contents_length);
if (item->data == NULL) {
state->top->status = decodeError;
@@ -2243,23 +2218,16 @@ sec_asn1d_concat_substrings(sec_asn1d_st
* ANY that is *not* also an INNER. Because we zero-allocate
* below, all we need to do is increase the length here.
*/
if (state->underlying_kind == SEC_ASN1_ANY && state->indefinite)
item_len += 2;
alloc_len = item_len;
}
- if (state->top->max_element_size > 0 &&
- alloc_len > state->top->max_element_size) {
- PORT_SetError(SEC_ERROR_OUTPUT_LEN);
- state->top->status = decodeError;
- return;
- }
-
item = (SECItem *)(state->dest);
PORT_Assert(item != NULL);
PORT_Assert(item->data == NULL);
item->data = (unsigned char *)sec_asn1d_zalloc(state->top->their_pool,
alloc_len);
if (item->data == NULL) {
state->top->status = decodeError;
return;
@@ -2753,17 +2721,17 @@ SEC_ASN1DecoderUpdate(SEC_ASN1DecoderCon
while (cx->status == keepGoing) {
state = cx->current;
what = SEC_ASN1_Contents;
consumed = 0;
#ifdef DEBUG_ASN1D_STATES
printf("\nPLACE = %s, next byte = 0x%02x, %08x[%d]\n",
(state->place >= 0 && state->place <= notInUse) ? place_names[state->place] : "(undefined)",
- len ? (unsigned int)((unsigned char *)buf)[consumed] : 0,
+ (unsigned int)((unsigned char *)buf)[consumed],
buf, consumed);
dump_states(cx);
#endif /* DEBUG_ASN1D_STATES */
switch (state->place) {
case beforeIdentifier:
consumed = sec_asn1d_parse_identifier(state, buf, len);
what = SEC_ASN1_Identifier;
break;
@@ -3069,23 +3037,16 @@ SEC_ASN1DecoderSetNotifyProc(SEC_ASN1Dec
void
SEC_ASN1DecoderClearNotifyProc(SEC_ASN1DecoderContext *cx)
{
cx->notify_proc = NULL;
cx->notify_arg = NULL; /* not necessary; just being clean */
}
void
-SEC_ASN1DecoderSetMaximumElementSize(SEC_ASN1DecoderContext *cx,
- unsigned long max_size)
-{
- cx->max_element_size = max_size;
-}
-
-void
SEC_ASN1DecoderAbort(SEC_ASN1DecoderContext *cx, int error)
{
PORT_Assert(cx);
PORT_SetError(error);
cx->status = decodeError;
}
SECStatus
@@ -3095,20 +3056,16 @@ SEC_ASN1Decode(PLArenaPool *poolp, void
{
SEC_ASN1DecoderContext *dcx;
SECStatus urv, frv;
dcx = SEC_ASN1DecoderStart(poolp, dest, theTemplate);
if (dcx == NULL)
return SECFailure;
- /* In one-shot mode, there's no possibility of streaming data beyond the
- * length of len */
- SEC_ASN1DecoderSetMaximumElementSize(dcx, len);
-
urv = SEC_ASN1DecoderUpdate(dcx, buf, len);
frv = SEC_ASN1DecoderFinish(dcx);
if (urv != SECSuccess)
return urv;
return frv;
}
--- a/security/nss/lib/util/utilmod.c
+++ b/security/nss/lib/util/utilmod.c
@@ -227,25 +227,20 @@ nssutil_ReadSecmodDB(const char *appName
* the following loop takes line separated config lines and collapses
* the lines to a single string, escaping and quoting as necessary.
*/
/* loop state variables */
moduleString = NULL; /* current concatenated string */
internal = PR_FALSE; /* is this an internal module */
skipParams = PR_FALSE; /* did we find an override parameter block*/
paramsValue = NULL; /* the current parameter block value */
- do {
- int len;
-
- if (fgets(line, sizeof(line), fd) == NULL) {
- goto endloop;
- }
+ while (fgets(line, sizeof(line), fd) != NULL) {
+ int len = PORT_Strlen(line);
/* remove the ending newline */
- len = PORT_Strlen(line);
if (len && line[len - 1] == '\n') {
len--;
line[len] = 0;
}
if (*line == '#') {
continue;
}
if (*line != 0) {
@@ -344,17 +339,16 @@ nssutil_ReadSecmodDB(const char *appName
}
}
continue;
}
if ((moduleString == NULL) || (*moduleString == 0)) {
continue;
}
- endloop:
/*
* if we are here, we have found a complete stanza. Now write out
* any param section we may have found.
*/
if (paramsValue) {
/* we had an override */
if (!skipParams) {
moduleString = nssutil_DupnCat(moduleString, " parameters=", 12);
@@ -380,17 +374,17 @@ nssutil_ReadSecmodDB(const char *appName
moduleList[0] = moduleString;
} else {
moduleList[moduleCount] = moduleString;
moduleCount++;
}
moduleString = NULL;
internal = PR_FALSE;
skipParams = PR_FALSE;
- } while (!feof(fd));
+ }
if (moduleString) {
PORT_Free(moduleString);
moduleString = NULL;
}
done:
/* if we couldn't open a pkcs11 database, look for the old one */
if (fd == NULL) {
deleted file mode 100644
--- a/security/nss/nss-tool/.clang-format
+++ /dev/null
@@ -1,4 +0,0 @@
----
-Language: Cpp
-BasedOnStyle: Google
-...
deleted file mode 100644
--- a/security/nss/nss-tool/common/argparse.cc
+++ /dev/null
@@ -1,23 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "argparse.h"
-
-ArgParser::ArgParser(const std::vector<std::string>& arguments) {
- for (size_t i = 0; i < arguments.size(); i++) {
- std::string arg = arguments.at(i);
- if (arg.find("--") == 0) {
- // look for an option argument
- if (i + 1 < arguments.size() && arguments.at(i + 1).find("--") != 0) {
- programArgs_[arg] = arguments.at(i + 1);
- i++;
- } else {
- programArgs_[arg] = "";
- }
- } else {
- // positional argument (e.g. required argument)
- positionalArgs_.push_back(arg);
- }
- }
-}
deleted file mode 100644
--- a/security/nss/nss-tool/common/argparse.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef argparse_h__
-#define argparse_h__
-
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-class ArgParser {
- public:
- ArgParser(const std::vector<std::string>& arguments);
-
- bool Has(std::string arg) const { return programArgs_.count(arg) > 0; }
-
- std::string Get(std::string arg) const { return programArgs_.at(arg); }
-
- size_t GetPositionalArgumentCount() const { return positionalArgs_.size(); }
- std::string GetPositionalArgument(size_t pos) const {
- return positionalArgs_.at(pos);
- }
-
- private:
- std::unordered_map<std::string, std::string> programArgs_;
- std::vector<std::string> positionalArgs_;
-};
-
-#endif // argparse_h__
deleted file mode 100644
--- a/security/nss/nss-tool/common/scoped_ptrs.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef scoped_ptrs_h__
-#define scoped_ptrs_h__
-
-#include <memory>
-#include "cert.h"
-#include "keyhi.h"
-#include "pk11pub.h"
-
-struct ScopedDelete {
- void operator()(CERTCertificate* cert) { CERT_DestroyCertificate(cert); }
- void operator()(CERTCertificateList* list) {
- CERT_DestroyCertificateList(list);
- }
- void operator()(CERTSubjectPublicKeyInfo* spki) {
- SECKEY_DestroySubjectPublicKeyInfo(spki);
- }
- void operator()(PK11SlotInfo* slot) { PK11_FreeSlot(slot); }
- void operator()(PK11SymKey* key) { PK11_FreeSymKey(key); }
- void operator()(SECAlgorithmID* id) { SECOID_DestroyAlgorithmID(id, true); }
- void operator()(SECItem* item) { SECITEM_FreeItem(item, true); }
- void operator()(SECKEYPublicKey* key) { SECKEY_DestroyPublicKey(key); }
- void operator()(SECKEYPrivateKey* key) { SECKEY_DestroyPrivateKey(key); }
-
- void operator()(CERTCertList* list) { CERT_DestroyCertList(list); }
-};
-
-template <class T>
-struct ScopedMaybeDelete {
- void operator()(T* ptr) {
- if (ptr) {
- ScopedDelete del;
- del(ptr);
- }
- }
-};
-
-#define SCOPED(x) typedef std::unique_ptr<x, ScopedMaybeDelete<x> > Scoped##x
-
-SCOPED(CERTCertificate);
-SCOPED(CERTCertificateList);
-SCOPED(CERTSubjectPublicKeyInfo);
-SCOPED(PK11SlotInfo);
-SCOPED(PK11SymKey);
-SCOPED(SECAlgorithmID);
-SCOPED(SECItem);
-SCOPED(SECKEYPublicKey);
-SCOPED(SECKEYPrivateKey);
-
-SCOPED(CERTCertList);
-
-#undef SCOPED
-
-#endif
deleted file mode 100644
--- a/security/nss/nss-tool/db/dbtool.cc
+++ /dev/null
@@ -1,281 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "dbtool.h"
-#include "argparse.h"
-#include "scoped_ptrs.h"
-
-#include <dirent.h>
-#include <fstream>
-#include <iomanip>
-#include <iostream>
-#include <memory>
-#include <regex>
-#include <sstream>
-
-#include <cert.h>
-#include <certdb.h>
-#include <nss.h>
-#include <prio.h>
-
-static std::string PrintFlags(unsigned int flags) {
- std::stringstream ss;
- if ((flags & CERTDB_VALID_CA) && !(flags & CERTDB_TRUSTED_CA) &&
- !(flags & CERTDB_TRUSTED_CLIENT_CA)) {
- ss << "c";
- }
- if ((flags & CERTDB_TERMINAL_RECORD) && !(flags & CERTDB_TRUSTED)) {
- ss << "p";
- }
- if (flags & CERTDB_TRUSTED_CA) {
- ss << "C";
- }
- if (flags & CERTDB_TRUSTED_CLIENT_CA) {
- ss << "T";
- }
- if (flags & CERTDB_TRUSTED) {
- ss << "P";
- }
- if (flags & CERTDB_USER) {
- ss << "u";
- }
- if (flags & CERTDB_SEND_WARN) {
- ss << "w";
- }
- if (flags & CERTDB_INVISIBLE_CA) {
- ss << "I";
- }
- if (flags & CERTDB_GOVT_APPROVED_CA) {
- ss << "G";
- }
- return ss.str();
-}
-
-static std::vector<char> ReadFromIstream(std::istream &is) {
- std::vector<char> certData;
- while (is) {
- char buf[1024];
- is.read(buf, sizeof(buf));
- certData.insert(certData.end(), buf, buf + is.gcount());
- }
-
- return certData;
-}
-
-void DBTool::Usage() {
- std::cerr << "Usage: nss db [--path <directory>]" << std::endl;
- std::cerr << " --create" << std::endl;
- std::cerr << " --list-certs" << std::endl;
- std::cerr << " --import-cert [<path>] --name <name> [--trusts <trusts>]"
- << std::endl;
-}
-
-bool DBTool::Run(const std::vector<std::string> &arguments) {
- ArgParser parser(arguments);
-
- if (!parser.Has("--create") && !parser.Has("--list-certs") &&
- !parser.Has("--import-cert")) {
- return false;
- }
-
- PRAccessHow how = PR_ACCESS_READ_OK;
- bool readOnly = true;
- if (parser.Has("--create") || parser.Has("--import-cert")) {
- how = PR_ACCESS_WRITE_OK;
- readOnly = false;
- }
-
- std::string initDir(".");
- if (parser.Has("--path")) {
- initDir = parser.Get("--path");
- }
- if (PR_Access(initDir.c_str(), how) != PR_SUCCESS) {
- std::cerr << "Directory '" << initDir
- << "' does not exist or you don't have permissions!" << std::endl;
- return false;
- }
-
- std::cout << "Using database directory: " << initDir << std::endl
- << std::endl;
-
- bool dbFilesExist = PathHasDBFiles(initDir);
- if (parser.Has("--create") && dbFilesExist) {
- std::cerr << "Trying to create database files in a directory where they "
- "already exists. Delete the db files before creating new ones."
- << std::endl;
- return false;
- }
- if (!parser.Has("--create") && !dbFilesExist) {
- std::cerr << "No db files found." << std::endl;
- std::cerr << "Create them using 'nss db --create [--path /foo/bar]' before "
- "continuing."
- << std::endl;
- return false;
- }
-
- // init NSS
- const char *certPrefix = ""; // certutil -P option --- can leave this empty
- SECStatus rv = NSS_Initialize(initDir.c_str(), certPrefix, certPrefix,
- "secmod.db", readOnly ? NSS_INIT_READONLY : 0);
- if (rv != SECSuccess) {
- std::cerr << "NSS init failed!" << std::endl;
- return false;
- }
-
- bool ret = true;
- if (parser.Has("--list-certs")) {
- ListCertificates();
- } else if (parser.Has("--import-cert")) {
- ret = ImportCertificate(parser);
- } else if (parser.Has("--create")) {
- std::cout << "DB files created successfully." << std::endl;
- }
-
- // shutdown nss
- if (NSS_Shutdown() != SECSuccess) {
- std::cerr << "NSS Shutdown failed!" << std::endl;
- return false;
- }
-
- return ret;
-}
-
-bool DBTool::PathHasDBFiles(std::string path) {
- std::regex certDBPattern("cert.*\\.db");
- std::regex keyDBPattern("key.*\\.db");
-
- DIR *dir;
- if (!(dir = opendir(path.c_str()))) {
- std::cerr << "Directory " << path << " could not be accessed!" << std::endl;
- return false;
- }
-
- struct dirent *ent;
- bool dbFileExists = false;
- while ((ent = readdir(dir))) {
- if (std::regex_match(ent->d_name, certDBPattern) ||
- std::regex_match(ent->d_name, keyDBPattern) ||
- "secmod.db" == std::string(ent->d_name)) {
- dbFileExists = true;
- break;
- }
- }
-
- closedir(dir);
- return dbFileExists;
-}
-
-void DBTool::ListCertificates() {
- ScopedCERTCertList list(PK11_ListCerts(PK11CertListAll, nullptr));
- CERTCertListNode *node;
-
- std::cout << std::setw(60) << std::left << "Certificate Nickname"
- << " "
- << "Trust Attributes" << std::endl;
- std::cout << std::setw(60) << std::left << ""
- << " "
- << "SSL,S/MIME,JAR/XPI" << std::endl
- << std::endl;
-
- for (node = CERT_LIST_HEAD(list); !CERT_LIST_END(node, list);
- node = CERT_LIST_NEXT(node)) {
- CERTCertificate *cert = node->cert;
-
- std::string name("(unknown)");
- char *appData = static_cast<char *>(node->appData);
- if (appData && strlen(appData) > 0) {
- name = appData;
- } else if (cert->nickname && strlen(cert->nickname) > 0) {
- name = cert->nickname;
- } else if (cert->emailAddr && strlen(cert->emailAddr) > 0) {
- name = cert->emailAddr;
- }
-
- CERTCertTrust trust;
- std::string trusts;
- if (CERT_GetCertTrust(cert, &trust) == SECSuccess) {
- std::stringstream ss;
- ss << PrintFlags(trust.sslFlags);
- ss << ",";
- ss << PrintFlags(trust.emailFlags);
- ss << ",";
- ss << PrintFlags(trust.objectSigningFlags);
- trusts = ss.str();
- } else {
- trusts = ",,";
- }
- std::cout << std::setw(60) << std::left << name << " " << trusts
- << std::endl;
- }
-}
-
-bool DBTool::ImportCertificate(const ArgParser &parser) {
- if (!parser.Has("--name")) {
- std::cerr << "A name (--name) is required to import a certificate."
- << std::endl;
- return false;
- }
-
- std::string derFilePath = parser.Get("--import-cert");
- std::string certName = parser.Get("--name");
- std::string trustString("TCu,Cu,Tu");
- if (parser.Has("--trusts")) {
- trustString = parser.Get("--trusts");
- }
-
- CERTCertTrust trust;
- SECStatus rv = CERT_DecodeTrustString(&trust, trustString.c_str());
- if (rv != SECSuccess) {
- std::cerr << "Cannot decode trust string!" << std::endl;
- return false;
- }
-
- ScopedPK11SlotInfo slot = ScopedPK11SlotInfo(PK11_GetInternalKeySlot());
- if (slot.get() == nullptr) {
- std::cerr << "Error: Init PK11SlotInfo failed!\n";
- return false;
- }
-
- std::vector<char> certData;
- if (derFilePath.empty()) {
- std::cout << "No Certificate file path given, using stdin." << std::endl;
- certData = ReadFromIstream(std::cin);
- } else {
- std::ifstream is(derFilePath, std::ifstream::binary);
- if (!is.good()) {
- std::cerr << "IO Error when opening " << derFilePath << std::endl;
- std::cerr
- << "Certificate file does not exist or you don't have permissions."
- << std::endl;
- return false;
- }
- certData = ReadFromIstream(is);
- }
-
- ScopedCERTCertificate cert(
- CERT_DecodeCertFromPackage(certData.data(), certData.size()));
- if (cert.get() == nullptr) {
- std::cerr << "Error: Could not decode certificate!" << std::endl;
- return false;
- }
-
- rv = PK11_ImportCert(slot.get(), cert.get(), CK_INVALID_HANDLE,
- certName.c_str(), PR_FALSE);
- if (rv != SECSuccess) {
- // TODO handle authentication -> PK11_Authenticate (see certutil.c line
- // 134)
- std::cerr << "Error: Could not add certificate to database!" << std::endl;
- return false;
- }
-
- rv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), cert.get(), &trust);
- if (rv != SECSuccess) {
- std::cerr << "Cannot change cert's trust" << std::endl;
- return false;
- }
-
- std::cout << "Certificate import was successful!" << std::endl;
- // TODO show information about imported certificate
- return true;
-}
deleted file mode 100644
--- a/security/nss/nss-tool/db/dbtool.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef dbtool_h__
-#define dbtool_h__
-
-#include <string>
-#include <vector>
-#include "argparse.h"
-
-class DBTool {
- public:
- bool Run(const std::vector<std::string>& arguments);
-
- void Usage();
-
- private:
- bool PathHasDBFiles(std::string path);
- void ListCertificates();
- bool ImportCertificate(const ArgParser& parser);
-};
-
-#endif // dbtool_h__
deleted file mode 100644
--- a/security/nss/nss-tool/nss_tool.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <iostream>
-#include <string>
-#include <vector>
-
-#include <prinit.h>
-
-#include "argparse.h"
-#include "db/dbtool.h"
-
-static void Usage() {
- std::cerr << "Usage: nss <command> <subcommand> [options]" << std::endl;
- std::cerr << " nss db [--path <directory>] <commands>" << std::endl;
-}
-
-int main(int argc, char **argv) {
- if (argc < 2) {
- Usage();
- return 1;
- }
-
- if (std::string(argv[1]) != "db") {
- Usage();
- return 1;
- }
-
- int exit_code = 0;
- PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
-
- std::vector<std::string> arguments(argv + 2, argv + argc);
- DBTool tool;
- if (!tool.Run(arguments)) {
- tool.Usage();
- exit_code = 1;
- }
-
- PR_Cleanup();
-
- return exit_code;
-}
deleted file mode 100644
--- a/security/nss/nss-tool/nss_tool.gyp
+++ /dev/null
@@ -1,27 +0,0 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-{
- 'includes' : [
- '../coreconf/config.gypi',
- '../cmd/platlibs.gypi',
- ],
- 'targets' : [
- {
- 'target_name' : 'nss',
- 'type' : 'executable',
- 'sources' : [
- 'nss_tool.cc',
- 'common/argparse.cc',
- 'db/dbtool.cc',
- ],
- 'include_dirs': [
- 'common',
- ],
- 'dependencies' : [
- '<(DEPTH)/exports.gyp:dbm_exports',
- '<(DEPTH)/exports.gyp:nss_exports'
- ],
- }
- ],
-}
--- a/security/nss/nss.gyp
+++ b/security/nss/nss.gyp
@@ -115,17 +115,16 @@
'dependencies': [
'cmd/crlutil/crlutil.gyp:crlutil',
'cmd/pwdecrypt/pwdecrypt.gyp:pwdecrypt',
'cmd/signtool/signtool.gyp:signtool',
'cmd/signver/signver.gyp:signver',
'cmd/smimetools/smimetools.gyp:cmsutil',
'cmd/ssltap/ssltap.gyp:ssltap',
'cmd/symkeyutil/symkeyutil.gyp:symkeyutil',
- 'nss-tool/nss_tool.gyp:nss',
],
}],
],
},
],
'conditions': [
[ 'disable_tests==0', {
'targets': [
@@ -172,16 +171,18 @@
'cmd/tests/tests.gyp:dertimetest',
'cmd/tests/tests.gyp:encodeinttest',
'cmd/tests/tests.gyp:nonspr10',
'cmd/tests/tests.gyp:remtest',
'cmd/tests/tests.gyp:secmodtest',
'cmd/tstclnt/tstclnt.gyp:tstclnt',
'cmd/vfychain/vfychain.gyp:vfychain',
'cmd/vfyserv/vfyserv.gyp:vfyserv',
+ 'gtests/google_test/google_test.gyp:gtest1',
+ 'gtests/common/common.gyp:gtests',
'gtests/der_gtest/der_gtest.gyp:der_gtest',
'gtests/pk11_gtest/pk11_gtest.gyp:pk11_gtest',
'gtests/ssl_gtest/ssl_gtest.gyp:ssl_gtest',
'gtests/util_gtest/util_gtest.gyp:util_gtest',
'gtests/nss_bogo_shim/nss_bogo_shim.gyp:nss_bogo_shim'
],
'conditions': [
[ 'OS=="linux"', {
@@ -235,38 +236,34 @@
}],
],
'action': ['<(python)', '<(DEPTH)/coreconf/shlibsign.py', '<@(_inputs)']
}
],
},
],
}],
- [ 'fuzz_tls==1', {
+ [ 'fuzz==1', {
'targets': [
{
'target_name': 'fuzz_warning',
'type': 'none',
'actions': [
{
'action_name': 'fuzz_warning',
'action': ['cat', 'fuzz/warning.txt'],
'inputs': ['fuzz/warning.txt'],
'ninja_use_console': 1,
'outputs': ['dummy'],
}
],
},
- ],
- }],
- [ 'fuzz==1', {
- 'targets': [
{
'target_name': 'fuzz',
'type': 'none',
'dependencies': [
'fuzz/fuzz.gyp:nssfuzz',
- ],
+ ]
},
],
}],
],
}
--- a/security/nss/readme.md
+++ b/security/nss/readme.md
@@ -1,173 +1,99 @@
# Network Security Services
-Network Security Services (NSS) is a set of libraries designed to support
-cross-platform development of security-enabled client and server
-applications. NSS supports SSL v3-TLS 1.2 (experimental TLS 1.3), PKCS #5, PKCS#7,
-PKCS #11, PKCS #12, S/MIME, X.509 v3 certificates, and other security
-standards.
+Network Security Services (NSS) is a set of libraries designed to support cross-platform development of security-enabled client and server applications. NSS supports SSL v3-TLS 1.2 (experimental TLS 1.3), PKCS #5, PKCS #7, PKCS #11, PKCS #12, S/MIME, X.509 v3 certificates, and other security standards.
## Getting started
-
-In order to get started create a new directory on that you will be uses as your
-local work area, and check out NSS and NSPR. (Note that there's no git mirror of
-NSPR and you require mercurial to get the latest NSPR source.)
+In order to get started create a new directory on that you will be uses as your local work area, and check out NSS and NSPR. (Note that there's no git mirror of NSPR and you require mercurial to get the latest NSPR source.)
git clone https://github.com/nss-dev/nss.git
hg clone https://hg.mozilla.org/projects/nspr
NSS can also be cloned with mercurial `
hg clone https://hg.mozilla.org/projects/nspr`
## Building NSS
-
-**This build system is under development. It does not yet support all the
-features or platforms that NSS supports. To build on anything other than Mac or
-Linux please use the legacy build system as described below.**
+*This build system is under development. It does not yet support all the features or platforms that NSS supports. To build on anything other than Mac or Linux please use the legacy build system as described below.*
Build requirements:
* [gyp](https://gyp.gsrc.io/)
* [ninja](https://ninja-build.org/)
After changing into the NSS directory a typical build is done as follows
./build.sh
-Once the build is done the build output is found in the directory
-`../dist/Debug` for debug builds and `../dist/Release` for opt builds.
-Exported header files can be found in the `include` directory, library files in
-directory `lib`, and tools in directory `bin`. In order to run the tools, set
-your system environment to use the libraries of your build from the "lib"
-directory, e.g., using the `LD_LIBRARY_PATH` or `DYLD_LIBRARY_PATH`.
+Once the build is done the build output is found in the directory `../dist/*.OBJ`, where `*` will be a name dynamically derived from your system's architecture. Exported header files can be found in the `include` directory, library files in directory `lib`, and tools in directory `bin`. In order to run the tools, set your system environment to use the libraries of your build from the "lib" directory, e.g., using the `LD_LIBRARY_PATH` or `DYLD_LIBRARY_PATH`.
- Usage: build.sh [-hcv] [-j <n>] [--nspr] [--gyp|-g] [--opt|-o] [-m32]
- [--test] [--fuzz] [--pprof] [--scan-build[=output]]
- [--asan] [--ubsan] [--msan] [--sancov[=edge|bb|func|...]]
- [--ct-verif] [--disable-tests]
-
- This script builds NSS with gyp and ninja.
-
- This build system is still under development. It does not yet support all
- the features or platforms that NSS supports.
-
- NSS build tool options:
+---
+ Usage: build.sh [-hcgv] [-j <n>] [--test] [--fuzz] [--scan-build[=output]]
+ [-m32] [--opt|-o]
- -h display this help and exit
- -c clean before build
- -v verbose build
- -j <n> run at most <n> concurrent jobs
- --nspr force a rebuild of NSPR
- --gyp|-g force a rerun of gyp
- --opt|-o do an opt build
- -m32 do a 32-bit build on a 64-bit system
- --test ignore map files and export everything we have
- --fuzz enable fuzzing mode. this always enables test builds
- --pprof build with gperftool support
- --ct-verif build with valgrind for ct-verif
- --scan-build run the build with scan-build (scan-build has to be in the path)
- --scan-build=/out/path sets the output path for scan-build
- --asan do an asan build
- --ubsan do an ubsan build
- --ubsan=bool,shift,... sets specific UB sanitizers
- --msan do an msan build
- --sancov do sanitize coverage builds
- --sancov=func sets coverage to function level for example
- --disable-tests don't build tests and corresponding cmdline utils
+ -h display this help and exit
+ -c clean before build
+ -g force a rebuild of gyp (and NSPR, because why not)
+ -j <n> run at most <n> concurrent jobs
+ -v verbose build
+ -m32 do a 32-bit build on a 64-bit system
+ --test ignore map files and export everything we have
+ --fuzz enable fuzzing mode. this always enables test builds
+ --scan-build run the build with scan-build (scan-build has to be in the path)
+ --scan-build=/out/path sets the output path for scan-build
+ --opt|-o do an opt build
## Building NSS (legacy build system)
-
-After changing into the NSS directory a typical build of 32-bit NSS is done as
-follows:
+After changing into the NSS directory a typical build of 32-bit NSS is done as follows
make nss_build_all
The following environment variables might be useful:
-
* `BUILD_OPT=1` to get an optimised build
-
* `USE_64=1` to get a 64-bit build (recommended)
+* `NSS_ENABLE_TLS_1_3=1` to enable TLS 1.3 support
-The complete list of environment variables can be found
-[here](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Reference/NSS_environment_variables).
+The complete list of environment variables can be found [here](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Reference/NSS_environment_variables).
-To clean the build directory run:
+To clean the build directory run
make nss_clean_all
## Tests
-
### Setup
-
-Make sure that the address `$HOST.$DOMSUF` on your computer is available. This
-is necessary because NSS tests generate certificates and establish TLS
-connections, which requires a fully qualified domain name.
-You can test this by
-calling `ping $HOST.$DOMSUF`. If this is working, you're all set. If it's not,
-set or export:
+Make sure that the address `$HOST.$DOMSUF` on your computer is available. This is necessary because NSS tests generate certificates and establish TLS connections, which requires a fully qualified domain name.
+You can test this by calling `ping $HOST.$DOMSUF`. If this is working, you're all set.
+If it's not, set or export
HOST=nss
DOMSUF=local
-
-Note that you might have to add `nss.local` to `/etc/hosts` if it's not
-there. The entry should look something like `127.0.0.1 nss.local nss`.
-
-If you get name resolution errors, try to ensure that you are using an IPv4
-address; IPv6 is the default on many systems for the loopback device which
-doesn't work.
+Note that you might have to add `nss.local` to `/etc/hosts` if it's not there. The entry should look something like `127.0.0.1 nss.local nss`.
+If you get name resolution errors, try to disable IPv6 on the loopback device, i.e. comment the lines starting with `::1` in your `/etc/hosts` .
### Running tests
-
-**Runnning all tests will take a while!**
+*Runnning all tests will take a while!*
cd tests
./all.sh
-
-Make sure that all environment variables set for the build are set while running
-the tests as well. Test results are published in the folder
-`../../test_results/`.
-
-Individual tests can be run with the `NSS_TESTS` environment variable,
-e.g. `NSS_TESTS=ssl_gtests ./all.sh` or by changing into the according directory
-and running the bash script there `cd ssl_gtests && ./ssl_gtests.sh`. The
-following tests are available:
+Make sure that all environment variables set for the build are set while running the tests as well.
+Test results are published in the folder `../../test_results/`.
+Individual tests can be run with the `NSS_TESTS` environment variable, e.g. `NSS_TESTS=ssl_gtests ./all.sh` or by changing into the according directory and running the bash script there `cd ssl_gtests && ./ssl_gtests.sh`. The following tests are available:
cipher lowhash libpkix cert dbtests tools fips sdr crmf smime ssl ocsp merge pkits chains ec gtests ssl_gtests bogo
-To make tests run faster it's recommended to set `NSS_CYCLES=standard` to run
-only the standard cycle.
+To make tests run faster it's recommended to set `NSS_CYCLES=standard` to run only the standard cycle.
## Releases
-
-NSS releases can be found at [Mozilla's download
-server](https://ftp.mozilla.org/pub/security/nss/releases/). Because NSS depends
-on the base library NSPR you should download the archive that combines both NSS
-and NSPR.
+NSS releases can be found at [Mozilla's download server](https://ftp.mozilla.org/pub/security/nss/releases/). Because NSS depends on the base library NSPR you should download the archive that combines both NSS and NSPR.
## Contributing
-
-[Bugzilla](https://bugzilla.mozilla.org/) is used to track NSS development and
-bugs. File new bugs in the NSS product.
-
-A list with good first bugs to start with are [listed
-here](https://bugzilla.mozilla.org/buglist.cgi?keywords=good-first-bug%2C%20&keywords_type=allwords&list_id=13238861&resolution=---&query_format=advanced&product=NSS).
+[Bugzilla](https://bugzilla.mozilla.org/) is used to track NSS development and bugs. File new bugs in the NSS product.
+A list with good first bugs to start with are [listed here](https://bugzilla.mozilla.org/buglist.cgi?keywords=good-first-bug%2C%20&keywords_type=allwords&list_id=13238861&resolution=---&query_format=advanced&product=NSS).
### NSS Folder Structure
-
The nss directory contains the following important subdirectories:
-
- `coreconf` contains the build logic.
-
- `lib` contains all library code that is used to create the runtime libraries.
+- `cmd` contains a set of various tool programs that are built with NSS. Several tools are general purpose and can be used to inspect and manipulate the storage files that software using the NSS library creates and modifies. Other tools are only used for testing purposes.
+- `test` and `gtests` contain the NSS test suite. While `test` contains shell scripts to drive test programs in `cmd`, `gtests` holds a set of [gtests](https://github.com/google/googletest).
-- `cmd` contains a set of various tool programs that are built with NSS. Several
- tools are general purpose and can be used to inspect and manipulate the
- storage files that software using the NSS library creates and modifies. Other
- tools are only used for testing purposes.
+A more comprehensible overview of the NSS folder structure and API guidelines can be found [here](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/NSS_API_Guidelines).
-- `test` and `gtests` contain the NSS test suite. While `test` contains shell
- scripts to drive test programs in `cmd`, `gtests` holds a set of
- [gtests](https://github.com/google/googletest).
-
-A more comprehensible overview of the NSS folder structure and API guidelines
-can be found
-[here](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/NSS_API_Guidelines).
--- a/security/nss/tests/all.sh
+++ b/security/nss/tests/all.sh
@@ -34,18 +34,16 @@
# chains.sh - PKIX cert chains tests
# dbupgrade.sh - upgrade databases to new shareable version (used
# only in upgrade test cycle)
# memleak.sh - memory leak testing (optional)
# ssl_gtests.sh- Gtest based unit tests for ssl
# gtests.sh - Gtest based unit tests for everything else
# bogo.sh - Bogo interop tests (disabled by default)
# https://boringssl.googlesource.com/boringssl/+/master/ssl/test/PORTING.md
-# interop.sh - Interoperability tests (disabled by default)
-# https://github.com/ekr/tls_interop
#
# NSS testing is now devided to 4 cycles:
# ---------------------------------------
# standard - run test suites with defaults settings
# pkix - run test suites with PKIX enabled
# upgradedb - upgrade existing certificate databases to shareable
# format (creates them if doesn't exist yet) and run
# test suites with those databases
@@ -57,16 +55,17 @@
# -----------------------------------------------------------
# HOST - test machine host name
# DOMSUF - test machine domain name
#
# Optional environment variables to specify build to use:
# -------------------------------------------------------
# BUILT_OPT - use optimized/debug build
# USE_64 - use 64bit/32bit build
+# USE_ASAN - use Address Sanitizer build
#
# Optional environment variables to enable specific NSS features:
# ---------------------------------------------------------------
# NSS_DISABLE_ECC - disable ECC
#
# Optional environment variables to select which cycles/suites to test:
# ---------------------------------------------------------------------
# NSS_CYCLES - list of cycles to run (separated by space
--- a/security/nss/tests/bogo/bogo.sh
+++ b/security/nss/tests/bogo/bogo.sh
@@ -34,16 +34,19 @@ bogo_init()
bogo_cleanup()
{
html "</TABLE><BR>"
cd ${QADIR}
. common/cleanup.sh
}
+# Need to add go to the PATH.
+export PATH=$PATH:/usr/lib/go-1.6/bin
+
cd "$(dirname "$0")"
SOURCE_DIR="$PWD"/../..
bogo_init
(cd "$BORING"/ssl/test/runner;
GOPATH="$PWD" go test -pipe -shim-path "${BINDIR}"/nss_bogo_shim \
-loose-errors -allow-unimplemented \
-shim-config "${SOURCE_DIR}/gtests/nss_bogo_shim/config.json") \
2>bogo.errors | tee bogo.log
deleted file mode 100755
--- a/security/nss/tests/interop/interop.sh
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/bin/bash
-#
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-########################################################################
-#
-# tests/interop/interop.sh
-#
-# Script to drive our cross-stack interop tests
-#
-########################################################################
-
-interop_init()
-{
- SCRIPTNAME="interop.sh"
- if [ -z "${INIT_SOURCED}" -o "${INIT_SOURCED}" != "TRUE" ] ; then
- cd ../common
- . ./init.sh
- fi
-
- mkdir -p "${HOSTDIR}/interop"
- cd "${HOSTDIR}/interop"
- INTEROP=${INTEROP:=tls_interop}
- if [ ! -d "$INTEROP" ]; then
- git clone -q https://github.com/mozilla/tls-interop "$INTEROP"
- fi
-
- # We use the BoringSSL keyfiles
- BORING=${BORING:=boringssl}
- if [ ! -d "$BORING" ]; then
- git clone -q https://boringssl.googlesource.com/boringssl "$BORING"
- git -C "$BORING" checkout -q ea80f9d5df4c302de391e999395e1c87f9c786b3
- fi
-
- SCRIPTNAME="interop.sh"
- html_head "interop test"
-}
-
-interop_cleanup()
-{
- html "</TABLE><BR>"
- cd ${QADIR}
- . common/cleanup.sh
-}
-
-# Function so we can easily add other stacks
-interop_run()
-{
- test_name=$1
- client=$2
- server=$3
-
- (cd "$INTEROP";
- cargo run -- --client ${client} --server ${server} --rootdir ../${BORING}/ssl/test/runner/ --test-cases cases.json) 2>interop-${test_name}.errors | tee interop-${test_name}.log
- html_msg "${PIPESTATUS[0]}" 0 "Interop" "Run successfully"
- grep -i 'FAILED\|Assertion failure' interop-${test_name}.errors
- html_msg $? 1 "Interop" "No failures"
-}
-
-cd "$(dirname "$0")"
-SOURCE_DIR="$PWD"/../..
-interop_init
-NSS_SHIM="${BINDIR}"/nss_bogo_shim
-BORING_SHIM="../${BORING}"/build/ssl/test/bssl_shim
-interop_run "nss_nss" ${NSS_SHIM} ${NSS_SHIM}
-interop_cleanup
--- a/security/nss/tests/ssl/ssl.sh
+++ b/security/nss/tests/ssl/ssl.sh
@@ -1001,17 +1001,17 @@ ssl_cleanup()
# local shell function to run coverage, authentication and stress tests
########################################################################
ssl_run()
{
for SSL_RUN in ${NSS_SSL_RUN}
do
case "${SSL_RUN}" in
"stapling")
- if [ -z "$NSS_DISABLE_LIBPKIX" ]; then
+ if [ -nz "$NSS_DISABLE_LIBPKIX" ]; then
ssl_stapling
fi
;;
"signed_cert_timestamps")
ssl_signed_cert_timestamps
;;
"cov")
ssl_cov