Update NSS to 3.35-RTM

This commit is contained in:
wolfbeast 2018-02-23 11:04:39 +01:00 • committed by Roy Tam
commit 66dd670b60
388 changed files with 39075 additions and 20752 deletions

View file

@ -57,7 +57,7 @@ tasks:
- "tc-treeherder.v2.{{project}}.{{revision}}.{{pushlog_id}}" - "tc-treeherder.v2.{{project}}.{{revision}}.{{pushlog_id}}"
payload: payload:
image: ttaubert/nss-decision:0.0.2 image: nssdev/nss-decision:0.0.2
env: env:
TC_OWNER: {{owner}} TC_OWNER: {{owner}}

View file

@ -1 +0,0 @@
NSS_3_32_1_RTM

View file

@ -0,0 +1,8 @@
Functions changes summary: 1 Removed, 0 Changed, 0 Added function
Variables changes summary: 0 Removed, 0 Changed, 0 Added variable
1 Removed function:
'function void PR_EXPERIMENTAL_ONLY_IN_4_17_GetOverlappedIOHandle(void**)' {PR_EXPERIMENTAL_ONLY_IN_4_17_GetOverlappedIOHandle}

View file

@ -0,0 +1,3 @@
Functions changes summary: 0 Removed, 0 Changed (5 filtered out), 0 Added function
Variables changes summary: 0 Removed, 0 Changed, 0 Added variable

View file

@ -1 +1 @@
NSS_3_31_BRANCH NSS_3_34_BRANCH

View file

@ -236,11 +236,14 @@ check_abi()
BASE_NSPR=NSPR_$(head -1 ${HGDIR}/baseline/nss/automation/release/nspr-version.txt | cut -d . -f 1-2 | tr . _)_BRANCH BASE_NSPR=NSPR_$(head -1 ${HGDIR}/baseline/nss/automation/release/nspr-version.txt | cut -d . -f 1-2 | tr . _)_BRANCH
hg clone -u "${BASE_NSPR}" "${HGDIR}/nspr" "${HGDIR}/baseline/nspr" hg clone -u "${BASE_NSPR}" "${HGDIR}/nspr" "${HGDIR}/baseline/nspr"
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
echo "invalid tag ${BASE_NSPR} derived from ${BASE_NSS} automation/release/nspr-version.txt" echo "nonexisting tag ${BASE_NSPR} derived from ${BASE_NSS} automation/release/nspr-version.txt"
return 1 # Assume that version hasn't been released yet, fall back to trunk
pushd "${HGDIR}/baseline/nspr"
hg update default
popd
fi fi
print_log "######## building older NSPR/NSS ########" print_log "######## building baseline NSPR/NSS ########"
pushd ${HGDIR}/baseline/nss pushd ${HGDIR}/baseline/nss
print_log "$ ${MAKE} ${NSS_BUILD_TARGET}" print_log "$ ${MAKE} ${NSS_BUILD_TARGET}"
@ -253,26 +256,44 @@ check_abi()
fi fi
popd popd
ABI_PROBLEM_FOUND=0
ABI_REPORT=${OUTPUTDIR}/abi-diff.txt ABI_REPORT=${OUTPUTDIR}/abi-diff.txt
rm -f ${ABI_REPORT} rm -f ${ABI_REPORT}
PREVDIST=${HGDIR}/baseline/dist PREVDIST=${HGDIR}/baseline/dist
NEWDIST=${HGDIR}/dist NEWDIST=${HGDIR}/dist
ALL_SOs="libfreebl3.so libfreeblpriv3.so libnspr4.so libnss3.so libnssckbi.so libnssdbm3.so libnsssysinit.so libnssutil3.so libplc4.so libplds4.so libsmime3.so libsoftokn3.so libssl3.so" ALL_SOs="libfreebl3.so libfreeblpriv3.so libnspr4.so libnss3.so libnssckbi.so libnssdbm3.so libnsssysinit.so libnssutil3.so libplc4.so libplds4.so libsmime3.so libsoftokn3.so libssl3.so"
for SO in ${ALL_SOs}; do for SO in ${ALL_SOs}; do
if [ ! -f nss/automation/abi-check/expected-report-$SO.txt ]; then if [ ! -f ${HGDIR}/nss/automation/abi-check/expected-report-$SO.txt ]; then
touch nss/automation/abi-check/expected-report-$SO.txt touch ${HGDIR}/nss/automation/abi-check/expected-report-$SO.txt
fi fi
abidiff --hd1 $PREVDIST/public/ --hd2 $NEWDIST/public \ abidiff --hd1 $PREVDIST/public/ --hd2 $NEWDIST/public \
$PREVDIST/*/lib/$SO $NEWDIST/*/lib/$SO \ $PREVDIST/*/lib/$SO $NEWDIST/*/lib/$SO \
> nss/automation/abi-check/new-report-$SO.txt > ${HGDIR}/nss/automation/abi-check/new-report-$SO.txt
diff -u nss/automation/abi-check/expected-report-$SO.txt \ if [ $? -ne 0 ]; then
nss/automation/abi-check/new-report-$SO.txt >> ${ABI_REPORT} ABI_PROBLEM_FOUND=1
print_log "FAILED to run abidiff {$PREVDIST , $NEWDIST} for $SO, or failed writing to ${HGDIR}/nss/automation/abi-check/new-report-$SO.txt"
fi
if [ ! -f ${HGDIR}/nss/automation/abi-check/expected-report-$SO.txt ]; then
ABI_PROBLEM_FOUND=1
print_log "FAILED to access report file: ${HGDIR}/nss/automation/abi-check/expected-report-$SO.txt"
fi
diff -wB -u ${HGDIR}/nss/automation/abi-check/expected-report-$SO.txt \
${HGDIR}/nss/automation/abi-check/new-report-$SO.txt >> ${ABI_REPORT}
if [ ! -f ${ABI_REPORT} ]; then
ABI_PROBLEM_FOUND=1
print_log "FAILED to compare exepcted and new report: ${HGDIR}/nss/automation/abi-check/new-report-$SO.txt"
fi
done done
if [ -s ${ABI_REPORT} ]; then if [ -s ${ABI_REPORT} ]; then
print_log "FAILED: there are new unexpected ABI changes" print_log "FAILED: there are new unexpected ABI changes"
cat ${ABI_REPORT} cat ${ABI_REPORT}
return 1 return 1
elif [ $ABI_PROBLEM_FOUND -ne 0 ]; then
print_log "FAILED: failure executing the ABI checks"
cat ${ABI_REPORT}
return 1
fi fi
return 0 return 0

View file

@ -6,6 +6,8 @@ if [[ $(id -u) -eq 0 ]]; then
exec su worker -c "$0 $*" exec su worker -c "$0 $*"
fi fi
set -e
# Apply clang-format on the provided folder and verify that this doesn't change any file. # 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. # 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. # Any differences between formatted and unformatted files is printed to stdout to give a hint what's wrong.
@ -21,17 +23,16 @@ blacklist=(
"./lib/zlib" \ "./lib/zlib" \
"./lib/sqlite" \ "./lib/sqlite" \
"./gtests/google_test" \ "./gtests/google_test" \
"./.hg" \
"./out" \ "./out" \
) )
top="$(dirname $0)/../.." top=$(cd "$(dirname $0)/../.."; pwd -P)
cd "$top"
if [ $# -gt 0 ]; then if [ $# -gt 0 ]; then
dirs=("$@") dirs=("$@")
else else
dirs=($(find . -maxdepth 2 -mindepth 1 -type d ! -path . \( ! -regex '.*/' \))) cd "$top"
dirs=($(find . -maxdepth 2 -mindepth 1 -type d ! -path '*/.*' -print))
fi fi
format_folder() format_folder()
@ -49,17 +50,17 @@ for dir in "${dirs[@]}"; do
if format_folder "$dir"; then if format_folder "$dir"; then
c="${dir//[^\/]}" c="${dir//[^\/]}"
echo "formatting $dir ..." echo "formatting $dir ..."
depth="" depth=()
if [ "${#c}" == "1" ]; then if [ "${#c}" == "1" ]; then
depth="-maxdepth 1" depth+=(-maxdepth 1)
fi fi
find "$dir" $depth -type f \( -name '*.[ch]' -o -name '*.cc' \) -exec clang-format -i {} \+ find "$dir" "${depth[@]}" -type f \( -name '*.[ch]' -o -name '*.cc' \) -exec clang-format -i {} \+
fi fi
done done
TMPFILE=$(mktemp /tmp/$(basename $0).XXXXXX) TMPFILE=$(mktemp /tmp/$(basename $0).XXXXXX)
trap 'rm $TMPFILE' exit trap 'rm -f $TMPFILE' exit
if (cd $(dirname $0); hg root >/dev/null 2>&1); then if [[ -d "$top/.hg" ]]; then
hg diff --git "$top" | tee $TMPFILE hg diff --git "$top" | tee $TMPFILE
else else
git -C "$top" diff | tee $TMPFILE git -C "$top" diff | tee $TMPFILE

View file

@ -17,8 +17,8 @@ apt_packages+=('locales')
apt-get install -y --no-install-recommends ${apt_packages[@]} apt-get install -y --no-install-recommends ${apt_packages[@]}
# Download clang. # Download clang.
curl -L http://releases.llvm.org/3.9.1/clang+llvm-3.9.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz -o clang.tar.xz curl -L https://releases.llvm.org/3.9.1/clang+llvm-3.9.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz -o clang.tar.xz
curl -L http://releases.llvm.org/3.9.1/clang+llvm-3.9.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz.sig -o clang.tar.xz.sig curl -L https://releases.llvm.org/3.9.1/clang+llvm-3.9.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz.sig -o clang.tar.xz.sig
# Verify the signature. # Verify the signature.
gpg --keyserver pool.sks-keyservers.net --recv-keys B6C8F98282B944E3B0D5C2530FC3042E345AD05D gpg --keyserver pool.sks-keyservers.net --recv-keys B6C8F98282B944E3B0D5C2530FC3042E345AD05D
gpg --verify clang.tar.xz.sig gpg --verify clang.tar.xz.sig

View file

@ -1,4 +1,4 @@
4.16 4.18
# The first line of this file must contain the human readable NSPR # The first line of this file must contain the human readable NSPR
# version number, which is the minimum required version of NSPR # version number, which is the minimum required version of NSPR

View file

@ -25,8 +25,8 @@ apt-get -y update
apt-get install -y --no-install-recommends ${apt_packages[@]} apt-get install -y --no-install-recommends ${apt_packages[@]}
# Download clang. # Download clang.
curl -LO http://releases.llvm.org/3.9.1/clang+llvm-3.9.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz curl -LO https://releases.llvm.org/3.9.1/clang+llvm-3.9.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz
curl -LO http://releases.llvm.org/3.9.1/clang+llvm-3.9.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz.sig curl -LO https://releases.llvm.org/3.9.1/clang+llvm-3.9.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz.sig
# Verify the signature. # Verify the signature.
gpg --keyserver pool.sks-keyservers.net --recv-keys B6C8F98282B944E3B0D5C2530FC3042E345AD05D gpg --keyserver pool.sks-keyservers.net --recv-keys B6C8F98282B944E3B0D5C2530FC3042E345AD05D
gpg --verify *.tar.xz.sig gpg --verify *.tar.xz.sig

View file

@ -12,6 +12,9 @@ RUN chmod +x /home/worker/bin/*
ADD setup.sh /tmp/setup.sh ADD setup.sh /tmp/setup.sh
RUN bash /tmp/setup.sh RUN bash /tmp/setup.sh
# Change user.
USER worker
# Env variables. # Env variables.
ENV HOME /home/worker ENV HOME /home/worker
ENV SHELL /bin/bash ENV SHELL /bin/bash

View file

@ -2,11 +2,6 @@
set -v -e -x 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. # Default values for testing.
REVISION=${NSS_HEAD_REVISION:-default} REVISION=${NSS_HEAD_REVISION:-default}
REPOSITORY=${NSS_HEAD_REPOSITORY:-https://hg.mozilla.org/projects/nss} REPOSITORY=${NSS_HEAD_REPOSITORY:-https://hg.mozilla.org/projects/nss}

View file

@ -0,0 +1,30 @@
FROM ubuntu:14.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
# Set a default command for debugging.
CMD ["/bin/bash", "--login"]

View file

@ -0,0 +1,20 @@
#!/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

View file

@ -0,0 +1,30 @@
#!/usr/bin/env bash
set -v -e -x
# Update packages.
export DEBIAN_FRONTEND=noninteractive
apt-get -y update && apt-get -y upgrade
apt_packages=()
apt_packages+=('ca-certificates')
apt_packages+=('g++-4.4')
apt_packages+=('gcc-4.4')
apt_packages+=('locales')
apt_packages+=('make')
apt_packages+=('mercurial')
apt_packages+=('zlib1g-dev')
# Install packages.
apt-get -y update
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

View file

@ -0,0 +1,30 @@
FROM ubuntu:xenial
MAINTAINER Franziskus Kiefer <franziskuskiefer@gmail.com>
# Based on the HACL* image from Benjamin Beurdouche and
# the original F* formula with Daniel Fabian
# Pinned versions of HACL* (F* and KreMLin are pinned as submodules)
ENV haclrepo https://github.com/mitls/hacl-star.git
# Define versions of dependencies
ENV opamv 4.04.2
ENV haclversion dcd48329d535727dbde93877b124c5ec4a7a2b20
# Install required packages and set versions
ADD setup.sh /tmp/setup.sh
RUN bash /tmp/setup.sh
# Create user, add scripts.
RUN useradd -ms /bin/bash worker
WORKDIR /home/worker
ADD bin /home/worker/bin
RUN chmod +x /home/worker/bin/*
USER worker
# Build F*, HACL*, verify. Install a few more dependencies.
ENV OPAMYES true
ENV PATH "/home/worker/hacl-star/dependencies/z3/bin:$PATH"
ADD setup-user.sh /tmp/setup-user.sh
ADD license.txt /tmp/license.txt
RUN bash /tmp/setup-user.sh

View file

@ -0,0 +1,20 @@
#!/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

View file

@ -0,0 +1,15 @@
/* Copyright 2016-2017 INRIA and Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

View file

@ -0,0 +1,26 @@
#!/usr/bin/env bash
set -v -e -x
# Prepare build (OCaml packages)
opam init
echo ". /home/worker/.opam/opam-init/init.sh > /dev/null 2> /dev/null || true" >> .bashrc
opam switch -v ${opamv}
opam install ocamlfind batteries sqlite3 fileutils yojson ppx_deriving_yojson zarith pprint menhir ulex process fix wasm stdint
# Get the HACL* code
git clone ${haclrepo} hacl-star
git -C hacl-star checkout ${haclversion}
# Prepare submodules, and build, verify, test, and extract c code
# This caches the extracted c code (pins the HACL* version). All we need to do
# on CI now is comparing the code in this docker image with the one in NSS.
opam config exec -- make -C hacl-star prepare -j$(nproc)
make -C hacl-star verify-nss -j$(nproc)
make -C hacl-star -f Makefile.build snapshots/nss -j$(nproc)
KOPTS="-funroll-loops 5" make -C hacl-star/code/curve25519 test -j$(nproc)
make -C hacl-star/code/salsa-family test -j$(nproc)
make -C hacl-star/code/poly1305 test -j$(nproc)
# Cleanup.
rm -rf ~/.ccache ~/.cache

View file

@ -0,0 +1,30 @@
#!/usr/bin/env bash
set -v -e -x
# Update packages.
export DEBIAN_FRONTEND=noninteractive
apt-get -qq update
apt-get install --yes libssl-dev libsqlite3-dev g++-5 gcc-5 m4 make opam pkg-config python libgmp3-dev cmake curl libtool-bin autoconf wget locales
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 200
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 200
# Get clang-format-3.9
curl -LO https://releases.llvm.org/3.9.1/clang+llvm-3.9.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz
curl -LO https://releases.llvm.org/3.9.1/clang+llvm-3.9.1-x86_64-linux-gnu-ubuntu-16.04.tar.xz.sig
# Verify the signature.
gpg --keyserver pool.sks-keyservers.net --recv-keys B6C8F98282B944E3B0D5C2530FC3042E345AD05D
gpg --verify *.tar.xz.sig
# Install into /usr/local/.
tar xJvf *.tar.xz -C /usr/local --strip-components=1
# Cleanup.
rm *.tar.xz*
locale-gen en_US.UTF-8
dpkg-reconfigure locales
# Cleanup.
rm -rf ~/.ccache ~/.cache
apt-get autoremove -y
apt-get clean
apt-get autoclean

View file

@ -48,8 +48,8 @@ apt-get -y update
apt-get install -y --no-install-recommends ${apt_packages[@]} apt-get install -y --no-install-recommends ${apt_packages[@]}
# Download clang. # Download clang.
curl -LO http://releases.llvm.org/4.0.0/clang+llvm-4.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz curl -LO https://releases.llvm.org/4.0.0/clang+llvm-4.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz
curl -LO http://releases.llvm.org/4.0.0/clang+llvm-4.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz.sig curl -LO https://releases.llvm.org/4.0.0/clang+llvm-4.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz.sig
# Verify the signature. # Verify the signature.
gpg --keyserver pool.sks-keyservers.net --recv-keys B6C8F98282B944E3B0D5C2530FC3042E345AD05D gpg --keyserver pool.sks-keyservers.net --recv-keys B6C8F98282B944E3B0D5C2530FC3042E345AD05D
gpg --verify *.tar.xz.sig gpg --verify *.tar.xz.sig

View file

@ -27,14 +27,24 @@ function collectFilesInDirectory(dir) {
}); });
} }
// Compute a context hash for the given context path. // A list of hashes for each file in the given path.
export default function (context_path) { function collectFileHashes(context_path) {
let root = path.join(__dirname, "../../../.."); let root = path.join(__dirname, "../../../..");
let dir = path.join(root, context_path); let dir = path.join(root, context_path);
let files = collectFilesInDirectory(dir).sort(); let files = collectFilesInDirectory(dir).sort();
let hashes = files.map(file => {
return files.map(file => {
return sha256(file + "|" + fs.readFileSync(file, "utf-8")); return sha256(file + "|" + fs.readFileSync(file, "utf-8"));
}); });
}
// Compute a context hash for the given context path.
export default function (context_path) {
// Regenerate all images when the image_builder changes.
let hashes = collectFileHashes("automation/taskcluster/image_builder");
// Regenerate images when the image itself changes.
hashes = hashes.concat(collectFileHashes(context_path));
// Generate a new prefix every month to ensure the image stays buildable. // Generate a new prefix every month to ensure the image stays buildable.
let now = new Date(); let now = new Date();

View file

@ -15,15 +15,29 @@ const LINUX_CLANG39_IMAGE = {
path: "automation/taskcluster/docker-clang-3.9" path: "automation/taskcluster/docker-clang-3.9"
}; };
const LINUX_GCC44_IMAGE = {
name: "linux-gcc-4.4",
path: "automation/taskcluster/docker-gcc-4.4"
};
const FUZZ_IMAGE = { const FUZZ_IMAGE = {
name: "fuzz", name: "fuzz",
path: "automation/taskcluster/docker-fuzz" path: "automation/taskcluster/docker-fuzz"
}; };
const HACL_GEN_IMAGE = {
name: "hacl",
path: "automation/taskcluster/docker-hacl"
};
const WINDOWS_CHECKOUT_CMD = const WINDOWS_CHECKOUT_CMD =
"bash -c \"hg clone -r $NSS_HEAD_REVISION $NSS_HEAD_REPOSITORY nss || " + "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 2; hg clone -r $NSS_HEAD_REVISION $NSS_HEAD_REPOSITORY nss) || " +
"(sleep 5; hg clone -r $NSS_HEAD_REVISION $NSS_HEAD_REPOSITORY nss)\""; "(sleep 5; hg clone -r $NSS_HEAD_REVISION $NSS_HEAD_REPOSITORY nss)\"";
const MAC_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)"];
/*****************************************************************************/ /*****************************************************************************/
@ -51,6 +65,15 @@ queue.filter(task => {
if (task.platform == "aarch64") { if (task.platform == "aarch64") {
return false; return false;
} }
// No mac
if (task.platform == "mac") {
return false;
}
}
if (task.tests == "fips" && task.platform == "mac") {
return false;
} }
// Only old make builds have -Ddisable_libpkix=0 and can run chain tests. // Only old make builds have -Ddisable_libpkix=0 and can run chain tests.
@ -59,8 +82,8 @@ queue.filter(task => {
} }
if (task.group == "Test") { if (task.group == "Test") {
// Don't run test builds on old make platforms // Don't run test builds on old make platforms, and not for fips gyp.
if (task.collection == "make") { if (task.collection == "make" || task.collection == "fips") {
return false; return false;
} }
} }
@ -78,11 +101,19 @@ queue.filter(task => {
queue.map(task => { queue.map(task => {
if (task.collection == "asan") { if (task.collection == "asan") {
// CRMF and FIPS tests still leak, unfortunately. // CRMF and FIPS tests still leak, unfortunately.
if (task.tests == "crmf" || task.tests == "fips") { if (task.tests == "crmf") {
task.env.ASAN_OPTIONS = "detect_leaks=0"; task.env.ASAN_OPTIONS = "detect_leaks=0";
} }
} }
// We don't run FIPS SSL tests
if (task.tests == "ssl") {
if (!task.env) {
task.env = {};
}
task.env.NSS_SSL_TESTS = "crl iopr policy";
}
// Windows is slow. // Windows is slow.
if (task.platform == "windows2012-64" && task.tests == "chains") { if (task.platform == "windows2012-64" && task.tests == "chains") {
task.maxRunTime = 7200; task.maxRunTime = 7200;
@ -128,6 +159,18 @@ export default async function main() {
], ],
}); });
await scheduleLinux("Linux 64 (opt, make)", {
env: {USE_64: "1", BUILD_OPT: "1"},
platform: "linux64",
image: LINUX_IMAGE,
collection: "make",
command: [
"/bin/bash",
"-c",
"bin/checkout.sh && nss/automation/taskcluster/scripts/build.sh"
],
});
await scheduleLinux("Linux 32 (debug, make)", { await scheduleLinux("Linux 32 (debug, make)", {
platform: "linux32", platform: "linux32",
image: LINUX_IMAGE, image: LINUX_IMAGE,
@ -153,6 +196,12 @@ export default async function main() {
features: ["allowPtrace"], features: ["allowPtrace"],
}, "--ubsan --asan"); }, "--ubsan --asan");
await scheduleLinux("Linux 64 (FIPS opt)", {
platform: "linux64",
collection: "fips",
image: LINUX_IMAGE,
}, "--enable-fips --opt");
await scheduleWindows("Windows 2012 64 (debug, make)", { await scheduleWindows("Windows 2012 64 (debug, make)", {
platform: "windows2012-64", platform: "windows2012-64",
collection: "make", collection: "make",
@ -216,6 +265,70 @@ export default async function main() {
collection: "opt", collection: "opt",
}, aarch64_base) }, aarch64_base)
); );
await scheduleMac("Mac (opt)", {collection: "opt"}, "--opt");
await scheduleMac("Mac (debug)", {collection: "debug"});
}
async function scheduleMac(name, base, args = "") {
let mac_base = merge(base, {
env: {
PATH: "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
NSS_TASKCLUSTER_MAC: "1",
DOMSUF: "localdomain",
HOST: "localhost",
},
provisioner: "localprovisioner",
workerType: "nss-macos-10-12",
platform: "mac"
});
// Build base definition.
let build_base = merge({
command: [
MAC_CHECKOUT_CMD,
["bash", "-c",
"nss/automation/taskcluster/scripts/build_gyp.sh", args]
],
provisioner: "localprovisioner",
workerType: "nss-macos-10-12",
platform: "mac",
maxRunTime: 7200,
artifacts: [{
expires: 24 * 7,
type: "directory",
path: "public"
}],
kind: "build",
symbol: "B"
}, mac_base);
// The task that builds NSPR+NSS.
let task_build = queue.scheduleTask(merge(build_base, {name}));
// The task that generates certificates.
let task_cert = queue.scheduleTask(merge(build_base, {
name: "Certificates",
command: [
MAC_CHECKOUT_CMD,
["bash", "-c",
"nss/automation/taskcluster/scripts/gen_certs.sh"]
],
parent: task_build,
symbol: "Certs"
}));
// Schedule tests.
scheduleTests(task_build, task_cert, merge(mac_base, {
command: [
MAC_CHECKOUT_CMD,
["bash", "-c",
"nss/automation/taskcluster/scripts/run_tests.sh"]
]
}));
return queue.submit();
} }
/*****************************************************************************/ /*****************************************************************************/
@ -242,6 +355,45 @@ async function scheduleLinux(name, base, args = "") {
// The task that builds NSPR+NSS. // The task that builds NSPR+NSS.
let task_build = queue.scheduleTask(merge(build_base, {name})); let task_build = queue.scheduleTask(merge(build_base, {name}));
// Make builds run FIPS tests, which need an extra FIPS build.
if (base.collection == "make") {
let extra_build = queue.scheduleTask(merge(build_base, {
env: { NSS_FORCE_FIPS: "1" },
group: "FIPS",
name: `${name} w/ NSS_FORCE_FIPS`
}));
// The task that generates certificates.
let task_cert = queue.scheduleTask(merge(build_base, {
name: "Certificates",
command: [
"/bin/bash",
"-c",
"bin/checkout.sh && nss/automation/taskcluster/scripts/gen_certs.sh"
],
parent: extra_build,
symbol: "Certs-F",
group: "FIPS",
}));
// Schedule FIPS tests.
queue.scheduleTask(merge(base, {
parent: task_cert,
name: "FIPS",
command: [
"/bin/bash",
"-c",
"bin/checkout.sh && nss/automation/taskcluster/scripts/run_tests.sh"
],
cycle: "standard",
kind: "test",
name: "FIPS tests",
symbol: "Tests-F",
tests: "fips",
group: "FIPS"
}));
}
// The task that generates certificates. // The task that generates certificates.
let task_cert = queue.scheduleTask(merge(build_base, { let task_cert = queue.scheduleTask(merge(build_base, {
name: "Certificates", name: "Certificates",
@ -274,6 +426,26 @@ async function scheduleLinux(name, base, args = "") {
symbol: "clang-4.0" symbol: "clang-4.0"
})); }));
queue.scheduleTask(merge(extra_base, {
name: `${name} w/ gcc-4.4`,
image: LINUX_GCC44_IMAGE,
env: {
USE_64: "1",
CC: "gcc-4.4",
CCC: "g++-4.4",
// gcc-4.6 introduced nullptr.
NSS_DISABLE_GTESTS: "1",
},
// Use the old Makefile-based build system, GYP doesn't have a proper GCC
// version check for __int128 support. It's mainly meant to cover RHEL6.
command: [
"/bin/bash",
"-c",
"bin/checkout.sh && nss/automation/taskcluster/scripts/build.sh",
],
symbol: "gcc-4.4"
}));
queue.scheduleTask(merge(extra_base, { queue.scheduleTask(merge(extra_base, {
name: `${name} w/ gcc-4.8`, name: `${name} w/ gcc-4.8`,
env: { env: {
@ -403,12 +575,13 @@ async function scheduleFuzzing() {
// Schedule MPI fuzzing runs. // Schedule MPI fuzzing runs.
let mpi_base = merge(run_base, {group: "MPI"}); let mpi_base = merge(run_base, {group: "MPI"});
let mpi_names = ["add", "addmod", "div", "expmod", "mod", "mulmod", "sqr", let mpi_names = ["add", "addmod", "div", "mod", "mulmod", "sqr",
"sqrmod", "sub", "submod"]; "sqrmod", "sub", "submod"];
for (let name of mpi_names) { for (let name of mpi_names) {
scheduleFuzzingRun(mpi_base, `MPI (${name})`, `mpi-${name}`, 4096, name); scheduleFuzzingRun(mpi_base, `MPI (${name})`, `mpi-${name}`, 4096, name);
} }
scheduleFuzzingRun(mpi_base, `MPI (invmod)`, `mpi-invmod`, 256, "invmod"); scheduleFuzzingRun(mpi_base, `MPI (invmod)`, `mpi-invmod`, 256, "invmod");
scheduleFuzzingRun(mpi_base, `MPI (expmod)`, `mpi-expmod`, 2048, "expmod");
// Schedule TLS fuzzing runs (non-fuzzing mode). // Schedule TLS fuzzing runs (non-fuzzing mode).
let tls_base = merge(run_base, {group: "TLS"}); let tls_base = merge(run_base, {group: "TLS"});
@ -625,6 +798,43 @@ async function scheduleWindows(name, base, build_script) {
symbol: "B" symbol: "B"
}); });
// Make builds run FIPS tests, which need an extra FIPS build.
if (base.collection == "make") {
let extra_build = queue.scheduleTask(merge(build_base, {
env: { NSS_FORCE_FIPS: "1" },
group: "FIPS",
name: `${name} w/ NSS_FORCE_FIPS`
}));
// The task that generates certificates.
let task_cert = queue.scheduleTask(merge(build_base, {
name: "Certificates",
command: [
WINDOWS_CHECKOUT_CMD,
"bash -c nss/automation/taskcluster/windows/gen_certs.sh"
],
parent: extra_build,
symbol: "Certs-F",
group: "FIPS",
}));
// Schedule FIPS tests.
queue.scheduleTask(merge(base, {
parent: task_cert,
name: "FIPS",
command: [
WINDOWS_CHECKOUT_CMD,
"bash -c nss/automation/taskcluster/windows/run_tests.sh"
],
cycle: "standard",
kind: "test",
name: "FIPS tests",
symbol: "Tests-F",
tests: "fips",
group: "FIPS"
}));
}
// The task that builds NSPR+NSS. // The task that builds NSPR+NSS.
let task_build = queue.scheduleTask(merge(build_base, {name})); let task_build = queue.scheduleTask(merge(build_base, {name}));
@ -702,9 +912,6 @@ function scheduleTests(task_build, task_cert, test_base) {
queue.scheduleTask(merge(cert_base, { queue.scheduleTask(merge(cert_base, {
name: "DB tests", symbol: "DB", tests: "dbtests" name: "DB tests", symbol: "DB", tests: "dbtests"
})); }));
queue.scheduleTask(merge(cert_base, {
name: "FIPS tests", symbol: "FIPS", tests: "fips"
}));
queue.scheduleTask(merge(cert_base, { queue.scheduleTask(merge(cert_base, {
name: "Merge tests", symbol: "Merge", tests: "merge" name: "Merge tests", symbol: "Merge", tests: "merge"
})); }));
@ -773,5 +980,16 @@ async function scheduleTools() {
] ]
})); }));
queue.scheduleTask(merge(base, {
symbol: "hacl",
name: "hacl",
image: HACL_GEN_IMAGE,
command: [
"/bin/bash",
"-c",
"bin/checkout.sh && nss/automation/taskcluster/scripts/run_hacl.sh"
]
}));
return queue.submit(); return queue.submit();
} }

View file

@ -31,13 +31,11 @@ export async function buildTask({name, path}) {
return { return {
name: "Image Builder", name: "Image Builder",
image: "taskcluster/image_builder:0.1.5", image: "nssdev/image_builder:0.1.5",
routes: ["index." + ns], routes: ["index." + ns],
env: { env: {
HEAD_REPOSITORY: process.env.NSS_HEAD_REPOSITORY, NSS_HEAD_REPOSITORY: process.env.NSS_HEAD_REPOSITORY,
BASE_REPOSITORY: process.env.NSS_HEAD_REPOSITORY, NSS_HEAD_REVISION: process.env.NSS_HEAD_REVISION,
HEAD_REV: process.env.NSS_HEAD_REVISION,
HEAD_REF: process.env.NSS_HEAD_REVISION,
PROJECT: process.env.TC_PROJECT, PROJECT: process.env.TC_PROJECT,
CONTEXT_PATH: path, CONTEXT_PATH: path,
HASH: hash HASH: hash
@ -52,10 +50,11 @@ export async function buildTask({name, path}) {
command: [ command: [
"/bin/bash", "/bin/bash",
"-c", "-c",
"/home/worker/bin/build_image.sh" "bin/checkout.sh && nss/automation/taskcluster/scripts/build_image.sh"
], ],
platform: "nss-decision", platform: "nss-decision",
features: ["dind"], features: ["dind"],
maxRunTime: 7200,
kind: "build", kind: "build",
symbol: "I" symbol: "I"
}; };

View file

@ -22,10 +22,10 @@ function parseOptions(opts) {
} }
// Parse platforms. // Parse platforms.
let allPlatforms = ["linux", "linux64", "linux64-asan", let allPlatforms = ["linux", "linux64", "linux64-asan", "linux64-fips",
"win", "win64", "win-make", "win64-make", "win", "win64", "win-make", "win64-make",
"linux64-make", "linux-make", "linux-fuzz", "linux64-make", "linux-make", "linux-fuzz",
"linux64-fuzz", "aarch64"]; "linux64-fuzz", "aarch64", "mac"];
let platforms = intersect(opts.platform.split(/\s*,\s*/), allPlatforms); let platforms = intersect(opts.platform.split(/\s*,\s*/), allPlatforms);
// If the given value is nonsense or "none" default to all platforms. // If the given value is nonsense or "none" default to all platforms.
@ -51,7 +51,7 @@ function parseOptions(opts) {
} }
// Parse tools. // Parse tools.
let allTools = ["clang-format", "scan-build"]; let allTools = ["clang-format", "scan-build", "hacl"];
let tools = intersect(opts.tools.split(/\s*,\s*/), allTools); let tools = intersect(opts.tools.split(/\s*,\s*/), allTools);
// If the given value is "all" run all tools. // If the given value is "all" run all tools.
@ -111,6 +111,7 @@ function filter(opts) {
"linux": "linux32", "linux": "linux32",
"linux-fuzz": "linux32", "linux-fuzz": "linux32",
"linux64-asan": "linux64", "linux64-asan": "linux64",
"linux64-fips": "linux64",
"linux64-fuzz": "linux64", "linux64-fuzz": "linux64",
"linux64-make": "linux64", "linux64-make": "linux64",
"linux-make": "linux32", "linux-make": "linux32",
@ -126,6 +127,8 @@ function filter(opts) {
// Additional checks. // Additional checks.
if (platform == "linux64-asan") { if (platform == "linux64-asan") {
keep &= coll("asan"); keep &= coll("asan");
} else if (platform == "linux64-fips") {
keep &= coll("fips");
} else if (platform == "linux64-make" || platform == "linux-make" || } else if (platform == "linux64-make" || platform == "linux-make" ||
platform == "win64-make" || platform == "win-make") { platform == "win64-make" || platform == "win-make") {
keep &= coll("make"); keep &= coll("make");

View file

@ -0,0 +1,23 @@
FROM ubuntu:16.04
MAINTAINER Tim Taubert <ttaubert@mozilla.com>
WORKDIR /home/worker
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && apt-get install -y apt-transport-https apt-utils
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9 && \
sh -c "echo deb https://get.docker.io/ubuntu docker main \
> /etc/apt/sources.list.d/docker.list"
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 41BD8711B1F0EC2B0D85B91CF59CE3A8323293EE && \
sh -c "echo deb http://ppa.launchpad.net/mercurial-ppa/releases/ubuntu xenial main \
> /etc/apt/sources.list.d/mercurial.list"
RUN apt-get update && apt-get install -y \
lxc-docker-1.6.1 \
mercurial
ADD bin /home/worker/bin
RUN chmod +x /home/worker/bin/*
# Set a default command useful for debugging
CMD ["/bin/bash", "--login"]

View file

@ -0,0 +1 @@
0.1.5

View file

@ -0,0 +1,15 @@
#!/usr/bin/env bash
set -v -e -x
# 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

View file

@ -9,5 +9,10 @@ hg_clone https://hg.mozilla.org/projects/nspr ./nspr default
nss/build.sh -g -v "$@" nss/build.sh -g -v "$@"
# Package. # Package.
if [[ $(uname) = "Darwin" ]]; then
mkdir -p public
tar cvfjh public/dist.tar.bz2 dist
else
mkdir artifacts mkdir artifacts
tar cvfjh artifacts/dist.tar.bz2 dist tar cvfjh artifacts/dist.tar.bz2 dist
fi

View file

@ -0,0 +1,24 @@
#!/bin/bash -vex
set -x -e -v
# Prefix errors with taskcluster error prefix so that they are parsed by Treeherder
raise_error() {
echo
echo "[taskcluster-image-build:error] $1"
exit 1
}
# Ensure that the PROJECT is specified so the image can be indexed
test -n "$PROJECT" || raise_error "Project must be provided."
test -n "$HASH" || raise_error "Context Hash must be provided."
CONTEXT_PATH=/home/worker/nss/$CONTEXT_PATH
test -d $CONTEXT_PATH || raise_error "Context Path $CONTEXT_PATH does not exist."
test -f "$CONTEXT_PATH/Dockerfile" || raise_error "Dockerfile must be present in $CONTEXT_PATH."
docker build -t $PROJECT:$HASH $CONTEXT_PATH
mkdir /artifacts
docker save $PROJECT:$HASH > /artifacts/image.tar

View file

@ -12,5 +12,10 @@ NSS_TESTS=cert NSS_CYCLES="standard pkix sharedb" $(dirname $0)/run_tests.sh
echo 1 > tests_results/security/localhost echo 1 > tests_results/security/localhost
# Package. # Package.
if [[ $(uname) = "Darwin" ]]; then
mkdir -p public
tar cvfjh public/dist.tar.bz2 dist tests_results
else
mkdir artifacts mkdir artifacts
tar cvfjh artifacts/dist.tar.bz2 dist tests_results tar cvfjh artifacts/dist.tar.bz2 dist tests_results
fi

View file

@ -0,0 +1,40 @@
#!/usr/bin/env bash
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
set -e -x -v
# The docker image this is running in has the HACL* and NSS sources.
# The extracted C code from HACL* is already generated and the HACL* tests were
# successfully executed.
# Verify Poly1305 (doesn't work in docker image build)
make verify -C ~/hacl-star/code/poly1305 -j$(nproc)
# Add license header to specs
spec_files=($(find ~/hacl-star/specs -type f -name '*.fst'))
for f in "${spec_files[@]}"; do
cat /tmp/license.txt "$f" > /tmp/tmpfile && mv /tmp/tmpfile "$f"
done
# Format the extracted C code.
cd ~/hacl-star/snapshots/nss
cp ~/nss/.clang-format .
find . -type f -name '*.[ch]' -exec clang-format -i {} \+
# These diff commands will return 1 if there are differences and stop the script.
files=($(find ~/nss/lib/freebl/verified/ -type f -name '*.[ch]'))
for f in "${files[@]}"; do
diff $f $(basename "$f")
done
# Check that the specs didn't change either.
cd ~/hacl-star/specs
files=($(find ~/nss/lib/freebl/verified/specs -type f))
for f in "${files[@]}"; do
diff $f $(basename "$f")
done

View file

@ -23,16 +23,10 @@ split_util() {
# Copy everything. # Copy everything.
cp -R $nssdir $dstdir cp -R $nssdir $dstdir
# Skip gtests when building.
sed '/^DIRS = /s/ cpputil gtests$//' $nssdir/manifest.mn > $dstdir/manifest.mn-t && mv $dstdir/manifest.mn-t $dstdir/manifest.mn
# Remove subdirectories that we don't want. # Remove subdirectories that we don't want.
rm -rf $dstdir/cmd rm -rf $dstdir/cmd
rm -rf $dstdir/tests
rm -rf $dstdir/lib rm -rf $dstdir/lib
rm -rf $dstdir/automation rm -rf $dstdir/automation
rm -rf $dstdir/gtests
rm -rf $dstdir/cpputil
rm -rf $dstdir/doc rm -rf $dstdir/doc
# Start with an empty cmd lib directories to be filled selectively. # Start with an empty cmd lib directories to be filled selectively.

View file

@ -1,10 +1,10 @@
[ [
{ {
"version": "Visual Studio 2015 Update 3 14.0.25425.01 / SDK 10.0.14393.0", "version": "Visual Studio 2017 15.4.2 / SDK 10.0.15063.0",
"size": 326656969, "size": 303146863,
"digest": "babc414ffc0457d27f5a1ed24a8e4873afbe2f1c1a4075469a27c005e1babc3b2a788f643f825efedff95b79686664c67ec4340ed535487168a3482e68559bc7", "digest": "18700889e6b5e81613b9cf57ce4e0d46a6ee45bb4c5c33bae2604a5275326128775b8a032a1eb178c5db973746d565340c4e36d98375789e1d5bd836ab16ba58",
"algorithm": "sha512", "algorithm": "sha512",
"filename": "vs2015u3.zip", "filename": "vs2017_15.4.2.zip",
"unpack": true "unpack": true
}, },
{ {

View file

@ -2,12 +2,12 @@
set -v -e -x set -v -e -x
export VSPATH="$(pwd)/vs2015u3" export VSPATH="$(pwd)/vs2017_15.4.2"
export NINJA_PATH="$(pwd)/ninja/bin" export NINJA_PATH="$(pwd)/ninja/bin"
export WINDOWSSDKDIR="${VSPATH}/SDK" export WINDOWSSDKDIR="${VSPATH}/SDK"
export VS90COMNTOOLS="${VSPATH}/VC" export VS90COMNTOOLS="${VSPATH}/VC"
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 INCLUDE="${VSPATH}/VC/include:${VSPATH}/SDK/Include/10.0.15063.0/ucrt:${VSPATH}/SDK/Include/10.0.15063.0/shared:${VSPATH}/SDK/Include/10.0.15063.0/um"
# Usage: hg_clone repo dir [revision=@] # Usage: hg_clone repo dir [revision=@]
hg_clone() { hg_clone() {
@ -23,4 +23,4 @@ hg_clone() {
} }
hg_clone https://hg.mozilla.org/build/tools tools default 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 tools/scripts/tooltool/tooltool_wrapper.sh $(dirname $0)/releng.manifest https://tooltool.mozilla-releng.net/ 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

View file

@ -4,7 +4,7 @@ set -v -e -x
source $(dirname $0)/setup.sh source $(dirname $0)/setup.sh
export WIN32_REDIST_DIR="${VSPATH}/VC/redist/x86/Microsoft.VC140.CRT" export WIN32_REDIST_DIR="${VSPATH}/VC/redist/x86/Microsoft.VC141.CRT"
export WIN_UCRT_REDIST_DIR="${VSPATH}/SDK/Redist/ucrt/DLLs/x86" export WIN_UCRT_REDIST_DIR="${VSPATH}/SDK/Redist/ucrt/DLLs/x86"
export PATH="${NINJA_PATH}:${VSPATH}/VC/bin/amd64_x86:${VSPATH}/VC/bin/amd64:${VSPATH}/VC/bin:${VSPATH}/SDK/bin/x86:${VSPATH}/SDK/bin/x64:${VSPATH}/VC/redist/x86/Microsoft.VC140.CRT:${VSPATH}/VC/redist/x64/Microsoft.VC140.CRT:${VSPATH}/SDK/Redist/ucrt/DLLs/x86:${VSPATH}/SDK/Redist/ucrt/DLLs/x64:${PATH}" export PATH="${NINJA_PATH}:${VSPATH}/VC/bin/Hostx64/x86:${VSPATH}/VC/bin/Hostx64/x64:${VSPATH}/VC/Hostx86/x86:${VSPATH}/SDK/bin/10.0.15063.0/x64:${VSPATH}/VC/redist/x86/Microsoft.VC141.CRT:${VSPATH}/SDK/Redist/ucrt/DLLs/x86:${PATH}"
export LIB="${VSPATH}/VC/lib:${VSPATH}/SDK/lib/10.0.14393.0/ucrt/x86:${VSPATH}/SDK/lib/10.0.14393.0/um/x86" export LIB="${VSPATH}/VC/lib/x86:${VSPATH}/SDK/lib/10.0.15063.0/ucrt/x86:${VSPATH}/SDK/lib/10.0.15063.0/um/x86"

View file

@ -4,7 +4,7 @@ set -v -e -x
source $(dirname $0)/setup.sh source $(dirname $0)/setup.sh
export WIN32_REDIST_DIR="${VSPATH}/VC/redist/x64/Microsoft.VC140.CRT" export WIN32_REDIST_DIR="${VSPATH}/VC/redist/x64/Microsoft.VC141.CRT"
export WIN_UCRT_REDIST_DIR="${VSPATH}/SDK/Redist/ucrt/DLLs/x64" export WIN_UCRT_REDIST_DIR="${VSPATH}/SDK/Redist/ucrt/DLLs/x64"
export PATH="${NINJA_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 PATH="${NINJA_PATH}:${VSPATH}/VC/bin/Hostx64/x64:${VSPATH}/VC/bin/Hostx86/x86:${VSPATH}/SDK/bin/10.0.15063.0/x64:${VSPATH}/VC/redist/x64/Microsoft.VC141.CRT:${VSPATH}/SDK/Redist/ucrt/DLLs/x64:${PATH}"
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 LIB="${VSPATH}/VC/lib/x64:${VSPATH}/SDK/lib/10.0.15063.0/ucrt/x64:${VSPATH}/SDK/lib/10.0.15063.0/um/x64"

View file

@ -68,11 +68,14 @@ fi
while [ $# -gt 0 ]; do while [ $# -gt 0 ]; do
case $1 in case $1 in
-c) clean=1 ;; -c) clean=1 ;;
-cc) clean_only=1 ;;
--gyp|-g) rebuild_gyp=1 ;; --gyp|-g) rebuild_gyp=1 ;;
--nspr) nspr_clean; rebuild_nspr=1 ;; --nspr) nspr_clean; rebuild_nspr=1 ;;
-j) ninja_params+=(-j "$2"); shift ;; -j) ninja_params+=(-j "$2"); shift ;;
-v) ninja_params+=(-v); verbose=1 ;; -v) ninja_params+=(-v); verbose=1 ;;
--test) gyp_params+=(-Dtest_build=1) ;; --test) gyp_params+=(-Dtest_build=1) ;;
--clang) export CC=clang; export CCC=clang++; export CXX=clang++ ;;
--gcc) export CC=gcc; export CCC=g++; export CXX=g++ ;;
--fuzz) fuzz=1 ;; --fuzz) fuzz=1 ;;
--fuzz=oss) fuzz=1; fuzz_oss=1 ;; --fuzz=oss) fuzz=1; fuzz_oss=1 ;;
--fuzz=tls) fuzz=1; fuzz_tls=1 ;; --fuzz=tls) fuzz=1; fuzz_tls=1 ;;
@ -94,6 +97,7 @@ while [ $# -gt 0 ]; do
--with-nspr=?*) set_nspr_path "${1#*=}"; no_local_nspr=1 ;; --with-nspr=?*) set_nspr_path "${1#*=}"; no_local_nspr=1 ;;
--system-nspr) set_nspr_path "/usr/include/nspr/:"; no_local_nspr=1 ;; --system-nspr) set_nspr_path "/usr/include/nspr/:"; no_local_nspr=1 ;;
--enable-libpkix) gyp_params+=(-Ddisable_libpkix=0) ;; --enable-libpkix) gyp_params+=(-Ddisable_libpkix=0) ;;
--enable-fips) gyp_params+=(-Ddisable_fips=0) ;;
*) show_help; exit 2 ;; *) show_help; exit 2 ;;
esac esac
shift shift
@ -121,10 +125,15 @@ dist_dir=$(mkdir -p "$dist_dir"; cd "$dist_dir"; pwd -P)
gyp_params+=(-Dnss_dist_dir="$dist_dir") gyp_params+=(-Dnss_dist_dir="$dist_dir")
# -c = clean first # -c = clean first
if [ "$clean" = 1 ]; then if [ "$clean" = 1 -o "$clean_only" = 1 ]; then
nspr_clean nspr_clean
rm -rf "$cwd"/out rm -rf "$cwd"/out
rm -rf "$dist_dir" rm -rf "$dist_dir"
# -cc = only clean, don't build
if [ "$clean_only" = 1 ]; then
echo "Cleaned"
exit 0
fi
fi fi
# This saves a canonical representation of arguments that we are passing to gyp # This saves a canonical representation of arguments that we are passing to gyp

View file

@ -20,16 +20,14 @@
#include "secport.h" #include "secport.h"
#include "secoid.h" #include "secoid.h"
#include "nssutil.h" #include "nssutil.h"
#include "ecl-curve.h"
#include "pkcs1_vectors.h" #include "pkcs1_vectors.h"
#ifndef NSS_DISABLE_ECC
#include "ecl-curve.h"
SECStatus EC_DecodeParams(const SECItem *encodedParams, SECStatus EC_DecodeParams(const SECItem *encodedParams,
ECParams **ecparams); ECParams **ecparams);
SECStatus EC_CopyParams(PLArenaPool *arena, ECParams *dstParams, SECStatus EC_CopyParams(PLArenaPool *arena, ECParams *dstParams,
const ECParams *srcParams); const ECParams *srcParams);
#endif
char *progName; char *progName;
char *testdir = NULL; char *testdir = NULL;
@ -135,18 +133,14 @@ Usage()
PRINTUSAGE(progName, "-S -m mode", "Sign a buffer"); PRINTUSAGE(progName, "-S -m mode", "Sign a buffer");
PRINTUSAGE("", "", "[-i plaintext] [-o signature] [-k key]"); PRINTUSAGE("", "", "[-i plaintext] [-o signature] [-k key]");
PRINTUSAGE("", "", "[-b bufsize]"); PRINTUSAGE("", "", "[-b bufsize]");
#ifndef NSS_DISABLE_ECC
PRINTUSAGE("", "", "[-n curvename]"); PRINTUSAGE("", "", "[-n curvename]");
#endif
PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]"); PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]");
PRINTUSAGE("", "-m", "cipher mode to use"); PRINTUSAGE("", "-m", "cipher mode to use");
PRINTUSAGE("", "-i", "file which contains input buffer"); PRINTUSAGE("", "-i", "file which contains input buffer");
PRINTUSAGE("", "-o", "file for signature"); PRINTUSAGE("", "-o", "file for signature");
PRINTUSAGE("", "-k", "file which contains key"); PRINTUSAGE("", "-k", "file which contains key");
#ifndef NSS_DISABLE_ECC
PRINTUSAGE("", "-n", "name of curve for EC key generation; one of:"); PRINTUSAGE("", "-n", "name of curve for EC key generation; one of:");
PRINTUSAGE("", "", " nistp256, nistp384, nistp521"); PRINTUSAGE("", "", " nistp256, nistp384, nistp521");
#endif
PRINTUSAGE("", "-p", "do performance test"); PRINTUSAGE("", "-p", "do performance test");
PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads"); PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads");
PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)"); PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)");
@ -369,7 +363,6 @@ dsakey_from_filedata(PLArenaPool *arena, SECItem *filedata)
return key; return key;
} }
#ifndef NSS_DISABLE_ECC
static ECPrivateKey * static ECPrivateKey *
eckey_from_filedata(PLArenaPool *arena, SECItem *filedata) eckey_from_filedata(PLArenaPool *arena, SECItem *filedata)
{ {
@ -519,7 +512,6 @@ getECParams(const char *curve)
return ecparams; return ecparams;
} }
#endif /* NSS_DISABLE_ECC */
static void static void
dump_pqg(PQGParams *pqg) dump_pqg(PQGParams *pqg)
@ -537,7 +529,6 @@ dump_dsakey(DSAPrivateKey *key)
SECU_PrintInteger(stdout, &key->privateValue, "PRIVATE VALUE:", 0); SECU_PrintInteger(stdout, &key->privateValue, "PRIVATE VALUE:", 0);
} }
#ifndef NSS_DISABLE_ECC
static void static void
dump_ecp(ECParams *ecp) dump_ecp(ECParams *ecp)
{ {
@ -552,7 +543,6 @@ dump_eckey(ECPrivateKey *key)
SECU_PrintInteger(stdout, &key->publicValue, "PUBLIC VALUE:", 0); SECU_PrintInteger(stdout, &key->publicValue, "PUBLIC VALUE:", 0);
SECU_PrintInteger(stdout, &key->privateValue, "PRIVATE VALUE:", 0); SECU_PrintInteger(stdout, &key->privateValue, "PRIVATE VALUE:", 0);
} }
#endif
static void static void
dump_rsakey(RSAPrivateKey *key) dump_rsakey(RSAPrivateKey *key)
@ -638,9 +628,7 @@ typedef enum {
bltestRSA, /* Public Key Ciphers */ bltestRSA, /* Public Key Ciphers */
bltestRSA_OAEP, /* . (Public Key Enc.) */ bltestRSA_OAEP, /* . (Public Key Enc.) */
bltestRSA_PSS, /* . (Public Key Sig.) */ bltestRSA_PSS, /* . (Public Key Sig.) */
#ifndef NSS_DISABLE_ECC
bltestECDSA, /* . (Public Key Sig.) */ bltestECDSA, /* . (Public Key Sig.) */
#endif
bltestDSA, /* . (Public Key Sig.) */ bltestDSA, /* . (Public Key Sig.) */
bltestMD2, /* Hash algorithms */ bltestMD2, /* Hash algorithms */
bltestMD5, /* . */ bltestMD5, /* . */
@ -678,9 +666,7 @@ static char *mode_strings[] =
"rsa", "rsa",
"rsa_oaep", "rsa_oaep",
"rsa_pss", "rsa_pss",
#ifndef NSS_DISABLE_ECC
"ecdsa", "ecdsa",
#endif
/*"pqg",*/ /*"pqg",*/
"dsa", "dsa",
"md2", "md2",
@ -732,13 +718,11 @@ typedef struct
PQGParams *pqg; PQGParams *pqg;
} bltestDSAParams; } bltestDSAParams;
#ifndef NSS_DISABLE_ECC
typedef struct typedef struct
{ {
char *curveName; char *curveName;
bltestIO sigseed; bltestIO sigseed;
} bltestECDSAParams; } bltestECDSAParams;
#endif
typedef struct typedef struct
{ {
@ -751,9 +735,7 @@ typedef struct
union { union {
bltestRSAParams rsa; bltestRSAParams rsa;
bltestDSAParams dsa; bltestDSAParams dsa;
#ifndef NSS_DISABLE_ECC
bltestECDSAParams ecdsa; bltestECDSAParams ecdsa;
#endif
} cipherParams; } cipherParams;
} bltestAsymKeyParams; } bltestAsymKeyParams;
@ -1310,7 +1292,6 @@ dsa_verifyDigest(void *cx, SECItem *output, const SECItem *input)
return DSA_VerifyDigest((DSAPublicKey *)params->pubKey, output, input); return DSA_VerifyDigest((DSAPublicKey *)params->pubKey, output, input);
} }
#ifndef NSS_DISABLE_ECC
SECStatus SECStatus
ecdsa_signDigest(void *cx, SECItem *output, const SECItem *input) ecdsa_signDigest(void *cx, SECItem *output, const SECItem *input)
{ {
@ -1331,7 +1312,6 @@ ecdsa_verifyDigest(void *cx, SECItem *output, const SECItem *input)
bltestAsymKeyParams *params = (bltestAsymKeyParams *)cx; bltestAsymKeyParams *params = (bltestAsymKeyParams *)cx;
return ECDSA_VerifyDigest((ECPublicKey *)params->pubKey, output, input); return ECDSA_VerifyDigest((ECPublicKey *)params->pubKey, output, input);
} }
#endif
SECStatus SECStatus
bltest_des_init(bltestCipherInfo *cipherInfo, PRBool encrypt) bltest_des_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
@ -1811,7 +1791,6 @@ bltest_dsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
return SECSuccess; return SECSuccess;
} }
#ifndef NSS_DISABLE_ECC
SECStatus SECStatus
bltest_ecdsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt) bltest_ecdsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
{ {
@ -1877,7 +1856,6 @@ bltest_ecdsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
} }
return SECSuccess; return SECSuccess;
} }
#endif
/* XXX unfortunately, this is not defined in blapi.h */ /* XXX unfortunately, this is not defined in blapi.h */
SECStatus SECStatus
@ -2169,11 +2147,7 @@ finish:
SECStatus SECStatus
pubkeyInitKey(bltestCipherInfo *cipherInfo, PRFileDesc *file, pubkeyInitKey(bltestCipherInfo *cipherInfo, PRFileDesc *file,
#ifndef NSS_DISABLE_ECC
int keysize, int exponent, char *curveName) int keysize, int exponent, char *curveName)
#else
int keysize, int exponent)
#endif
{ {
int i; int i;
SECStatus rv = SECSuccess; SECStatus rv = SECSuccess;
@ -2182,12 +2156,10 @@ pubkeyInitKey(bltestCipherInfo *cipherInfo, PRFileDesc *file,
RSAPrivateKey **rsaKey = NULL; RSAPrivateKey **rsaKey = NULL;
bltestDSAParams *dsap; bltestDSAParams *dsap;
DSAPrivateKey **dsaKey = NULL; DSAPrivateKey **dsaKey = NULL;
#ifndef NSS_DISABLE_ECC
SECItem *tmpECParamsDER; SECItem *tmpECParamsDER;
ECParams *tmpECParams = NULL; ECParams *tmpECParams = NULL;
SECItem ecSerialize[3]; SECItem ecSerialize[3];
ECPrivateKey **ecKey = NULL; ECPrivateKey **ecKey = NULL;
#endif
switch (cipherInfo->mode) { switch (cipherInfo->mode) {
case bltestRSA: case bltestRSA:
case bltestRSA_PSS: case bltestRSA_PSS:
@ -2224,7 +2196,6 @@ pubkeyInitKey(bltestCipherInfo *cipherInfo, PRFileDesc *file,
dsap->keysize = (*dsaKey)->params.prime.len * 8; dsap->keysize = (*dsaKey)->params.prime.len * 8;
} }
break; break;
#ifndef NSS_DISABLE_ECC
case bltestECDSA: case bltestECDSA:
ecKey = (ECPrivateKey **)&asymk->privKey; ecKey = (ECPrivateKey **)&asymk->privKey;
if (curveName != NULL) { if (curveName != NULL) {
@ -2254,7 +2225,6 @@ pubkeyInitKey(bltestCipherInfo *cipherInfo, PRFileDesc *file,
*ecKey = eckey_from_filedata(cipherInfo->arena, &asymk->key.buf); *ecKey = eckey_from_filedata(cipherInfo->arena, &asymk->key.buf);
} }
break; break;
#endif
default: default:
return SECFailure; return SECFailure;
} }
@ -2341,7 +2311,6 @@ cipherInit(bltestCipherInfo *cipherInfo, PRBool encrypt)
} }
return bltest_dsa_init(cipherInfo, encrypt); return bltest_dsa_init(cipherInfo, encrypt);
break; break;
#ifndef NSS_DISABLE_ECC
case bltestECDSA: case bltestECDSA:
if (encrypt) { if (encrypt) {
SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
@ -2349,7 +2318,6 @@ cipherInit(bltestCipherInfo *cipherInfo, PRBool encrypt)
} }
return bltest_ecdsa_init(cipherInfo, encrypt); return bltest_ecdsa_init(cipherInfo, encrypt);
break; break;
#endif
case bltestMD2: case bltestMD2:
restart = cipherInfo->params.hash.restart; restart = cipherInfo->params.hash.restart;
SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
@ -2644,9 +2612,7 @@ cipherFinish(bltestCipherInfo *cipherInfo)
case bltestRSA_PSS: /* will be freed with it. */ case bltestRSA_PSS: /* will be freed with it. */
case bltestRSA_OAEP: case bltestRSA_OAEP:
case bltestDSA: case bltestDSA:
#ifndef NSS_DISABLE_ECC
case bltestECDSA: case bltestECDSA:
#endif
case bltestMD2: /* hash contexts are ephemeral */ case bltestMD2: /* hash contexts are ephemeral */
case bltestMD5: case bltestMD5:
case bltestSHA1: case bltestSHA1:
@ -2822,7 +2788,6 @@ print_td:
fprintf(stdout, "%8d", info->params.asymk.cipherParams.dsa.keysize); fprintf(stdout, "%8d", info->params.asymk.cipherParams.dsa.keysize);
} }
break; break;
#ifndef NSS_DISABLE_ECC
case bltestECDSA: case bltestECDSA:
if (td) { if (td) {
fprintf(stdout, "%12s", "ec_curve"); fprintf(stdout, "%12s", "ec_curve");
@ -2833,7 +2798,6 @@ print_td:
ecCurve_map[curveName] ? ecCurve_map[curveName]->text : "Unsupported curve"); ecCurve_map[curveName] ? ecCurve_map[curveName]->text : "Unsupported curve");
} }
break; break;
#endif
case bltestMD2: case bltestMD2:
case bltestMD5: case bltestMD5:
case bltestSHA1: case bltestSHA1:
@ -3063,7 +3027,6 @@ get_params(PLArenaPool *arena, bltestParams *params,
sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j); sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j);
load_file_data(arena, &params->asymk.sig, filename, bltestBase64Encoded); load_file_data(arena, &params->asymk.sig, filename, bltestBase64Encoded);
break; break;
#ifndef NSS_DISABLE_ECC
case bltestECDSA: case bltestECDSA:
sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
load_file_data(arena, &params->asymk.key, filename, bltestBase64Encoded); load_file_data(arena, &params->asymk.key, filename, bltestBase64Encoded);
@ -3075,7 +3038,6 @@ get_params(PLArenaPool *arena, bltestParams *params,
sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j); sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j);
load_file_data(arena, &params->asymk.sig, filename, bltestBase64Encoded); load_file_data(arena, &params->asymk.sig, filename, bltestBase64Encoded);
break; break;
#endif
case bltestMD2: case bltestMD2:
case bltestMD5: case bltestMD5:
case bltestSHA1: case bltestSHA1:
@ -3297,13 +3259,11 @@ dump_file(bltestCipherMode mode, char *filename)
load_file_data(arena, &keydata, filename, bltestBase64Encoded); load_file_data(arena, &keydata, filename, bltestBase64Encoded);
key = dsakey_from_filedata(arena, &keydata.buf); key = dsakey_from_filedata(arena, &keydata.buf);
dump_dsakey(key); dump_dsakey(key);
#ifndef NSS_DISABLE_ECC
} else if (mode == bltestECDSA) { } else if (mode == bltestECDSA) {
ECPrivateKey *key; ECPrivateKey *key;
load_file_data(arena, &keydata, filename, bltestBase64Encoded); load_file_data(arena, &keydata, filename, bltestBase64Encoded);
key = eckey_from_filedata(arena, &keydata.buf); key = eckey_from_filedata(arena, &keydata.buf);
dump_eckey(key); dump_eckey(key);
#endif
} }
PORT_FreeArena(arena, PR_FALSE); PORT_FreeArena(arena, PR_FALSE);
return SECFailure; return SECFailure;
@ -3590,9 +3550,7 @@ enum {
opt_Key, opt_Key,
opt_HexWSpc, opt_HexWSpc,
opt_Mode, opt_Mode,
#ifndef NSS_DISABLE_ECC
opt_CurveName, opt_CurveName,
#endif
opt_Output, opt_Output,
opt_Repetitions, opt_Repetitions,
opt_ZeroBuf, opt_ZeroBuf,
@ -3644,9 +3602,7 @@ static secuCommandFlag bltest_options[] =
{ /* opt_Key */ 'k', PR_TRUE, 0, PR_FALSE }, { /* opt_Key */ 'k', PR_TRUE, 0, PR_FALSE },
{ /* opt_HexWSpc */ 'l', PR_FALSE, 0, PR_FALSE }, { /* opt_HexWSpc */ 'l', PR_FALSE, 0, PR_FALSE },
{ /* opt_Mode */ 'm', PR_TRUE, 0, PR_FALSE }, { /* opt_Mode */ 'm', PR_TRUE, 0, PR_FALSE },
#ifndef NSS_DISABLE_ECC
{ /* opt_CurveName */ 'n', PR_TRUE, 0, PR_FALSE }, { /* opt_CurveName */ 'n', PR_TRUE, 0, PR_FALSE },
#endif
{ /* opt_Output */ 'o', PR_TRUE, 0, PR_FALSE }, { /* opt_Output */ 'o', PR_TRUE, 0, PR_FALSE },
{ /* opt_Repetitions */ 'p', PR_TRUE, 0, PR_FALSE }, { /* opt_Repetitions */ 'p', PR_TRUE, 0, PR_FALSE },
{ /* opt_ZeroBuf */ 'q', PR_FALSE, 0, PR_FALSE }, { /* opt_ZeroBuf */ 'q', PR_FALSE, 0, PR_FALSE },
@ -3679,9 +3635,7 @@ main(int argc, char **argv)
bltestCipherInfo *cipherInfoListHead, *cipherInfo = NULL; bltestCipherInfo *cipherInfoListHead, *cipherInfo = NULL;
bltestIOMode ioMode; bltestIOMode ioMode;
int bufsize, exponent, curThrdNum; int bufsize, exponent, curThrdNum;
#ifndef NSS_DISABLE_ECC
char *curveName = NULL; char *curveName = NULL;
#endif
int i, commandsEntered; int i, commandsEntered;
int inoff, outoff; int inoff, outoff;
int threads = 1; int threads = 1;
@ -3917,12 +3871,10 @@ main(int argc, char **argv)
else else
exponent = 65537; exponent = 65537;
#ifndef NSS_DISABLE_ECC
if (bltest.options[opt_CurveName].activated) if (bltest.options[opt_CurveName].activated)
curveName = PORT_Strdup(bltest.options[opt_CurveName].arg); curveName = PORT_Strdup(bltest.options[opt_CurveName].arg);
else else
curveName = NULL; curveName = NULL;
#endif
if (bltest.commands[cmd_Verify].activated && if (bltest.commands[cmd_Verify].activated &&
!bltest.options[opt_SigFile].activated) { !bltest.options[opt_SigFile].activated) {
@ -4008,11 +3960,7 @@ main(int argc, char **argv)
file = PR_Open("tmp.key", PR_WRONLY | PR_CREATE_FILE, 00660); file = PR_Open("tmp.key", PR_WRONLY | PR_CREATE_FILE, 00660);
} }
params->key.mode = bltestBase64Encoded; params->key.mode = bltestBase64Encoded;
#ifndef NSS_DISABLE_ECC
pubkeyInitKey(cipherInfo, file, keysize, exponent, curveName); pubkeyInitKey(cipherInfo, file, keysize, exponent, curveName);
#else
pubkeyInitKey(cipherInfo, file, keysize, exponent);
#endif
PR_Close(file); PR_Close(file);
} }

View file

@ -233,8 +233,7 @@ make_datastruct(char *data, int len)
if (remaining == 1) { if (remaining == 1) {
remaining += fields; remaining += fields;
fields = fields * 2; fields = fields * 2;
datastruct = (Pair *)PORT_Realloc(datastruct, fields * datastruct = (Pair *)PORT_Realloc(datastruct, fields * sizeof(Pair));
sizeof(Pair));
if (datastruct == NULL) { if (datastruct == NULL) {
error_allocate(); error_allocate();
} }

View file

@ -194,6 +194,8 @@ CertReq(SECKEYPrivateKey *privk, SECKEYPublicKey *pubk, KeyType keyType,
PLArenaPool *arena; PLArenaPool *arena;
void *extHandle; void *extHandle;
SECItem signedReq = { siBuffer, NULL, 0 }; SECItem signedReq = { siBuffer, NULL, 0 };
SECAlgorithmID signAlg;
SECItem *params = NULL;
arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
if (!arena) { if (!arena) {
@ -211,11 +213,26 @@ CertReq(SECKEYPrivateKey *privk, SECKEYPublicKey *pubk, KeyType keyType,
/* Change cert type to RSA-PSS, if desired. */ /* Change cert type to RSA-PSS, if desired. */
if (pssCertificate) { if (pssCertificate) {
params = SEC_CreateSignatureAlgorithmParameters(arena,
NULL,
SEC_OID_PKCS1_RSA_PSS_SIGNATURE,
hashAlgTag,
NULL,
privk);
if (!params) {
PORT_FreeArena(arena, PR_FALSE);
SECKEY_DestroySubjectPublicKeyInfo(spki);
SECU_PrintError(progName, "unable to create RSA-PSS parameters");
return SECFailure;
}
spki->algorithm.parameters.data = NULL; spki->algorithm.parameters.data = NULL;
rv = SECOID_SetAlgorithmID(arena, &spki->algorithm, rv = SECOID_SetAlgorithmID(arena, &spki->algorithm,
SEC_OID_PKCS1_RSA_PSS_SIGNATURE, 0); SEC_OID_PKCS1_RSA_PSS_SIGNATURE,
hashAlgTag == SEC_OID_UNKNOWN ? NULL : params);
if (rv != SECSuccess) { if (rv != SECSuccess) {
PORT_FreeArena(arena, PR_FALSE); PORT_FreeArena(arena, PR_FALSE);
SECKEY_DestroySubjectPublicKeyInfo(spki);
SECU_PrintError(progName, "unable to set algorithm ID"); SECU_PrintError(progName, "unable to set algorithm ID");
return SECFailure; return SECFailure;
} }
@ -256,16 +273,34 @@ CertReq(SECKEYPrivateKey *privk, SECKEYPublicKey *pubk, KeyType keyType,
return SECFailure; return SECFailure;
} }
/* Sign the request */ PORT_Memset(&signAlg, 0, sizeof(signAlg));
if (pssCertificate) {
rv = SECOID_SetAlgorithmID(arena, &signAlg,
SEC_OID_PKCS1_RSA_PSS_SIGNATURE, params);
if (rv != SECSuccess) {
PORT_FreeArena(arena, PR_FALSE);
SECU_PrintError(progName, "unable to set algorithm ID");
return SECFailure;
}
} else {
signAlgTag = SEC_GetSignatureAlgorithmOidTag(keyType, hashAlgTag); signAlgTag = SEC_GetSignatureAlgorithmOidTag(keyType, hashAlgTag);
if (signAlgTag == SEC_OID_UNKNOWN) { if (signAlgTag == SEC_OID_UNKNOWN) {
PORT_FreeArena(arena, PR_FALSE); PORT_FreeArena(arena, PR_FALSE);
SECU_PrintError(progName, "unknown Key or Hash type"); SECU_PrintError(progName, "unknown Key or Hash type");
return SECFailure; return SECFailure;
} }
rv = SECOID_SetAlgorithmID(arena, &signAlg, signAlgTag, 0);
if (rv != SECSuccess) {
PORT_FreeArena(arena, PR_FALSE);
SECU_PrintError(progName, "unable to set algorithm ID");
return SECFailure;
}
}
rv = SEC_DerSignData(arena, &signedReq, encoding->data, encoding->len, /* Sign the request */
privk, signAlgTag); rv = SEC_DerSignDataWithAlgorithmID(arena, &signedReq,
encoding->data, encoding->len,
privk, &signAlg);
if (rv) { if (rv) {
PORT_FreeArena(arena, PR_FALSE); PORT_FreeArena(arena, PR_FALSE);
SECU_PrintError(progName, "signing of data failed"); SECU_PrintError(progName, "signing of data failed");
@ -365,7 +400,7 @@ ChangeTrustAttributes(CERTCertDBHandle *handle, PK11SlotInfo *slot,
CERTCertificate *cert; CERTCertificate *cert;
CERTCertTrust *trust; CERTCertTrust *trust;
cert = CERT_FindCertByNicknameOrEmailAddr(handle, name); cert = CERT_FindCertByNicknameOrEmailAddrCX(handle, name, pwdata);
if (!cert) { if (!cert) {
SECU_PrintError(progName, "could not find certificate named \"%s\"", SECU_PrintError(progName, "could not find certificate named \"%s\"",
name); name);
@ -591,6 +626,10 @@ ListCerts(CERTCertDBHandle *handle, char *nickname, char *email,
{ {
SECStatus rv; SECStatus rv;
if (slot && PK11_NeedUserInit(slot)) {
printf("\nDatabase needs user init\n");
}
if (!ascii && !raw && !nickname && !email) { if (!ascii && !raw && !nickname && !email) {
PR_fprintf(outfile, "\n%-60s %-5s\n%-60s %-5s\n\n", PR_fprintf(outfile, "\n%-60s %-5s\n%-60s %-5s\n\n",
"Certificate Nickname", "Trust Attributes", "", "Certificate Nickname", "Trust Attributes", "",
@ -614,12 +653,12 @@ ListCerts(CERTCertDBHandle *handle, char *nickname, char *email,
} }
static SECStatus static SECStatus
DeleteCert(CERTCertDBHandle *handle, char *name) DeleteCert(CERTCertDBHandle *handle, char *name, void *pwdata)
{ {
SECStatus rv; SECStatus rv;
CERTCertificate *cert; CERTCertificate *cert;
cert = CERT_FindCertByNicknameOrEmailAddr(handle, name); cert = CERT_FindCertByNicknameOrEmailAddrCX(handle, name, pwdata);
if (!cert) { if (!cert) {
SECU_PrintError(progName, "could not find certificate named \"%s\"", SECU_PrintError(progName, "could not find certificate named \"%s\"",
name); name);
@ -635,12 +674,12 @@ DeleteCert(CERTCertDBHandle *handle, char *name)
} }
static SECStatus static SECStatus
RenameCert(CERTCertDBHandle *handle, char *name, char *newName) RenameCert(CERTCertDBHandle *handle, char *name, char *newName, void *pwdata)
{ {
SECStatus rv; SECStatus rv;
CERTCertificate *cert; CERTCertificate *cert;
cert = CERT_FindCertByNicknameOrEmailAddr(handle, name); cert = CERT_FindCertByNicknameOrEmailAddrCX(handle, name, pwdata);
if (!cert) { if (!cert) {
SECU_PrintError(progName, "could not find certificate named \"%s\"", SECU_PrintError(progName, "could not find certificate named \"%s\"",
name); name);
@ -1014,6 +1053,18 @@ ListModules(void)
return SECSuccess; return SECSuccess;
} }
static void
PrintBuildFlags()
{
#ifdef NSS_FIPS_DISABLED
PR_fprintf(PR_STDOUT, "NSS_FIPS_DISABLED\n");
#endif
#ifdef NSS_NO_INIT_SUPPORT
PR_fprintf(PR_STDOUT, "NSS_NO_INIT_SUPPORT\n");
#endif
exit(0);
}
static void static void
PrintSyntax(char *progName) PrintSyntax(char *progName)
{ {
@ -1044,15 +1095,10 @@ PrintSyntax(char *progName)
"\t\t [-f pwfile] [-z noisefile] [-d certdir] [-P dbprefix]\n", progName); "\t\t [-f pwfile] [-z noisefile] [-d certdir] [-P dbprefix]\n", progName);
FPS "\t%s -G [-h token-name] -k dsa [-q pqgfile -g key-size] [-f pwfile]\n" FPS "\t%s -G [-h token-name] -k dsa [-q pqgfile -g key-size] [-f pwfile]\n"
"\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName); "\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName);
#ifndef NSS_DISABLE_ECC
FPS "\t%s -G [-h token-name] -k ec -q curve [-f pwfile]\n" FPS "\t%s -G [-h token-name] -k ec -q curve [-f pwfile]\n"
"\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName); "\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName);
FPS "\t%s -K [-n key-name] [-h token-name] [-k dsa|ec|rsa|all]\n", FPS "\t%s -K [-n key-name] [-h token-name] [-k dsa|ec|rsa|all]\n",
progName); progName);
#else
FPS "\t%s -K [-n key-name] [-h token-name] [-k dsa|rsa|all]\n",
progName);
#endif /* NSS_DISABLE_ECC */
FPS "\t\t [-f pwfile] [-X] [-d certdir] [-P dbprefix]\n"); FPS "\t\t [-f pwfile] [-X] [-d certdir] [-P dbprefix]\n");
FPS "\t%s --upgrade-merge --source-dir upgradeDir --upgrade-id uniqueID\n", FPS "\t%s --upgrade-merge --source-dir upgradeDir --upgrade-id uniqueID\n",
progName); progName);
@ -1066,6 +1112,7 @@ PrintSyntax(char *progName)
FPS "\t%s -L [-n cert-name] [-h token-name] [--email email-address]\n", FPS "\t%s -L [-n cert-name] [-h token-name] [--email email-address]\n",
progName); progName);
FPS "\t\t [-X] [-r] [-a] [--dump-ext-val OID] [-d certdir] [-P dbprefix]\n"); FPS "\t\t [-X] [-r] [-a] [--dump-ext-val OID] [-d certdir] [-P dbprefix]\n");
FPS "\t%s --build-flags\n", progName);
FPS "\t%s -M -n cert-name -t trustargs [-d certdir] [-P dbprefix]\n", FPS "\t%s -M -n cert-name -t trustargs [-d certdir] [-P dbprefix]\n",
progName); progName);
FPS "\t%s -O -n cert-name [-X] [-d certdir] [-a] [-P dbprefix]\n", progName); FPS "\t%s -O -n cert-name [-X] [-d certdir] [-a] [-P dbprefix]\n", progName);
@ -1184,6 +1231,8 @@ luC(enum usage_level ul, const char *command)
" -o output-cert"); " -o output-cert");
FPS "%-20s Self sign\n", FPS "%-20s Self sign\n",
" -x"); " -x");
FPS "%-20s Sign the certificate with RSA-PSS (the issuer key must be rsa)\n",
" --pss-sign");
FPS "%-20s Cert serial number\n", FPS "%-20s Cert serial number\n",
" -m serial-number"); " -m serial-number");
FPS "%-20s Time Warp\n", FPS "%-20s Time Warp\n",
@ -1244,17 +1293,10 @@ luG(enum usage_level ul, const char *command)
return; return;
FPS "%-20s Name of token in which to generate key (default is internal)\n", FPS "%-20s Name of token in which to generate key (default is internal)\n",
" -h token-name"); " -h token-name");
#ifndef NSS_DISABLE_ECC
FPS "%-20s Type of key pair to generate (\"dsa\", \"ec\", \"rsa\" (default))\n", FPS "%-20s Type of key pair to generate (\"dsa\", \"ec\", \"rsa\" (default))\n",
" -k key-type"); " -k key-type");
FPS "%-20s Key size in bits, (min %d, max %d, default %d) (not for ec)\n", FPS "%-20s Key size in bits, (min %d, max %d, default %d) (not for ec)\n",
" -g key-size", MIN_KEY_BITS, MAX_KEY_BITS, DEFAULT_KEY_BITS); " -g key-size", MIN_KEY_BITS, MAX_KEY_BITS, DEFAULT_KEY_BITS);
#else
FPS "%-20s Type of key pair to generate (\"dsa\", \"rsa\" (default))\n",
" -k key-type");
FPS "%-20s Key size in bits, (min %d, max %d, default %d)\n",
" -g key-size", MIN_KEY_BITS, MAX_KEY_BITS, DEFAULT_KEY_BITS);
#endif /* NSS_DISABLE_ECC */
FPS "%-20s Set the public exponent value (3, 17, 65537) (rsa only)\n", FPS "%-20s Set the public exponent value (3, 17, 65537) (rsa only)\n",
" -y exp"); " -y exp");
FPS "%-20s Specify the password file\n", FPS "%-20s Specify the password file\n",
@ -1263,7 +1305,6 @@ luG(enum usage_level ul, const char *command)
" -z noisefile"); " -z noisefile");
FPS "%-20s read PQG value from pqgfile (dsa only)\n", FPS "%-20s read PQG value from pqgfile (dsa only)\n",
" -q pqgfile"); " -q pqgfile");
#ifndef NSS_DISABLE_ECC
FPS "%-20s Elliptic curve name (ec only)\n", FPS "%-20s Elliptic curve name (ec only)\n",
" -q curve-name"); " -q curve-name");
FPS "%-20s One of nistp256, nistp384, nistp521, curve25519.\n", ""); FPS "%-20s One of nistp256, nistp384, nistp521, curve25519.\n", "");
@ -1285,7 +1326,6 @@ luG(enum usage_level ul, const char *command)
FPS "%-20s c2tnb359w1, c2pnb368w1, c2tnb431r1, secp112r1, \n", ""); FPS "%-20s c2tnb359w1, c2pnb368w1, c2tnb431r1, secp112r1, \n", "");
FPS "%-20s secp112r2, secp128r1, secp128r2, sect113r1, sect113r2\n", ""); FPS "%-20s secp112r2, secp128r1, secp128r2, sect113r1, sect113r2\n", "");
FPS "%-20s sect131r1, sect131r2\n", ""); FPS "%-20s sect131r1, sect131r2\n", "");
#endif
FPS "%-20s Key database directory (default is ~/.netscape)\n", FPS "%-20s Key database directory (default is ~/.netscape)\n",
" -d keydir"); " -d keydir");
FPS "%-20s Cert & Key database prefix\n", FPS "%-20s Cert & Key database prefix\n",
@ -1375,9 +1415,7 @@ luK(enum usage_level ul, const char *command)
" -h token-name "); " -h token-name ");
FPS "%-20s Key type (\"all\" (default), \"dsa\"," FPS "%-20s Key type (\"all\" (default), \"dsa\","
#ifndef NSS_DISABLE_ECC
" \"ec\"," " \"ec\","
#endif
" \"rsa\")\n", " \"rsa\")\n",
" -k key-type"); " -k key-type");
FPS "%-20s The nickname of the key or associated certificate\n", FPS "%-20s The nickname of the key or associated certificate\n",
@ -1520,11 +1558,7 @@ luR(enum usage_level ul, const char *command)
" -s subject"); " -s subject");
FPS "%-20s Output the cert request to this file\n", FPS "%-20s Output the cert request to this file\n",
" -o output-req"); " -o output-req");
#ifndef NSS_DISABLE_ECC
FPS "%-20s Type of key pair to generate (\"dsa\", \"ec\", \"rsa\" (default))\n", FPS "%-20s Type of key pair to generate (\"dsa\", \"ec\", \"rsa\" (default))\n",
#else
FPS "%-20s Type of key pair to generate (\"dsa\", \"rsa\" (default))\n",
#endif /* NSS_DISABLE_ECC */
" -k key-type-or-id"); " -k key-type-or-id");
FPS "%-20s or nickname of the cert key to use \n", FPS "%-20s or nickname of the cert key to use \n",
""); "");
@ -1532,14 +1566,14 @@ luR(enum usage_level ul, const char *command)
" -h token-name"); " -h token-name");
FPS "%-20s Key size in bits, RSA keys only (min %d, max %d, default %d)\n", FPS "%-20s Key size in bits, RSA keys only (min %d, max %d, default %d)\n",
" -g key-size", MIN_KEY_BITS, MAX_KEY_BITS, DEFAULT_KEY_BITS); " -g key-size", MIN_KEY_BITS, MAX_KEY_BITS, DEFAULT_KEY_BITS);
FPS "%-20s Create a certificate request restricted to RSA-PSS (rsa only)\n",
" --pss");
FPS "%-20s Name of file containing PQG parameters (dsa only)\n", FPS "%-20s Name of file containing PQG parameters (dsa only)\n",
" -q pqgfile"); " -q pqgfile");
#ifndef NSS_DISABLE_ECC
FPS "%-20s Elliptic curve name (ec only)\n", FPS "%-20s Elliptic curve name (ec only)\n",
" -q curve-name"); " -q curve-name");
FPS "%-20s See the \"-G\" option for a full list of supported names.\n", FPS "%-20s See the \"-G\" option for a full list of supported names.\n",
""); "");
#endif /* NSS_DISABLE_ECC */
FPS "%-20s Specify the password file\n", FPS "%-20s Specify the password file\n",
" -f pwfile"); " -f pwfile");
FPS "%-20s Key database directory (default is ~/.netscape)\n", FPS "%-20s Key database directory (default is ~/.netscape)\n",
@ -1705,26 +1739,24 @@ luS(enum usage_level ul, const char *command)
" -c issuer-name"); " -c issuer-name");
FPS "%-20s Set the certificate trust attributes (see -A above)\n", FPS "%-20s Set the certificate trust attributes (see -A above)\n",
" -t trustargs"); " -t trustargs");
#ifndef NSS_DISABLE_ECC
FPS "%-20s Type of key pair to generate (\"dsa\", \"ec\", \"rsa\" (default))\n", FPS "%-20s Type of key pair to generate (\"dsa\", \"ec\", \"rsa\" (default))\n",
#else
FPS "%-20s Type of key pair to generate (\"dsa\", \"rsa\" (default))\n",
#endif /* NSS_DISABLE_ECC */
" -k key-type-or-id"); " -k key-type-or-id");
FPS "%-20s Name of token in which to generate key (default is internal)\n", FPS "%-20s Name of token in which to generate key (default is internal)\n",
" -h token-name"); " -h token-name");
FPS "%-20s Key size in bits, RSA keys only (min %d, max %d, default %d)\n", FPS "%-20s Key size in bits, RSA keys only (min %d, max %d, default %d)\n",
" -g key-size", MIN_KEY_BITS, MAX_KEY_BITS, DEFAULT_KEY_BITS); " -g key-size", MIN_KEY_BITS, MAX_KEY_BITS, DEFAULT_KEY_BITS);
FPS "%-20s Create a certificate restricted to RSA-PSS (rsa only)\n",
" --pss");
FPS "%-20s Name of file containing PQG parameters (dsa only)\n", FPS "%-20s Name of file containing PQG parameters (dsa only)\n",
" -q pqgfile"); " -q pqgfile");
#ifndef NSS_DISABLE_ECC
FPS "%-20s Elliptic curve name (ec only)\n", FPS "%-20s Elliptic curve name (ec only)\n",
" -q curve-name"); " -q curve-name");
FPS "%-20s See the \"-G\" option for a full list of supported names.\n", FPS "%-20s See the \"-G\" option for a full list of supported names.\n",
""); "");
#endif /* NSS_DISABLE_ECC */
FPS "%-20s Self sign\n", FPS "%-20s Self sign\n",
" -x"); " -x");
FPS "%-20s Sign the certificate with RSA-PSS (the issuer key must be rsa)\n",
" --pss-sign");
FPS "%-20s Cert serial number\n", FPS "%-20s Cert serial number\n",
" -m serial-number"); " -m serial-number");
FPS "%-20s Time Warp\n", FPS "%-20s Time Warp\n",
@ -1793,6 +1825,18 @@ luS(enum usage_level ul, const char *command)
FPS "\n"); FPS "\n");
} }
static void
luBuildFlags(enum usage_level ul, const char *command)
{
int is_my_command = (command && 0 == strcmp(command, "build-flags"));
if (ul == usage_all || !command || is_my_command)
FPS "%-15s Print enabled build flags relevant for NSS test execution\n",
"--build-flags");
if (ul == usage_selected && !is_my_command)
return;
FPS "\n");
}
static void static void
LongUsage(char *progName, enum usage_level ul, const char *command) LongUsage(char *progName, enum usage_level ul, const char *command)
{ {
@ -1807,6 +1851,7 @@ LongUsage(char *progName, enum usage_level ul, const char *command)
luU(ul, command); luU(ul, command);
luK(ul, command); luK(ul, command);
luL(ul, command); luL(ul, command);
luBuildFlags(ul, command);
luM(ul, command); luM(ul, command);
luN(ul, command); luN(ul, command);
luT(ul, command); luT(ul, command);
@ -1888,47 +1933,120 @@ MakeV1Cert(CERTCertDBHandle *handle,
return (cert); return (cert);
} }
static SECStatus
SetSignatureAlgorithm(PLArenaPool *arena,
SECAlgorithmID *signAlg,
SECAlgorithmID *spkiAlg,
SECOidTag hashAlgTag,
SECKEYPrivateKey *privKey,
PRBool pssSign)
{
SECStatus rv;
if (pssSign ||
SECOID_GetAlgorithmTag(spkiAlg) == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
SECItem *srcParams;
SECItem *params;
if (SECOID_GetAlgorithmTag(spkiAlg) == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
srcParams = &spkiAlg->parameters;
} else {
/* If the issuer's public key is RSA, the parameter field
* of the SPKI should be NULL, which can't be used as a
* basis of RSA-PSS parameters. */
srcParams = NULL;
}
params = SEC_CreateSignatureAlgorithmParameters(arena,
NULL,
SEC_OID_PKCS1_RSA_PSS_SIGNATURE,
hashAlgTag,
srcParams,
privKey);
if (!params) {
SECU_PrintError(progName, "Could not create RSA-PSS parameters");
return SECFailure;
}
rv = SECOID_SetAlgorithmID(arena, signAlg,
SEC_OID_PKCS1_RSA_PSS_SIGNATURE,
params);
if (rv != SECSuccess) {
SECU_PrintError(progName, "Could not set signature algorithm id.");
return rv;
}
} else {
KeyType keyType = SECKEY_GetPrivateKeyType(privKey);
SECOidTag algID;
algID = SEC_GetSignatureAlgorithmOidTag(keyType, hashAlgTag);
if (algID == SEC_OID_UNKNOWN) {
SECU_PrintError(progName, "Unknown key or hash type for issuer.");
return SECFailure;
}
rv = SECOID_SetAlgorithmID(arena, signAlg, algID, 0);
if (rv != SECSuccess) {
SECU_PrintError(progName, "Could not set signature algorithm id.");
return rv;
}
}
return SECSuccess;
}
static SECStatus static SECStatus
SignCert(CERTCertDBHandle *handle, CERTCertificate *cert, PRBool selfsign, SignCert(CERTCertDBHandle *handle, CERTCertificate *cert, PRBool selfsign,
SECOidTag hashAlgTag, SECOidTag hashAlgTag,
SECKEYPrivateKey *privKey, char *issuerNickName, SECKEYPrivateKey *privKey, char *issuerNickName,
int certVersion, void *pwarg) int certVersion, PRBool pssSign, void *pwarg)
{ {
SECItem der; SECItem der;
SECKEYPrivateKey *caPrivateKey = NULL; SECKEYPrivateKey *caPrivateKey = NULL;
SECStatus rv; SECStatus rv;
PLArenaPool *arena; PLArenaPool *arena;
SECOidTag algID; CERTCertificate *issuer;
void *dummy; void *dummy;
if (!selfsign) {
CERTCertificate *issuer = PK11_FindCertFromNickname(issuerNickName, pwarg);
if ((CERTCertificate *)NULL == issuer) {
SECU_PrintError(progName, "unable to find issuer with nickname %s",
issuerNickName);
return SECFailure;
}
privKey = caPrivateKey = PK11_FindKeyByAnyCert(issuer, pwarg);
CERT_DestroyCertificate(issuer);
if (caPrivateKey == NULL) {
SECU_PrintError(progName, "unable to retrieve key %s", issuerNickName);
return SECFailure;
}
}
arena = cert->arena; arena = cert->arena;
algID = SEC_GetSignatureAlgorithmOidTag(privKey->keyType, hashAlgTag); if (selfsign) {
if (algID == SEC_OID_UNKNOWN) { issuer = cert;
fprintf(stderr, "Unknown key or hash type for issuer."); } else {
issuer = PK11_FindCertFromNickname(issuerNickName, pwarg);
if ((CERTCertificate *)NULL == issuer) {
SECU_PrintError(progName, "unable to find issuer with nickname %s",
issuerNickName);
rv = SECFailure; rv = SECFailure;
goto done; goto done;
} }
privKey = caPrivateKey = PK11_FindKeyByAnyCert(issuer, pwarg);
if (caPrivateKey == NULL) {
SECU_PrintError(progName, "unable to retrieve key %s", issuerNickName);
rv = SECFailure;
CERT_DestroyCertificate(issuer);
goto done;
}
}
rv = SECOID_SetAlgorithmID(arena, &cert->signature, algID, 0); if (pssSign &&
(SECKEY_GetPrivateKeyType(privKey) != rsaKey &&
SECKEY_GetPrivateKeyType(privKey) != rsaPssKey)) {
SECU_PrintError(progName, "unable to create RSA-PSS signature with key %s",
issuerNickName);
rv = SECFailure;
if (!selfsign) {
CERT_DestroyCertificate(issuer);
}
goto done;
}
rv = SetSignatureAlgorithm(arena,
&cert->signature,
&issuer->subjectPublicKeyInfo.algorithm,
hashAlgTag,
privKey,
pssSign);
if (!selfsign) {
CERT_DestroyCertificate(issuer);
}
if (rv != SECSuccess) { if (rv != SECSuccess) {
fprintf(stderr, "Could not set signature algorithm id.");
goto done; goto done;
} }
@ -1947,7 +2065,8 @@ SignCert(CERTCertDBHandle *handle, CERTCertificate *cert, PRBool selfsign,
break; break;
default: default:
PORT_SetError(SEC_ERROR_INVALID_ARGS); PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure; rv = SECFailure;
goto done;
} }
der.len = 0; der.len = 0;
@ -1960,7 +2079,8 @@ SignCert(CERTCertDBHandle *handle, CERTCertificate *cert, PRBool selfsign,
goto done; goto done;
} }
rv = SEC_DerSignData(arena, &cert->derCert, der.data, der.len, privKey, algID); rv = SEC_DerSignDataWithAlgorithmID(arena, &cert->derCert, der.data, der.len,
privKey, &cert->signature);
if (rv != SECSuccess) { if (rv != SECSuccess) {
fprintf(stderr, "Could not sign encoded certificate data.\n"); fprintf(stderr, "Could not sign encoded certificate data.\n");
/* result allocated out of the arena, it will be freed /* result allocated out of the arena, it will be freed
@ -1993,6 +2113,7 @@ CreateCert(
certutilExtnList extnList, certutilExtnList extnList,
const char *extGeneric, const char *extGeneric,
int certVersion, int certVersion,
PRBool pssSign,
SECItem *certDER) SECItem *certDER)
{ {
void *extHandle = NULL; void *extHandle = NULL;
@ -2053,7 +2174,7 @@ CreateCert(
rv = SignCert(handle, subjectCert, selfsign, hashAlgTag, rv = SignCert(handle, subjectCert, selfsign, hashAlgTag,
*selfsignprivkey, issuerNickName, *selfsignprivkey, issuerNickName,
certVersion, pwarg); certVersion, pssSign, pwarg);
if (rv != SECSuccess) if (rv != SECSuccess)
break; break;
@ -2306,6 +2427,7 @@ enum {
cmd_Merge, cmd_Merge,
cmd_UpgradeMerge, /* test only */ cmd_UpgradeMerge, /* test only */
cmd_Rename, cmd_Rename,
cmd_BuildFlags,
max_cmd max_cmd
}; };
@ -2376,6 +2498,7 @@ enum certutilOpts {
opt_GenericExtensions, opt_GenericExtensions,
opt_NewNickname, opt_NewNickname,
opt_Pss, opt_Pss,
opt_PssSign,
opt_Help opt_Help
}; };
@ -2407,7 +2530,9 @@ static const secuCommandFlag commands_init[] =
{ /* cmd_UpgradeMerge */ 0, PR_FALSE, 0, PR_FALSE, { /* cmd_UpgradeMerge */ 0, PR_FALSE, 0, PR_FALSE,
"upgrade-merge" }, "upgrade-merge" },
{ /* cmd_Rename */ 0, PR_FALSE, 0, PR_FALSE, { /* cmd_Rename */ 0, PR_FALSE, 0, PR_FALSE,
"rename" } "rename" },
{ /* cmd_BuildFlags */ 0, PR_FALSE, 0, PR_FALSE,
"build-flags" }
}; };
#define NUM_COMMANDS ((sizeof commands_init) / (sizeof commands_init[0])) #define NUM_COMMANDS ((sizeof commands_init) / (sizeof commands_init[0]))
@ -2496,6 +2621,8 @@ static const secuCommandFlag options_init[] =
"new-n" }, "new-n" },
{ /* opt_Pss */ 0, PR_FALSE, 0, PR_FALSE, { /* opt_Pss */ 0, PR_FALSE, 0, PR_FALSE,
"pss" }, "pss" },
{ /* opt_PssSign */ 0, PR_FALSE, 0, PR_FALSE,
"pss-sign" },
}; };
#define NUM_OPTIONS ((sizeof options_init) / (sizeof options_init[0])) #define NUM_OPTIONS ((sizeof options_init) / (sizeof options_init[0]))
@ -2592,6 +2719,10 @@ certutil_main(int argc, char **argv, PRBool initialize)
exit(1); exit(1);
} }
if (certutil.commands[cmd_BuildFlags].activated) {
PrintBuildFlags();
}
if (certutil.options[opt_PasswordFile].arg) { if (certutil.options[opt_PasswordFile].arg) {
pwdata.source = PW_FROMFILE; pwdata.source = PW_FROMFILE;
pwdata.data = certutil.options[opt_PasswordFile].arg; pwdata.data = certutil.options[opt_PasswordFile].arg;
@ -2621,12 +2752,10 @@ certutil_main(int argc, char **argv, PRBool initialize)
progName, MIN_KEY_BITS, MAX_KEY_BITS); progName, MIN_KEY_BITS, MAX_KEY_BITS);
return 255; return 255;
} }
#ifndef NSS_DISABLE_ECC
if (keytype == ecKey) { if (keytype == ecKey) {
PR_fprintf(PR_STDERR, "%s -g: Not for ec keys.\n", progName); PR_fprintf(PR_STDERR, "%s -g: Not for ec keys.\n", progName);
return 255; return 255;
} }
#endif /* NSS_DISABLE_ECC */
} }
/* -h specify token name */ /* -h specify token name */
@ -2655,10 +2784,8 @@ certutil_main(int argc, char **argv, PRBool initialize)
keytype = rsaKey; keytype = rsaKey;
} else if (PL_strcmp(arg, "dsa") == 0) { } else if (PL_strcmp(arg, "dsa") == 0) {
keytype = dsaKey; keytype = dsaKey;
#ifndef NSS_DISABLE_ECC
} else if (PL_strcmp(arg, "ec") == 0) { } else if (PL_strcmp(arg, "ec") == 0) {
keytype = ecKey; keytype = ecKey;
#endif /* NSS_DISABLE_ECC */
} else if (PL_strcmp(arg, "all") == 0) { } else if (PL_strcmp(arg, "all") == 0) {
keytype = nullKey; keytype = nullKey;
} else { } else {
@ -2711,16 +2838,10 @@ certutil_main(int argc, char **argv, PRBool initialize)
/* -q PQG file or curve name */ /* -q PQG file or curve name */
if (certutil.options[opt_PQGFile].activated) { if (certutil.options[opt_PQGFile].activated) {
#ifndef NSS_DISABLE_ECC
if ((keytype != dsaKey) && (keytype != ecKey)) { if ((keytype != dsaKey) && (keytype != ecKey)) {
PR_fprintf(PR_STDERR, "%s -q: specifies a PQG file for DSA keys" PR_fprintf(PR_STDERR, "%s -q: specifies a PQG file for DSA keys"
" (-k dsa) or a named curve for EC keys (-k ec)\n)", " (-k dsa) or a named curve for EC keys (-k ec)\n)",
progName); progName);
#else /* } */
if (keytype != dsaKey) {
PR_fprintf(PR_STDERR, "%s -q: PQG file is for DSA key (-k dsa).\n)",
progName);
#endif /* NSS_DISABLE_ECC */
return 255; return 255;
} }
} }
@ -3032,12 +3153,44 @@ certutil_main(int argc, char **argv, PRBool initialize)
/* If creating new database, initialize the password. */ /* If creating new database, initialize the password. */
if (certutil.commands[cmd_NewDBs].activated) { if (certutil.commands[cmd_NewDBs].activated) {
if (certutil.options[opt_EmptyPassword].activated && (PK11_NeedUserInit(slot))) if (certutil.options[opt_EmptyPassword].activated && (PK11_NeedUserInit(slot))) {
PK11_InitPin(slot, (char *)NULL, ""); rv = PK11_InitPin(slot, (char *)NULL, "");
else } else {
SECU_ChangePW2(slot, 0, 0, certutil.options[opt_PasswordFile].arg, rv = SECU_ChangePW2(slot, 0, 0, certutil.options[opt_PasswordFile].arg,
certutil.options[opt_NewPasswordFile].arg); certutil.options[opt_NewPasswordFile].arg);
} }
if (rv != SECSuccess) {
SECU_PrintError(progName, "Could not set password for the slot");
goto shutdown;
}
}
/* if we are going to modify the cert database,
* make sure it's initialized */
if (certutil.commands[cmd_ModifyCertTrust].activated ||
certutil.commands[cmd_CreateAndAddCert].activated ||
certutil.commands[cmd_AddCert].activated ||
certutil.commands[cmd_AddEmailCert].activated) {
if (PK11_NeedLogin(slot) && PK11_NeedUserInit(slot)) {
char *password = NULL;
/* fetch the password from the command line or the file
* if no password is supplied, initialize the password to NULL */
if (pwdata.source == PW_FROMFILE) {
password = SECU_FilePasswd(slot, PR_FALSE, pwdata.data);
} else if (pwdata.source == PW_PLAINTEXT) {
password = PL_strdup(pwdata.data);
}
rv = PK11_InitPin(slot, (char *)NULL, password ? password : "");
if (password) {
PORT_Memset(password, 0, PL_strlen(password));
PORT_Free(password);
}
if (rv != SECSuccess) {
SECU_PrintError(progName, "Could not set password for the slot");
goto shutdown;
}
}
}
/* walk through the upgrade merge if necessary. /* walk through the upgrade merge if necessary.
* This option is more to test what some applications will want to do * This option is more to test what some applications will want to do
@ -3214,12 +3367,12 @@ certutil_main(int argc, char **argv, PRBool initialize)
} }
/* Delete cert (-D) */ /* Delete cert (-D) */
if (certutil.commands[cmd_DeleteCert].activated) { if (certutil.commands[cmd_DeleteCert].activated) {
rv = DeleteCert(certHandle, name); rv = DeleteCert(certHandle, name, &pwdata);
goto shutdown; goto shutdown;
} }
/* Rename cert (--rename) */ /* Rename cert (--rename) */
if (certutil.commands[cmd_Rename].activated) { if (certutil.commands[cmd_Rename].activated) {
rv = RenameCert(certHandle, name, newName); rv = RenameCert(certHandle, name, newName, &pwdata);
goto shutdown; goto shutdown;
} }
/* Delete key (-F) */ /* Delete key (-F) */
@ -3237,8 +3390,11 @@ certutil_main(int argc, char **argv, PRBool initialize)
if (certutil.commands[cmd_ChangePassword].activated) { if (certutil.commands[cmd_ChangePassword].activated) {
rv = SECU_ChangePW2(slot, 0, 0, certutil.options[opt_PasswordFile].arg, rv = SECU_ChangePW2(slot, 0, 0, certutil.options[opt_PasswordFile].arg,
certutil.options[opt_NewPasswordFile].arg); certutil.options[opt_NewPasswordFile].arg);
if (rv != SECSuccess) {
SECU_PrintError(progName, "Could not set password for the slot");
goto shutdown; goto shutdown;
} }
}
/* Reset the a token */ /* Reset the a token */
if (certutil.commands[cmd_TokenReset].activated) { if (certutil.commands[cmd_TokenReset].activated) {
char *sso_pass = ""; char *sso_pass = "";
@ -3362,6 +3518,25 @@ certutil_main(int argc, char **argv, PRBool initialize)
} }
} }
/* --pss-sign is to sign a certificate with RSA-PSS, even if the
* issuer's key is an RSA key. If the key is an RSA-PSS key, the
* generated signature is always RSA-PSS. */
if (certutil.options[opt_PssSign].activated) {
if (!certutil.commands[cmd_CreateNewCert].activated &&
!certutil.commands[cmd_CreateAndAddCert].activated) {
PR_fprintf(PR_STDERR,
"%s -%c: --pss-sign only works with -C or -S.\n",
progName, commandToRun);
return 255;
}
if (keytype != rsaKey) {
PR_fprintf(PR_STDERR,
"%s -%c: --pss-sign only works with RSA keys.\n",
progName, commandToRun);
return 255;
}
}
/* If we need a list of extensions convert the flags into list format */ /* If we need a list of extensions convert the flags into list format */
if (certutil.commands[cmd_CertReq].activated || if (certutil.commands[cmd_CertReq].activated ||
certutil.commands[cmd_CreateAndAddCert].activated || certutil.commands[cmd_CreateAndAddCert].activated ||
@ -3499,6 +3674,7 @@ certutil_main(int argc, char **argv, PRBool initialize)
(certutil.options[opt_GenericExtensions].activated ? certutil.options[opt_GenericExtensions].arg (certutil.options[opt_GenericExtensions].activated ? certutil.options[opt_GenericExtensions].arg
: NULL), : NULL),
certVersion, certVersion,
certutil.options[opt_PssSign].activated,
&certDER); &certDER);
if (rv) if (rv)
goto shutdown; goto shutdown;

View file

@ -380,7 +380,6 @@ CERTUTIL_FileForRNG(const char *noise)
return SECSuccess; return SECSuccess;
} }
#ifndef NSS_DISABLE_ECC
typedef struct curveNameTagPairStr { typedef struct curveNameTagPairStr {
char *curveName; char *curveName;
SECOidTag curveOidTag; SECOidTag curveOidTag;
@ -506,7 +505,6 @@ getECParams(const char *curve)
return ecparams; return ecparams;
} }
#endif /* NSS_DISABLE_ECC */
SECKEYPrivateKey * SECKEYPrivateKey *
CERTUTIL_GeneratePrivateKey(KeyType keytype, PK11SlotInfo *slot, int size, CERTUTIL_GeneratePrivateKey(KeyType keytype, PK11SlotInfo *slot, int size,
@ -564,14 +562,12 @@ CERTUTIL_GeneratePrivateKey(KeyType keytype, PK11SlotInfo *slot, int size,
params = (void *)&default_pqg_params; params = (void *)&default_pqg_params;
} }
break; break;
#ifndef NSS_DISABLE_ECC
case ecKey: case ecKey:
mechanism = CKM_EC_KEY_PAIR_GEN; mechanism = CKM_EC_KEY_PAIR_GEN;
/* For EC keys, PQGFile determines EC parameters */ /* For EC keys, PQGFile determines EC parameters */
if ((params = (void *)getECParams(pqgFile)) == NULL) if ((params = (void *)getECParams(pqgFile)) == NULL)
return NULL; return NULL;
break; break;
#endif /* NSS_DISABLE_ECC */
default: default:
return NULL; return NULL;
} }
@ -580,8 +576,7 @@ CERTUTIL_GeneratePrivateKey(KeyType keytype, PK11SlotInfo *slot, int size,
fprintf(stderr, "Generating key. This may take a few moments...\n\n"); fprintf(stderr, "Generating key. This may take a few moments...\n\n");
privKey = PK11_GenerateKeyPairWithOpFlags(slot, mechanism, params, pubkeyp, privKey = PK11_GenerateKeyPairWithOpFlags(slot, mechanism, params, pubkeyp,
attrFlags, opFlagsOn, opFlagsOn | attrFlags, opFlagsOn, opFlagsOn | opFlagsOff,
opFlagsOff,
pwdata /*wincx*/); pwdata /*wincx*/);
/* free up the params */ /* free up the params */
switch (keytype) { switch (keytype) {
@ -589,11 +584,9 @@ CERTUTIL_GeneratePrivateKey(KeyType keytype, PK11SlotInfo *slot, int size,
if (dsaparams) if (dsaparams)
CERTUTIL_DestroyParamsPQG(dsaparams); CERTUTIL_DestroyParamsPQG(dsaparams);
break; break;
#ifndef NSS_DISABLE_ECC
case ecKey: case ecKey:
SECITEM_FreeItem((SECItem *)params, PR_TRUE); SECITEM_FreeItem((SECItem *)params, PR_TRUE);
break; break;
#endif
default: /* nothing to free */ default: /* nothing to free */
break; break;
} }

View file

@ -616,8 +616,7 @@ crlgen_CreateInvalidityDate(PLArenaPool *arena, const char **dataArr,
goto loser; goto loser;
} }
PORT_Memcpy(encodedItem->data, dataArr[2], (encodedItem->len = length) * PORT_Memcpy(encodedItem->data, dataArr[2], (encodedItem->len = length) * sizeof(char));
sizeof(char));
*extCode = SEC_OID_X509_INVALID_DATE; *extCode = SEC_OID_X509_INVALID_DATE;
return encodedItem; return encodedItem;

View file

@ -35,13 +35,11 @@
#include "../../lib/freebl/mpi/mpi.h" #include "../../lib/freebl/mpi/mpi.h"
#endif #endif
#ifndef NSS_DISABLE_ECC
extern SECStatus extern SECStatus
EC_DecodeParams(const SECItem *encodedParams, ECParams **ecparams); EC_DecodeParams(const SECItem *encodedParams, ECParams **ecparams);
extern SECStatus extern SECStatus
EC_CopyParams(PLArenaPool *arena, ECParams *dstParams, EC_CopyParams(PLArenaPool *arena, ECParams *dstParams,
const ECParams *srcParams); const ECParams *srcParams);
#endif
#define ENCRYPT 1 #define ENCRYPT 1
#define DECRYPT 0 #define DECRYPT 0
@ -2094,7 +2092,6 @@ get_next_line(FILE *req, char *key, char *val, FILE *rsp)
return (c == EOF) ? -1 : ignore; return (c == EOF) ? -1 : ignore;
} }
#ifndef NSS_DISABLE_ECC
typedef struct curveNameTagPairStr { typedef struct curveNameTagPairStr {
char *curveName; char *curveName;
SECOidTag curveOidTag; SECOidTag curveOidTag;
@ -2958,7 +2955,6 @@ loser:
} }
fclose(ecdsareq); fclose(ecdsareq);
} }
#endif /* NSS_DISABLE_ECC */
PRBool PRBool
isblankline(char *b) isblankline(char *b)
@ -5926,8 +5922,7 @@ tls(char *reqfn)
goto loser; goto loser;
} }
crv = NSC_DeriveKey(session, &master_mech, pms_handle, crv = NSC_DeriveKey(session, &master_mech, pms_handle,
derive_template, derive_template_count - derive_template, derive_template_count - 1,
1,
&master_handle); &master_handle);
if (crv != CKR_OK) { if (crv != CKR_OK) {
fprintf(stderr, "NSC_DeriveKey(master) failed crv=0x%x\n", fprintf(stderr, "NSC_DeriveKey(master) failed crv=0x%x\n",
@ -6094,7 +6089,6 @@ main(int argc, char **argv)
/* Signature Verification Test */ /* Signature Verification Test */
dsa_sigver_test(argv[3]); dsa_sigver_test(argv[3]);
} }
#ifndef NSS_DISABLE_ECC
/*************/ /*************/
/* ECDSA */ /* ECDSA */
/*************/ /*************/
@ -6113,7 +6107,6 @@ main(int argc, char **argv)
/* Signature Verification Test */ /* Signature Verification Test */
ecdsa_sigver_test(argv[3]); ecdsa_sigver_test(argv[3]);
} }
#endif /* NSS_DISABLE_ECC */
/*************/ /*************/
/* RNG */ /* RNG */
/*************/ /*************/

View file

@ -7,9 +7,6 @@
TESTDIR=${1-.} TESTDIR=${1-.}
COMMAND=${2-run} COMMAND=${2-run}
TESTS="aes aesgcm dsa ecdsa hmac tls rng rsa sha tdea" TESTS="aes aesgcm dsa ecdsa hmac tls rng rsa sha tdea"
if [ ${NSS_ENABLE_ECC}x = 1x ]; then
TESTS=${TESTS} ecdsa
fi
for i in $TESTS for i in $TESTS
do do
echo "********************Running $i tests" echo "********************Running $i tests"

View file

@ -54,6 +54,10 @@ static char consoleName[] = {
static PRBool utf8DisplayEnabled = PR_FALSE; static PRBool utf8DisplayEnabled = PR_FALSE;
/* The minimum password/pin length (in Unicode characters) in FIPS mode,
* defined in lib/softoken/pkcs11i.h. */
#define FIPS_MIN_PIN 7
void void
SECU_EnableUtf8Display(PRBool enable) SECU_EnableUtf8Display(PRBool enable)
{ {
@ -236,7 +240,8 @@ SECU_GetModulePassword(PK11SlotInfo *slot, PRBool retry, void *arg)
sprintf(prompt, sprintf(prompt,
"Press Enter, then enter PIN for \"%s\" on external device.\n", "Press Enter, then enter PIN for \"%s\" on external device.\n",
PK11_GetTokenName(slot)); PK11_GetTokenName(slot));
(void)SECU_GetPasswordString(NULL, prompt); char *pw = SECU_GetPasswordString(NULL, prompt);
PORT_Free(pw);
/* Fall Through */ /* Fall Through */
case PW_PLAINTEXT: case PW_PLAINTEXT:
return PL_strdup(pwdata->data); return PL_strdup(pwdata->data);
@ -276,10 +281,25 @@ secu_InitSlotPassword(PK11SlotInfo *slot, PRBool retry, void *arg)
} }
/* we have no password, so initialize database with one */ /* we have no password, so initialize database with one */
if (PK11_IsFIPS()) {
PR_fprintf(PR_STDERR,
"Enter a password which will be used to encrypt your keys.\n"
"The password should be at least %d characters long,\n"
"and should consist of at least three character classes.\n"
"The available character classes are: digits (0-9), ASCII\n"
"lowercase letters, ASCII uppercase letters, ASCII\n"
"non-alphanumeric characters, and non-ASCII characters.\n\n"
"If an ASCII uppercase letter appears at the beginning of\n"
"the password, it is not counted toward its character class.\n"
"Similarly, if a digit appears at the end of the password,\n"
"it is not counted toward its character class.\n\n",
FIPS_MIN_PIN);
} else {
PR_fprintf(PR_STDERR, PR_fprintf(PR_STDERR,
"Enter a password which will be used to encrypt your keys.\n" "Enter a password which will be used to encrypt your keys.\n"
"The password should be at least 8 characters long,\n" "The password should be at least 8 characters long,\n"
"and should contain at least one non-alphabetic character.\n\n"); "and should contain at least one non-alphabetic character.\n\n");
}
output = fopen(consoleName, "w"); output = fopen(consoleName, "w");
if (output == NULL) { if (output == NULL) {
@ -465,48 +485,6 @@ SECU_ConfigDirectory(const char *base)
return buf; return buf;
} }
/*Turn off SSL for now */
/* This gets called by SSL when server wants our cert & key */
int
SECU_GetClientAuthData(void *arg, PRFileDesc *fd,
struct CERTDistNamesStr *caNames,
struct CERTCertificateStr **pRetCert,
struct SECKEYPrivateKeyStr **pRetKey)
{
SECKEYPrivateKey *key;
CERTCertificate *cert;
int errsave;
if (arg == NULL) {
fprintf(stderr, "no key/cert name specified for client auth\n");
return -1;
}
cert = PK11_FindCertFromNickname(arg, NULL);
errsave = PORT_GetError();
if (!cert) {
if (errsave == SEC_ERROR_BAD_PASSWORD)
fprintf(stderr, "Bad password\n");
else if (errsave > 0)
fprintf(stderr, "Unable to read cert (error %d)\n", errsave);
else if (errsave == SEC_ERROR_BAD_DATABASE)
fprintf(stderr, "Unable to get cert from database (%d)\n", errsave);
else
fprintf(stderr, "SECKEY_FindKeyByName: internal error %d\n", errsave);
return -1;
}
key = PK11_FindKeyByAnyCert(arg, NULL);
if (!key) {
fprintf(stderr, "Unable to get key (%d)\n", PORT_GetError());
return -1;
}
*pRetCert = cert;
*pRetKey = key;
return 0;
}
SECStatus SECStatus
SECU_ReadDERFromFile(SECItem *der, PRFileDesc *inFile, PRBool ascii, SECU_ReadDERFromFile(SECItem *der, PRFileDesc *inFile, PRBool ascii,
PRBool warnOnPrivateKeyInAsciiFile) PRBool warnOnPrivateKeyInAsciiFile)
@ -991,7 +969,7 @@ secu_PrintUniversalString(FILE *out, const SECItem *i, const char *m, int level)
for (s = my.data, d = tmp.data; len > 0; len--) { for (s = my.data, d = tmp.data; len > 0; len--) {
PRUint32 bmpChar = (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3]; PRUint32 bmpChar = (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3];
s += 4; s += 4;
if (!isprint(bmpChar)) if (!isprint(bmpChar & 0xFF))
goto loser; goto loser;
*d++ = (unsigned char)bmpChar; *d++ = (unsigned char)bmpChar;
} }
@ -1215,7 +1193,7 @@ secu_PrintRSAPSSParams(FILE *out, SECItem *value, char *m, int level)
SECU_Indent(out, level + 1); SECU_Indent(out, level + 1);
fprintf(out, "Salt length: default, %i (0x%2X)\n", 20, 20); fprintf(out, "Salt length: default, %i (0x%2X)\n", 20, 20);
} else { } else {
SECU_PrintInteger(out, &param.saltLength, "Salt Length", level + 1); SECU_PrintInteger(out, &param.saltLength, "Salt length", level + 1);
} }
} else { } else {
SECU_Indent(out, level + 1); SECU_Indent(out, level + 1);
@ -1335,15 +1313,12 @@ SECU_PrintAlgorithmID(FILE *out, SECAlgorithmID *a, char *m, int level)
return; return;
} }
if (algtag == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
secu_PrintRSAPSSParams(out, &a->parameters, "Parameters", level + 1);
return;
}
if (a->parameters.len == 0 || if (a->parameters.len == 0 ||
(a->parameters.len == 2 && (a->parameters.len == 2 &&
PORT_Memcmp(a->parameters.data, "\005\000", 2) == 0)) { PORT_Memcmp(a->parameters.data, "\005\000", 2) == 0)) {
/* No arguments or NULL argument */ /* No arguments or NULL argument */
} else if (algtag == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
secu_PrintRSAPSSParams(out, &a->parameters, "Parameters", level + 1);
} else { } else {
/* Print args to algorithm */ /* Print args to algorithm */
SECU_PrintAsHex(out, &a->parameters, "Args", level + 1); SECU_PrintAsHex(out, &a->parameters, "Args", level + 1);
@ -1390,7 +1365,6 @@ secu_PrintAttribute(FILE *out, SEC_PKCS7Attribute *attr, char *m, int level)
} }
} }
#ifndef NSS_DISABLE_ECC
static void static void
secu_PrintECPublicKey(FILE *out, SECKEYPublicKey *pk, char *m, int level) secu_PrintECPublicKey(FILE *out, SECKEYPublicKey *pk, char *m, int level)
{ {
@ -1409,7 +1383,6 @@ secu_PrintECPublicKey(FILE *out, SECKEYPublicKey *pk, char *m, int level)
SECU_PrintObjectID(out, &curveOID, "Curve", level + 1); SECU_PrintObjectID(out, &curveOID, "Curve", level + 1);
} }
} }
#endif /* NSS_DISABLE_ECC */
void void
SECU_PrintRSAPublicKey(FILE *out, SECKEYPublicKey *pk, char *m, int level) SECU_PrintRSAPublicKey(FILE *out, SECKEYPublicKey *pk, char *m, int level)
@ -1457,11 +1430,9 @@ secu_PrintSubjectPublicKeyInfo(FILE *out, PLArenaPool *arena,
SECU_PrintDSAPublicKey(out, pk, "DSA Public Key", level + 1); SECU_PrintDSAPublicKey(out, pk, "DSA Public Key", level + 1);
break; break;
#ifndef NSS_DISABLE_ECC
case ecKey: case ecKey:
secu_PrintECPublicKey(out, pk, "EC Public Key", level + 1); secu_PrintECPublicKey(out, pk, "EC Public Key", level + 1);
break; break;
#endif
case dhKey: case dhKey:
case fortezzaKey: case fortezzaKey:
@ -3614,44 +3585,6 @@ loser:
return rv; return rv;
} }
#if 0
/* we need access to the private function cert_FindExtension for this code to work */
CERTAuthKeyID *
SECU_FindCRLAuthKeyIDExten (PLArenaPool *arena, CERTSignedCrl *scrl)
{
SECItem encodedExtenValue;
SECStatus rv;
CERTAuthKeyID *ret;
CERTCrl* crl;
if (!scrl) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return NULL;
}
crl = &scrl->crl;
encodedExtenValue.data = NULL;
encodedExtenValue.len = 0;
rv = cert_FindExtension(crl->extensions, SEC_OID_X509_AUTH_KEY_ID,
&encodedExtenValue);
if ( rv != SECSuccess ) {
return (NULL);
}
ret = CERT_DecodeAuthKeyID (arena, &encodedExtenValue);
PORT_Free(encodedExtenValue.data);
encodedExtenValue.data = NULL;
return(ret);
}
#endif
/* /*
* Find the issuer of a Crl. Use the authorityKeyID if it exists. * Find the issuer of a Crl. Use the authorityKeyID if it exists.
*/ */
@ -3725,7 +3658,7 @@ SECU_FindCertByNicknameOrFilename(CERTCertDBHandle *handle,
void *pwarg) void *pwarg)
{ {
CERTCertificate *the_cert; CERTCertificate *the_cert;
the_cert = CERT_FindCertByNicknameOrEmailAddr(handle, name); the_cert = CERT_FindCertByNicknameOrEmailAddrCX(handle, name, pwarg);
if (the_cert) { if (the_cert) {
return the_cert; return the_cert;
} }

View file

@ -78,16 +78,14 @@ test_list2(int argc, char *argv[])
for (i = 0; i < size; i++) for (i = 0; i < size; i++)
for (j = 9; j > i; j--) { for (j = 9; j > i; j--) {
PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_GetItem(list, j, &obj, plContext)); PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_GetItem(list, j, &obj, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_GetItem(list, j - PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_GetItem(list, j - 1,
1,
&obj2, plContext)); &obj2, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Object_Compare(obj, obj2, &cmpResult, plContext)); PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Object_Compare(obj, obj2, &cmpResult, plContext));
if (cmpResult < 0) { if (cmpResult < 0) {
/* Exchange the items */ /* Exchange the items */
PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_SetItem(list, j, obj2, plContext)); PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_SetItem(list, j, obj2, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_SetItem(list, j - PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_SetItem(list, j - 1,
1,
obj, plContext)); obj, plContext));
} }
/* DecRef objects */ /* DecRef objects */

View file

@ -10,7 +10,9 @@
#include <errno.h> #include <errno.h>
#include <stdio.h> #include <stdio.h>
#include "nss.h"
#include "secport.h" #include "secport.h"
#include "secutil.h"
#include "ssl.h" #include "ssl.h"
int int
@ -19,6 +21,43 @@ main(int argc, char **argv)
const PRUint16 *cipherSuites = SSL_ImplementedCiphers; const PRUint16 *cipherSuites = SSL_ImplementedCiphers;
int i; int i;
int errCount = 0; int errCount = 0;
SECStatus rv;
PRErrorCode err;
char *certDir = NULL;
/* load policy from $SSL_DIR/pkcs11.txt, for testing */
certDir = SECU_DefaultSSLDir();
if (certDir) {
rv = NSS_Init(certDir);
} else {
rv = NSS_NoDB_Init(NULL);
}
if (rv != SECSuccess) {
err = PR_GetError();
++errCount;
fprintf(stderr, "NSS_Init failed: %s\n", PORT_ErrorToString(err));
goto out;
}
/* apply policy */
rv = NSS_SetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, NSS_USE_POLICY_IN_SSL, 0);
if (rv != SECSuccess) {
err = PR_GetError();
++errCount;
fprintf(stderr, "NSS_SetAlgorithmPolicy failed: %s\n",
PORT_ErrorToString(err));
goto out;
}
/* update the default cipher suites according to the policy */
rv = SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);
if (rv != SECSuccess) {
err = PR_GetError();
++errCount;
fprintf(stderr, "SSL_OptionSetDefault failed: %s\n",
PORT_ErrorToString(err));
goto out;
}
fputs("This version of libSSL supports these cipher suites:\n\n", stdout); fputs("This version of libSSL supports these cipher suites:\n\n", stdout);
@ -58,5 +97,14 @@ main(int argc, char **argv)
info.isFIPS ? "FIPS" : "", info.isFIPS ? "FIPS" : "",
info.nonStandard ? "nonStandard" : ""); info.nonStandard ? "nonStandard" : "");
} }
out:
rv = NSS_Shutdown();
if (rv != SECSuccess) {
err = PR_GetError();
++errCount;
fprintf(stderr, "NSS_Shutdown failed: %s\n", PORT_ErrorToString(err));
}
return errCount; return errCount;
} }

View file

@ -63,6 +63,7 @@ NSS_SRCDIRS = \
pp \ pp \
pwdecrypt \ pwdecrypt \
rsaperf \ rsaperf \
rsapoptst \
sdrtest \ sdrtest \
selfserv \ selfserv \
signtool \ signtool \

View file

@ -57,6 +57,7 @@ typedef enum {
UNSPECIFIED_ERR, UNSPECIFIED_ERR,
NOCERTDB_MISUSE_ERR, NOCERTDB_MISUSE_ERR,
NSS_INITIALIZE_FAILED_ERR, NSS_INITIALIZE_FAILED_ERR,
INITPW_FAILED_ERR,
LAST_ERR /* must be last */ LAST_ERR /* must be last */
} Error; } Error;
@ -109,8 +110,9 @@ static char *errStrings[] = {
"ERROR: Failed to change default.\n", "ERROR: Failed to change default.\n",
"ERROR: Unable to read from standard input.\n", "ERROR: Unable to read from standard input.\n",
"ERROR: Unknown error occurred.\n", "ERROR: Unknown error occurred.\n",
"ERROR: -nocertdb option can only be used with the -jar command.\n" "ERROR: -nocertdb option can only be used with the -jar command.\n",
"ERROR: NSS_Initialize() failed.\n" "ERROR: NSS_Initialize() failed.\n",
"ERROR: Unable to set initial password on the database.\n"
}; };
typedef enum { typedef enum {

View file

@ -975,8 +975,7 @@ Pk11Install_Platform_Print(Pk11Install_Platform* _this, int pad)
printf("Doesn't use equiv\n"); printf("Doesn't use equiv\n");
} }
PAD(pad); PAD(pad);
printf("Module File: %s\n", _this->moduleFile ? _this->moduleFile printf("Module File: %s\n", _this->moduleFile ? _this->moduleFile : "<NULL>");
: "<NULL>");
PAD(pad); PAD(pad);
printf("mechFlags: %lx\n", _this->mechFlags); printf("mechFlags: %lx\n", _this->mechFlags);
PAD(pad); PAD(pad);

View file

@ -865,7 +865,7 @@ main(int argc, char* argv[])
errcode = ChangePW(tokenName, pwFile, newpwFile); errcode = ChangePW(tokenName, pwFile, newpwFile);
break; break;
case CREATE_COMMAND: case CREATE_COMMAND:
/* The work was already done in init_crypto() */ errcode = InitPW();
break; break;
case DEFAULT_COMMAND: case DEFAULT_COMMAND:
errcode = SetDefaultModule(moduleName, slotName, mechanisms); errcode = SetDefaultModule(moduleName, slotName, mechanisms);

View file

@ -29,6 +29,7 @@ Error AddModule(char *moduleName, char *libFile, char *ciphers,
Error DeleteModule(char *moduleName); Error DeleteModule(char *moduleName);
Error ListModule(char *moduleName); Error ListModule(char *moduleName);
Error ListModules(); Error ListModules();
Error InitPW(void);
Error ChangePW(char *tokenName, char *pwFile, char *newpwFile); Error ChangePW(char *tokenName, char *pwFile, char *newpwFile);
Error EnableModule(char *moduleName, char *slotName, PRBool enable); Error EnableModule(char *moduleName, char *slotName, PRBool enable);
Error RawAddModule(char *dbmodulespec, char *modulespec); Error RawAddModule(char *dbmodulespec, char *modulespec);

View file

@ -668,6 +668,39 @@ loser:
return rv; return rv;
} }
/************************************************************************
*
* I n i t P W
*/
Error
InitPW(void)
{
PK11SlotInfo *slot;
Error ret = UNSPECIFIED_ERR;
slot = PK11_GetInternalKeySlot();
if (!slot) {
PR_fprintf(PR_STDERR, errStrings[NO_SUCH_TOKEN_ERR], "internal");
return NO_SUCH_TOKEN_ERR;
}
/* Set the initial password to empty */
if (PK11_NeedUserInit(slot)) {
if (PK11_InitPin(slot, NULL, "") != SECSuccess) {
PR_fprintf(PR_STDERR, errStrings[INITPW_FAILED_ERR]);
ret = INITPW_FAILED_ERR;
goto loser;
}
}
ret = SUCCESS;
loser:
PK11_FreeSlot(slot);
return ret;
}
/************************************************************************ /************************************************************************
* *
* C h a n g e P W * C h a n g e P W
@ -695,7 +728,7 @@ ChangePW(char *tokenName, char *pwFile, char *newpwFile)
ret = BAD_PW_ERR; ret = BAD_PW_ERR;
goto loser; goto loser;
} }
} else { } else if (PK11_NeedLogin(slot)) {
for (matching = PR_FALSE; !matching;) { for (matching = PR_FALSE; !matching;) {
oldpw = SECU_GetPasswordString(NULL, "Enter old password: "); oldpw = SECU_GetPasswordString(NULL, "Enter old password: ");
if (PK11_CheckUserPassword(slot, oldpw) == SECSuccess) { if (PK11_CheckUserPassword(slot, oldpw) == SECSuccess) {

View file

@ -502,8 +502,7 @@ do_list_certs(const char *progName, int log)
SECU_PrintCertNickname(node, stderr); SECU_PrintCertNickname(node, stderr);
if (log) { if (log) {
fprintf(stderr, "* Slot=%s*\n", cert->slot ? PK11_GetTokenName(cert->slot) fprintf(stderr, "* Slot=%s*\n", cert->slot ? PK11_GetTokenName(cert->slot) : "none");
: "none");
fprintf(stderr, "* Nickname=%s*\n", cert->nickname); fprintf(stderr, "* Nickname=%s*\n", cert->nickname);
fprintf(stderr, "* Subject=<%s>*\n", cert->subjectName); fprintf(stderr, "* Subject=<%s>*\n", cert->subjectName);
fprintf(stderr, "* Issuer=<%s>*\n", cert->issuerName); fprintf(stderr, "* Issuer=<%s>*\n", cert->issuerName);

View file

@ -2169,36 +2169,22 @@ PKM_Mechanism(CK_FUNCTION_LIST_PTR pFunctionList,
PKM_LogIt(" ulMinKeySize = %lu\n", minfo.ulMinKeySize); PKM_LogIt(" ulMinKeySize = %lu\n", minfo.ulMinKeySize);
PKM_LogIt(" ulMaxKeySize = %lu\n", minfo.ulMaxKeySize); PKM_LogIt(" ulMaxKeySize = %lu\n", minfo.ulMaxKeySize);
PKM_LogIt(" flags = 0x%08x\n", minfo.flags); PKM_LogIt(" flags = 0x%08x\n", minfo.flags);
PKM_LogIt(" -> HW = %s\n", minfo.flags & CKF_HW ? "TRUE" PKM_LogIt(" -> HW = %s\n", minfo.flags & CKF_HW ? "TRUE" : "FALSE");
: "FALSE"); PKM_LogIt(" -> ENCRYPT = %s\n", minfo.flags & CKF_ENCRYPT ? "TRUE" : "FALSE");
PKM_LogIt(" -> ENCRYPT = %s\n", minfo.flags & CKF_ENCRYPT ? "TRUE" PKM_LogIt(" -> DECRYPT = %s\n", minfo.flags & CKF_DECRYPT ? "TRUE" : "FALSE");
: "FALSE"); PKM_LogIt(" -> DIGEST = %s\n", minfo.flags & CKF_DIGEST ? "TRUE" : "FALSE");
PKM_LogIt(" -> DECRYPT = %s\n", minfo.flags & CKF_DECRYPT ? "TRUE" PKM_LogIt(" -> SIGN = %s\n", minfo.flags & CKF_SIGN ? "TRUE" : "FALSE");
: "FALSE"); PKM_LogIt(" -> SIGN_RECOVER = %s\n", minfo.flags & CKF_SIGN_RECOVER ? "TRUE" : "FALSE");
PKM_LogIt(" -> DIGEST = %s\n", minfo.flags & CKF_DIGEST ? "TRUE" PKM_LogIt(" -> VERIFY = %s\n", minfo.flags & CKF_VERIFY ? "TRUE" : "FALSE");
: "FALSE");
PKM_LogIt(" -> SIGN = %s\n", minfo.flags & CKF_SIGN ? "TRUE"
: "FALSE");
PKM_LogIt(" -> SIGN_RECOVER = %s\n", minfo.flags &
CKF_SIGN_RECOVER
? "TRUE"
: "FALSE");
PKM_LogIt(" -> VERIFY = %s\n", minfo.flags & CKF_VERIFY ? "TRUE"
: "FALSE");
PKM_LogIt(" -> VERIFY_RECOVER = %s\n", PKM_LogIt(" -> VERIFY_RECOVER = %s\n",
minfo.flags & CKF_VERIFY_RECOVER ? "TRUE" : "FALSE"); minfo.flags & CKF_VERIFY_RECOVER ? "TRUE" : "FALSE");
PKM_LogIt(" -> GENERATE = %s\n", minfo.flags & CKF_GENERATE ? "TRUE" PKM_LogIt(" -> GENERATE = %s\n", minfo.flags & CKF_GENERATE ? "TRUE" : "FALSE");
: "FALSE");
PKM_LogIt(" -> GENERATE_KEY_PAIR = %s\n", PKM_LogIt(" -> GENERATE_KEY_PAIR = %s\n",
minfo.flags & CKF_GENERATE_KEY_PAIR ? "TRUE" : "FALSE"); minfo.flags & CKF_GENERATE_KEY_PAIR ? "TRUE" : "FALSE");
PKM_LogIt(" -> WRAP = %s\n", minfo.flags & CKF_WRAP ? "TRUE" PKM_LogIt(" -> WRAP = %s\n", minfo.flags & CKF_WRAP ? "TRUE" : "FALSE");
: "FALSE"); PKM_LogIt(" -> UNWRAP = %s\n", minfo.flags & CKF_UNWRAP ? "TRUE" : "FALSE");
PKM_LogIt(" -> UNWRAP = %s\n", minfo.flags & CKF_UNWRAP ? "TRUE" PKM_LogIt(" -> DERIVE = %s\n", minfo.flags & CKF_DERIVE ? "TRUE" : "FALSE");
: "FALSE"); PKM_LogIt(" -> EXTENSION = %s\n", minfo.flags & CKF_EXTENSION ? "TRUE" : "FALSE");
PKM_LogIt(" -> DERIVE = %s\n", minfo.flags & CKF_DERIVE ? "TRUE"
: "FALSE");
PKM_LogIt(" -> EXTENSION = %s\n", minfo.flags & CKF_EXTENSION ? "TRUE"
: "FALSE");
PKM_LogIt("\n"); PKM_LogIt("\n");
} }
@ -3604,24 +3590,12 @@ PKM_FindAllObjects(CK_FUNCTION_LIST_PTR pFunctionList,
PKM_LogIt(" state = %lu\n", sinfo.state); PKM_LogIt(" state = %lu\n", sinfo.state);
PKM_LogIt(" flags = 0x%08x\n", sinfo.flags); PKM_LogIt(" flags = 0x%08x\n", sinfo.flags);
#ifdef CKF_EXCLUSIVE_SESSION #ifdef CKF_EXCLUSIVE_SESSION
PKM_LogIt(" -> EXCLUSIVE SESSION = %s\n", sinfo.flags & PKM_LogIt(" -> EXCLUSIVE SESSION = %s\n", sinfo.flags & CKF_EXCLUSIVE_SESSION ? "TRUE" : "FALSE");
CKF_EXCLUSIVE_SESSION
? "TRUE"
: "FALSE");
#endif /* CKF_EXCLUSIVE_SESSION */ #endif /* CKF_EXCLUSIVE_SESSION */
PKM_LogIt(" -> RW SESSION = %s\n", sinfo.flags & PKM_LogIt(" -> RW SESSION = %s\n", sinfo.flags & CKF_RW_SESSION ? "TRUE" : "FALSE");
CKF_RW_SESSION PKM_LogIt(" -> SERIAL SESSION = %s\n", sinfo.flags & CKF_SERIAL_SESSION ? "TRUE" : "FALSE");
? "TRUE"
: "FALSE");
PKM_LogIt(" -> SERIAL SESSION = %s\n", sinfo.flags &
CKF_SERIAL_SESSION
? "TRUE"
: "FALSE");
#ifdef CKF_INSERTION_CALLBACK #ifdef CKF_INSERTION_CALLBACK
PKM_LogIt(" -> INSERTION CALLBACK = %s\n", sinfo.flags & PKM_LogIt(" -> INSERTION CALLBACK = %s\n", sinfo.flags & CKF_INSERTION_CALLBACK ? "TRUE" : "FALSE");
CKF_INSERTION_CALLBACK
? "TRUE"
: "FALSE");
#endif /* CKF_INSERTION_CALLBACK */ #endif /* CKF_INSERTION_CALLBACK */
PKM_LogIt(" ulDeviceError = %lu\n", sinfo.ulDeviceError); PKM_LogIt(" ulDeviceError = %lu\n", sinfo.ulDeviceError);
PKM_LogIt("\n"); PKM_LogIt("\n");

View file

@ -23,6 +23,7 @@
static char *progName; static char *progName;
PRBool pk12_debugging = PR_FALSE; PRBool pk12_debugging = PR_FALSE;
PRBool dumpRawFile; PRBool dumpRawFile;
static PRBool pk12uForceUnicode;
PRIntn pk12uErrno = 0; PRIntn pk12uErrno = 0;
@ -357,6 +358,7 @@ p12U_ReadPKCS12File(SECItem *uniPwp, char *in_file, PK11SlotInfo *slot,
SECItem p12file = { 0 }; SECItem p12file = { 0 };
SECStatus rv = SECFailure; SECStatus rv = SECFailure;
PRBool swapUnicode = PR_FALSE; PRBool swapUnicode = PR_FALSE;
PRBool forceUnicode = pk12uForceUnicode;
PRBool trypw; PRBool trypw;
int error; int error;
@ -424,6 +426,18 @@ p12U_ReadPKCS12File(SECItem *uniPwp, char *in_file, PK11SlotInfo *slot,
SEC_PKCS12DecoderFinish(p12dcx); SEC_PKCS12DecoderFinish(p12dcx);
uniPwp->len = 0; uniPwp->len = 0;
trypw = PR_TRUE; trypw = PR_TRUE;
} else if (forceUnicode == pk12uForceUnicode) {
/* try again with a different password encoding */
forceUnicode = !pk12uForceUnicode;
rv = NSS_OptionSet(__NSS_PKCS12_DECODE_FORCE_UNICODE,
forceUnicode);
if (rv != SECSuccess) {
SECU_PrintError(progName, "PKCS12 decoding failed to set option");
pk12uErrno = PK12UERR_DECODEVERIFY;
break;
}
SEC_PKCS12DecoderFinish(p12dcx);
trypw = PR_TRUE;
} else { } else {
SECU_PrintError(progName, "PKCS12 decode not verified"); SECU_PrintError(progName, "PKCS12 decode not verified");
pk12uErrno = PK12UERR_DECODEVERIFY; pk12uErrno = PK12UERR_DECODEVERIFY;
@ -431,6 +445,15 @@ p12U_ReadPKCS12File(SECItem *uniPwp, char *in_file, PK11SlotInfo *slot,
} }
} }
} while (trypw == PR_TRUE); } while (trypw == PR_TRUE);
/* revert the option setting */
if (forceUnicode != pk12uForceUnicode) {
rv = NSS_OptionSet(__NSS_PKCS12_DECODE_FORCE_UNICODE, pk12uForceUnicode);
if (rv != SECSuccess) {
SECU_PrintError(progName, "PKCS12 decoding failed to set option");
pk12uErrno = PK12UERR_DECODEVERIFY;
}
}
/* rv has been set at this point */ /* rv has been set at this point */
done: done:
@ -470,6 +493,8 @@ P12U_ImportPKCS12Object(char *in_file, PK11SlotInfo *slot,
{ {
SEC_PKCS12DecoderContext *p12dcx = NULL; SEC_PKCS12DecoderContext *p12dcx = NULL;
SECItem uniPwitem = { 0 }; SECItem uniPwitem = { 0 };
PRBool forceUnicode = pk12uForceUnicode;
PRBool trypw;
SECStatus rv = SECFailure; SECStatus rv = SECFailure;
rv = P12U_InitSlot(slot, slotPw); rv = P12U_InitSlot(slot, slotPw);
@ -480,6 +505,8 @@ P12U_ImportPKCS12Object(char *in_file, PK11SlotInfo *slot,
return rv; return rv;
} }
do {
trypw = PR_FALSE; /* normally we do this once */
rv = SECFailure; rv = SECFailure;
p12dcx = p12U_ReadPKCS12File(&uniPwitem, in_file, slot, slotPw, p12FilePw); p12dcx = p12U_ReadPKCS12File(&uniPwitem, in_file, slot, slotPw, p12FilePw);
@ -500,12 +527,41 @@ P12U_ImportPKCS12Object(char *in_file, PK11SlotInfo *slot,
} }
/* stuff 'em in */ /* stuff 'em in */
if (forceUnicode != pk12uForceUnicode) {
rv = NSS_OptionSet(__NSS_PKCS12_DECODE_FORCE_UNICODE,
forceUnicode);
if (rv != SECSuccess) {
SECU_PrintError(progName, "PKCS12 decode set option failed");
pk12uErrno = PK12UERR_DECODEIMPTBAGS;
goto loser;
}
}
rv = SEC_PKCS12DecoderImportBags(p12dcx); rv = SEC_PKCS12DecoderImportBags(p12dcx);
if (rv != SECSuccess) { if (rv != SECSuccess) {
if (PR_GetError() == SEC_ERROR_PKCS12_UNABLE_TO_IMPORT_KEY &&
forceUnicode == pk12uForceUnicode) {
/* try again with a different password encoding */
forceUnicode = !pk12uForceUnicode;
SEC_PKCS12DecoderFinish(p12dcx);
SECITEM_ZfreeItem(&uniPwitem, PR_FALSE);
trypw = PR_TRUE;
} else {
SECU_PrintError(progName, "PKCS12 decode import bags failed"); SECU_PrintError(progName, "PKCS12 decode import bags failed");
pk12uErrno = PK12UERR_DECODEIMPTBAGS; pk12uErrno = PK12UERR_DECODEIMPTBAGS;
goto loser; goto loser;
} }
}
} while (trypw);
/* revert the option setting */
if (forceUnicode != pk12uForceUnicode) {
rv = NSS_OptionSet(__NSS_PKCS12_DECODE_FORCE_UNICODE, pk12uForceUnicode);
if (rv != SECSuccess) {
SECU_PrintError(progName, "PKCS12 decode set option failed");
pk12uErrno = PK12UERR_DECODEIMPTBAGS;
goto loser;
}
}
fprintf(stdout, "%s: PKCS12 IMPORT SUCCESSFUL\n", progName); fprintf(stdout, "%s: PKCS12 IMPORT SUCCESSFUL\n", progName);
rv = SECSuccess; rv = SECSuccess;
@ -947,6 +1003,7 @@ main(int argc, char **argv)
int keyLen = 0; int keyLen = 0;
int certKeyLen = 0; int certKeyLen = 0;
secuCommand pk12util; secuCommand pk12util;
PRInt32 forceUnicode;
#ifdef _CRTDBG_MAP_ALLOC #ifdef _CRTDBG_MAP_ALLOC
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
@ -978,6 +1035,14 @@ main(int argc, char **argv)
Usage(progName); Usage(progName);
} }
rv = NSS_OptionGet(__NSS_PKCS12_DECODE_FORCE_UNICODE, &forceUnicode);
if (rv != SECSuccess) {
SECU_PrintError(progName,
"Failed to get NSS_PKCS12_DECODE_FORCE_UNICODE option");
Usage(progName);
}
pk12uForceUnicode = forceUnicode;
slotname = SECU_GetOptionArg(&pk12util, opt_TokenName); slotname = SECU_GetOptionArg(&pk12util, opt_TokenName);
import_file = (pk12util.options[opt_List].activated) ? SECU_GetOptionArg(&pk12util, opt_List) import_file = (pk12util.options[opt_List].activated) ? SECU_GetOptionArg(&pk12util, opt_List)

View file

@ -84,6 +84,8 @@ main(int argc, char **argv)
if (!inFile) { if (!inFile) {
fprintf(stderr, "%s: unable to open \"%s\" for reading\n", fprintf(stderr, "%s: unable to open \"%s\" for reading\n",
progName, optstate->value); progName, optstate->value);
PORT_Free(typeTag);
PL_DestroyOptState(optstate);
return -1; return -1;
} }
break; break;
@ -93,6 +95,8 @@ main(int argc, char **argv)
if (!outFile) { if (!outFile) {
fprintf(stderr, "%s: unable to open \"%s\" for writing\n", fprintf(stderr, "%s: unable to open \"%s\" for writing\n",
progName, optstate->value); progName, optstate->value);
PORT_Free(typeTag);
PL_DestroyOptState(optstate);
return -1; return -1;
} }
break; break;

View file

@ -671,8 +671,7 @@ main(int argc, char **argv)
printf("%ld iterations in %s\n", printf("%ld iterations in %s\n",
iters, TimingGenerateString(timeCtx)); iters, TimingGenerateString(timeCtx));
printf("%.2f operations/s .\n", ((double)(iters) * (double)1000000.0) / printf("%.2f operations/s .\n", ((double)(iters) * (double)1000000.0) / (double)timeCtx->interval);
(double)timeCtx->interval);
TimingDivide(timeCtx, iters); TimingDivide(timeCtx, iters);
printf("one operation every %s\n", TimingGenerateString(timeCtx)); printf("one operation every %s\n", TimingGenerateString(timeCtx));

View file

@ -23,7 +23,7 @@ static const struct test_args test_array[] = {
{ "d_n_q", 0x02, "private exponent, modulus, prime2" }, { "d_n_q", 0x02, "private exponent, modulus, prime2" },
{ "d_p_q", 0x04, "private exponent, prime1, prime2" }, { "d_p_q", 0x04, "private exponent, prime1, prime2" },
{ "e_d_q", 0x08, "public exponent, private exponent, prime2" }, { "e_d_q", 0x08, "public exponent, private exponent, prime2" },
{ "e_d_n", 0x10, "public exponent, private exponent, moduls" } { "e_d_n", 0x10, "public exponent, private exponent, modulus" }
}; };
static const int test_array_size = static const int test_array_size =
(sizeof(test_array) / sizeof(struct test_args)); (sizeof(test_array) / sizeof(struct test_args));
@ -58,6 +58,7 @@ const static CK_ATTRIBUTE rsaTemplate[] = {
{ CKA_TOKEN, NULL, 0 }, { CKA_TOKEN, NULL, 0 },
{ CKA_SENSITIVE, NULL, 0 }, { CKA_SENSITIVE, NULL, 0 },
{ CKA_PRIVATE, NULL, 0 }, { CKA_PRIVATE, NULL, 0 },
{ CKA_ID, NULL, 0 },
{ CKA_MODULUS, NULL, 0 }, { CKA_MODULUS, NULL, 0 },
{ CKA_PUBLIC_EXPONENT, NULL, 0 }, { CKA_PUBLIC_EXPONENT, NULL, 0 },
{ CKA_PRIVATE_EXPONENT, NULL, 0 }, { CKA_PRIVATE_EXPONENT, NULL, 0 },
@ -123,48 +124,79 @@ fail:
#define ATTR_STRING(x) getNameFromAttribute(x) #define ATTR_STRING(x) getNameFromAttribute(x)
void static void
dumpTemplate(CK_ATTRIBUTE *template, int start, int end) dumphex(FILE *file, const unsigned char *cpval, int start, int end)
{ {
int i, j; int i;
for (i = 0; i < end; i++) { for (i = start; i < end; i++) {
if ((i % 16) == 0)
fprintf(file, "\n ");
fprintf(file, " %02x", cpval[i]);
}
return;
}
void
dumpTemplate(FILE *file, const CK_ATTRIBUTE *template, int start, int end)
{
int i;
for (i = start; i < end; i++) {
unsigned char cval; unsigned char cval;
CK_ULONG ulval; CK_ULONG ulval;
unsigned char *cpval; const unsigned char *cpval;
fprintf(stderr, "%s:", ATTR_STRING(template[i].type)); fprintf(file, "%s:", ATTR_STRING(template[i].type));
switch (template[i].ulValueLen) { switch (template[i].ulValueLen) {
case 1: case 1:
cval = *(unsigned char *)template[i].pValue; cval = *(unsigned char *)template[i].pValue;
switch (cval) { switch (cval) {
case 0: case 0:
fprintf(stderr, " false"); fprintf(file, " false");
break; break;
case 1: case 1:
fprintf(stderr, " true"); fprintf(file, " true");
break; break;
default: default:
fprintf(stderr, " %d (=0x%02x,'%c')", cval, cval, cval); fprintf(file, " %d (=0x%02x,'%c')", cval, cval, cval);
break; break;
} }
break; break;
case sizeof(CK_ULONG): case sizeof(CK_ULONG):
ulval = *(CK_ULONG *)template[i].pValue; ulval = *(CK_ULONG *)template[i].pValue;
fprintf(stderr, " %ld (=0x%04lx)", ulval, ulval); fprintf(file, " %ld (=0x%04lx)", ulval, ulval);
break; break;
default: default:
cpval = (unsigned char *)template[i].pValue; cpval = (const unsigned char *)template[i].pValue;
for (j = 0; j < template[i].ulValueLen; j++) { dumphex(file, cpval, 0, template[i].ulValueLen);
if ((j % 16) == 0)
fprintf(stderr, "\n ");
fprintf(stderr, " %02x", cpval[j]);
}
break; break;
} }
fprintf(stderr, "\n"); fprintf(file, "\n");
} }
} }
void
dumpItem(FILE *file, const SECItem *item)
{
const unsigned char *cpval;
if (item == NULL) {
fprintf(file, " pNULL ");
return;
}
if (item->data == NULL) {
fprintf(file, " NULL ");
return;
}
if (item->len == 0) {
fprintf(file, " Empty ");
return;
}
cpval = item->data;
dumphex(file, cpval, 0, item->len);
fprintf(file, " ");
return;
}
PRBool PRBool
rsaKeysAreEqual(PK11ObjectType srcType, void *src, rsaKeysAreEqual(PK11ObjectType srcType, void *src,
PK11ObjectType destType, void *dest) PK11ObjectType destType, void *dest)
@ -184,13 +216,16 @@ rsaKeysAreEqual(PK11ObjectType srcType, void *src,
printf("Could read source key\n"); printf("Could read source key\n");
return PR_FALSE; return PR_FALSE;
} }
readKey(destType, dest, destTemplate, 0, RSA_ATTRIBUTES); rv = readKey(destType, dest, destTemplate, 0, RSA_ATTRIBUTES);
if (rv != SECSuccess) { if (rv != SECSuccess) {
printf("Could read dest key\n"); printf("Could read dest key\n");
return PR_FALSE; return PR_FALSE;
} }
for (i = 0; i < RSA_ATTRIBUTES; i++) { for (i = 0; i < RSA_ATTRIBUTES; i++) {
if (srcTemplate[i].type == CKA_ID) {
continue; /* we purposefully make the CKA_ID different */
}
if (srcTemplate[i].ulValueLen != destTemplate[i].ulValueLen) { if (srcTemplate[i].ulValueLen != destTemplate[i].ulValueLen) {
printf("key->%s not equal src_len = %ld, dest_len=%ld\n", printf("key->%s not equal src_len = %ld, dest_len=%ld\n",
ATTR_STRING(srcTemplate[i].type), ATTR_STRING(srcTemplate[i].type),
@ -204,18 +239,22 @@ rsaKeysAreEqual(PK11ObjectType srcType, void *src,
} }
if (!areEqual) { if (!areEqual) {
fprintf(stderr, "original key:\n"); fprintf(stderr, "original key:\n");
dumpTemplate(srcTemplate, 0, RSA_ATTRIBUTES); dumpTemplate(stderr, srcTemplate, 0, RSA_ATTRIBUTES);
fprintf(stderr, "created key:\n"); fprintf(stderr, "created key:\n");
dumpTemplate(destTemplate, 0, RSA_ATTRIBUTES); dumpTemplate(stderr, destTemplate, 0, RSA_ATTRIBUTES);
} }
resetTemplate(srcTemplate, 0, RSA_ATTRIBUTES);
resetTemplate(destTemplate, 0, RSA_ATTRIBUTES);
return areEqual; return areEqual;
} }
static int exp_exp_prime_fail_count = 0; static int exp_exp_prime_fail_count = 0;
#define LEAK_ID 0xf
static int static int
doRSAPopulateTest(unsigned int keySize, unsigned long exponent, doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
int mask, void *pwarg) int mask, int round, void *pwarg)
{ {
SECKEYPrivateKey *rsaPrivKey; SECKEYPrivateKey *rsaPrivKey;
SECKEYPublicKey *rsaPubKey; SECKEYPublicKey *rsaPubKey;
@ -227,7 +266,10 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
CK_OBJECT_CLASS obj_class = CKO_PRIVATE_KEY; CK_OBJECT_CLASS obj_class = CKO_PRIVATE_KEY;
CK_KEY_TYPE key_type = CKK_RSA; CK_KEY_TYPE key_type = CKK_RSA;
CK_BBOOL ck_false = CK_FALSE; CK_BBOOL ck_false = CK_FALSE;
CK_BYTE cka_id[2] = { 0, 0 };
int failed = 0; int failed = 0;
int leak_found; /* did we find the expected leak */
int expect_leak = 0; /* are we expecting a leak? */
rsaParams.pe = exponent; rsaParams.pe = exponent;
rsaParams.keySizeInBits = keySize; rsaParams.keySizeInBits = keySize;
@ -259,11 +301,15 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
tstTemplate[3].ulValueLen = sizeof(ck_false); tstTemplate[3].ulValueLen = sizeof(ck_false);
tstTemplate[4].pValue = &ck_false; tstTemplate[4].pValue = &ck_false;
tstTemplate[4].ulValueLen = sizeof(ck_false); tstTemplate[4].ulValueLen = sizeof(ck_false);
tstHeaderCount = 5; tstTemplate[5].pValue = &cka_id[0];
tstTemplate[5].ulValueLen = sizeof(cka_id);
tstHeaderCount = 6;
cka_id[0] = round;
if (mask & 1) { if (mask & 1) {
printf("%s\n", test_array[1].description); printf("%s\n", test_array[1].description);
resetTemplate(tstTemplate, tstHeaderCount, RSA_ATTRIBUTES); resetTemplate(tstTemplate, tstHeaderCount, RSA_ATTRIBUTES);
cka_id[1] = 0;
copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate, copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate,
tstHeaderCount, CKA_PUBLIC_EXPONENT); tstHeaderCount, CKA_PUBLIC_EXPONENT);
copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate, copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate,
@ -271,7 +317,7 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate, copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate,
tstHeaderCount + 2, CKA_PRIME_1); tstHeaderCount + 2, CKA_PRIME_1);
tstPrivKey = PK11_CreateGenericObject(slot, tstTemplate, tstPrivKey = PK11_CreateManagedGenericObject(slot, tstTemplate,
tstHeaderCount + tstHeaderCount +
3, 3,
PR_FALSE); PR_FALSE);
@ -290,6 +336,7 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
printf("%s\n", test_array[2].description); printf("%s\n", test_array[2].description);
/* test the basic2 case, public exponent, modulus, prime2 */ /* test the basic2 case, public exponent, modulus, prime2 */
resetTemplate(tstTemplate, tstHeaderCount, RSA_ATTRIBUTES); resetTemplate(tstTemplate, tstHeaderCount, RSA_ATTRIBUTES);
cka_id[1] = 1;
copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate, copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate,
tstHeaderCount, CKA_PUBLIC_EXPONENT); tstHeaderCount, CKA_PUBLIC_EXPONENT);
copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate, copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate,
@ -299,7 +346,7 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
/* test with q in the prime1 position */ /* test with q in the prime1 position */
tstTemplate[tstHeaderCount + 2].type = CKA_PRIME_1; tstTemplate[tstHeaderCount + 2].type = CKA_PRIME_1;
tstPrivKey = PK11_CreateGenericObject(slot, tstTemplate, tstPrivKey = PK11_CreateManagedGenericObject(slot, tstTemplate,
tstHeaderCount + tstHeaderCount +
3, 3,
PR_FALSE); PR_FALSE);
@ -318,6 +365,7 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
printf("%s\n", test_array[3].description); printf("%s\n", test_array[3].description);
/* test the medium case, private exponent, prime1, prime2 */ /* test the medium case, private exponent, prime1, prime2 */
resetTemplate(tstTemplate, tstHeaderCount, RSA_ATTRIBUTES); resetTemplate(tstTemplate, tstHeaderCount, RSA_ATTRIBUTES);
cka_id[1] = 2;
copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate, copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate,
tstHeaderCount, CKA_PRIVATE_EXPONENT); tstHeaderCount, CKA_PRIVATE_EXPONENT);
@ -329,7 +377,7 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
tstTemplate[tstHeaderCount + 2].type = CKA_PRIME_1; tstTemplate[tstHeaderCount + 2].type = CKA_PRIME_1;
tstTemplate[tstHeaderCount + 1].type = CKA_PRIME_2; tstTemplate[tstHeaderCount + 1].type = CKA_PRIME_2;
tstPrivKey = PK11_CreateGenericObject(slot, tstTemplate, tstPrivKey = PK11_CreateManagedGenericObject(slot, tstTemplate,
tstHeaderCount + tstHeaderCount +
3, 3,
PR_FALSE); PR_FALSE);
@ -348,6 +396,7 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
printf("%s\n", test_array[4].description); printf("%s\n", test_array[4].description);
/* test the advanced case, public exponent, private exponent, prime2 */ /* test the advanced case, public exponent, private exponent, prime2 */
resetTemplate(tstTemplate, tstHeaderCount, RSA_ATTRIBUTES); resetTemplate(tstTemplate, tstHeaderCount, RSA_ATTRIBUTES);
cka_id[1] = 3;
copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate, copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate,
tstHeaderCount, CKA_PRIVATE_EXPONENT); tstHeaderCount, CKA_PRIVATE_EXPONENT);
copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate, copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate,
@ -355,7 +404,7 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate, copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate,
tstHeaderCount + 2, CKA_PRIME_2); tstHeaderCount + 2, CKA_PRIME_2);
tstPrivKey = PK11_CreateGenericObject(slot, tstTemplate, tstPrivKey = PK11_CreateManagedGenericObject(slot, tstTemplate,
tstHeaderCount + tstHeaderCount +
3, 3,
PR_FALSE); PR_FALSE);
@ -373,11 +422,12 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
if (tstPrivKey) if (tstPrivKey)
PK11_DestroyGenericObject(tstPrivKey); PK11_DestroyGenericObject(tstPrivKey);
} }
if (mask & 16) { if (mask & 0x10) {
printf("%s\n", test_array[5].description); printf("%s\n", test_array[5].description);
/* test the advanced case2, public exponent, private exponent, modulus /* test the advanced case2, public exponent, private exponent, modulus
*/ */
resetTemplate(tstTemplate, tstHeaderCount, RSA_ATTRIBUTES); resetTemplate(tstTemplate, tstHeaderCount, RSA_ATTRIBUTES);
cka_id[1] = LEAK_ID;
copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate, copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate,
tstHeaderCount, CKA_PRIVATE_EXPONENT); tstHeaderCount, CKA_PRIVATE_EXPONENT);
@ -386,6 +436,7 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate, copyAttribute(PK11_TypePrivKey, rsaPrivKey, tstTemplate,
tstHeaderCount + 2, CKA_MODULUS); tstHeaderCount + 2, CKA_MODULUS);
/* purposefully use the old version. This will create a leak */
tstPrivKey = PK11_CreateGenericObject(slot, tstTemplate, tstPrivKey = PK11_CreateGenericObject(slot, tstTemplate,
tstHeaderCount + tstHeaderCount +
3, 3,
@ -398,9 +449,59 @@ doRSAPopulateTest(unsigned int keySize, unsigned long exponent,
fprintf(stderr, "RSA Populate key mismatch: pubExp privExp mod\n"); fprintf(stderr, "RSA Populate key mismatch: pubExp privExp mod\n");
failed = 1; failed = 1;
} }
expect_leak = 1;
if (tstPrivKey) if (tstPrivKey)
PK11_DestroyGenericObject(tstPrivKey); PK11_DestroyGenericObject(tstPrivKey);
} }
resetTemplate(tstTemplate, tstHeaderCount, RSA_ATTRIBUTES);
SECKEY_DestroyPrivateKey(rsaPrivKey);
SECKEY_DestroyPublicKey(rsaPubKey);
/* make sure we didn't leak */
leak_found = 0;
tstPrivKey = PK11_FindGenericObjects(slot, CKO_PRIVATE_KEY);
if (tstPrivKey) {
SECStatus rv;
PK11GenericObject *thisKey;
int i;
fprintf(stderr, "Leaking keys...\n");
for (i = 0, thisKey = tstPrivKey; thisKey; i++,
thisKey = PK11_GetNextGenericObject(thisKey)) {
SECItem id = { 0, NULL, 0 };
rv = PK11_ReadRawAttribute(PK11_TypeGeneric, thisKey,
CKA_ID, &id);
if (rv != SECSuccess) {
fprintf(stderr, "Key %d: couldn't read CKA_ID: %s\n",
i, PORT_ErrorToString(PORT_GetError()));
continue;
}
fprintf(stderr, "id = { ");
dumpItem(stderr, &id);
fprintf(stderr, "};");
if (id.data[1] == LEAK_ID) {
fprintf(stderr, " ---> leak expected\n");
if (id.data[0] == round)
leak_found = 1;
} else {
if (id.len != sizeof(cka_id)) {
fprintf(stderr,
" ---> ERROR unexpected leak in generated key\n");
} else {
fprintf(stderr,
" ---> ERROR unexpected leak in constructed key\n");
}
failed = 1;
}
SECITEM_FreeItem(&id, PR_FALSE);
}
PK11_DestroyGenericObjects(tstPrivKey);
}
if (expect_leak && !leak_found) {
fprintf(stderr, "ERROR expected leak not found\n");
failed = 1;
}
PK11_FreeSlot(slot); PK11_FreeSlot(slot);
return failed ? -1 : 0; return failed ? -1 : 0;
@ -517,7 +618,7 @@ main(int argc, char **argv)
exp_exp_prime_fail_count = 0; exp_exp_prime_fail_count = 0;
for (i = 0; i < repeat; i++) { for (i = 0; i < repeat; i++) {
printf("Running RSA Populate test run %d\n", i); printf("Running RSA Populate test run %d\n", i);
ret = doRSAPopulateTest(keySize, exponent, mask, NULL); ret = doRSAPopulateTest(keySize, exponent, mask, i, NULL);
if (ret != 0) { if (ret != 0) {
i++; i++;
break; break;
@ -531,5 +632,9 @@ main(int argc, char **argv)
exp_exp_prime_fail_count, i, exp_exp_prime_fail_count, i,
(((double)exp_exp_prime_fail_count) * 100.0) / (double)i); (((double)exp_exp_prime_fail_count) * 100.0) / (double)i);
} }
if (NSS_Shutdown() != SECSuccess) {
fprintf(stderr, "Shutdown failed\n");
ret = -1;
}
return ret; return ret;
} }

View file

@ -0,0 +1,25 @@
# 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': 'rsapoptst',
'type': 'executable',
'sources': [
'rsapoptst.c'
],
'dependencies': [
'<(DEPTH)/exports.gyp:dbm_exports',
'<(DEPTH)/exports.gyp:nss_exports',
]
}
],
'variables': {
'module': 'nss',
}
}

View file

@ -38,6 +38,7 @@
#include "nss.h" #include "nss.h"
#include "ssl.h" #include "ssl.h"
#include "sslproto.h" #include "sslproto.h"
#include "sslexp.h"
#include "cert.h" #include "cert.h"
#include "certt.h" #include "certt.h"
#include "ocsp.h" #include "ocsp.h"
@ -165,9 +166,7 @@ PrintUsageHeader(const char *progName)
" [-V [min-version]:[max-version]] [-a sni_name]\n" " [-V [min-version]:[max-version]] [-a sni_name]\n"
" [ T <good|revoked|unknown|badsig|corrupted|none|ocsp>] [-A ca]\n" " [ T <good|revoked|unknown|badsig|corrupted|none|ocsp>] [-A ca]\n"
" [-C SSLCacheEntries] [-S dsa_nickname] -Q [-I groups]" " [-C SSLCacheEntries] [-S dsa_nickname] -Q [-I groups]"
#ifndef NSS_DISABLE_ECC
" [-e ec_nickname]" " [-e ec_nickname]"
#endif /* NSS_DISABLE_ECC */
"\n" "\n"
" -U [0|1] -H [0|1|2] -W [0|1]\n" " -U [0|1] -H [0|1|2] -W [0|1]\n"
"\n", "\n",
@ -1955,6 +1954,10 @@ server_main(
if (enabledVersions.max < SSL_LIBRARY_VERSION_TLS_1_3) { if (enabledVersions.max < SSL_LIBRARY_VERSION_TLS_1_3) {
errExit("You tried enabling 0RTT without enabling TLS 1.3!"); errExit("You tried enabling 0RTT without enabling TLS 1.3!");
} }
rv = SSL_SetupAntiReplay(10 * PR_USEC_PER_SEC, 7, 14);
if (rv != SECSuccess) {
errExit("error configuring anti-replay ");
}
rv = SSL_OptionSet(model_sock, SSL_ENABLE_0RTT_DATA, PR_TRUE); rv = SSL_OptionSet(model_sock, SSL_ENABLE_0RTT_DATA, PR_TRUE);
if (rv != SECSuccess) { if (rv != SECSuccess) {
errExit("error enabling 0RTT "); errExit("error enabling 0RTT ");
@ -2343,7 +2346,6 @@ main(int argc, char **argv)
dir = optstate->value; dir = optstate->value;
break; break;
#ifndef NSS_DISABLE_ECC
case 'e': case 'e':
if (certNicknameIndex >= MAX_CERT_NICKNAME_ARRAY_INDEX) { if (certNicknameIndex >= MAX_CERT_NICKNAME_ARRAY_INDEX) {
Usage(progName); Usage(progName);
@ -2351,7 +2353,6 @@ main(int argc, char **argv)
} }
certNicknameArray[certNicknameIndex++] = PORT_Strdup(optstate->value); certNicknameArray[certNicknameIndex++] = PORT_Strdup(optstate->value);
break; break;
#endif /* NSS_DISABLE_ECC */
case 'f': case 'f':
pwdata.source = PW_FROMFILE; pwdata.source = PW_FROMFILE;
@ -2553,6 +2554,14 @@ main(int argc, char **argv)
tmp = PR_GetEnvSecure("TMPDIR"); tmp = PR_GetEnvSecure("TMPDIR");
if (!tmp) if (!tmp)
tmp = PR_GetEnvSecure("TEMP"); tmp = PR_GetEnvSecure("TEMP");
/* Call the NSS initialization routines */
rv = NSS_Initialize(dir, certPrefix, certPrefix, SECMOD_DB, NSS_INIT_READONLY);
if (rv != SECSuccess) {
fputs("NSS_Init failed.\n", stderr);
exit(8);
}
if (envString) { if (envString) {
/* we're one of the children in a multi-process server. */ /* we're one of the children in a multi-process server. */
listen_sock = PR_GetInheritedFD(inheritableSockName); listen_sock = PR_GetInheritedFD(inheritableSockName);
@ -2607,13 +2616,6 @@ main(int argc, char **argv)
/* set our password function */ /* set our password function */
PK11_SetPasswordFunc(SECU_GetModulePassword); PK11_SetPasswordFunc(SECU_GetModulePassword);
/* Call the NSS initialization routines */
rv = NSS_Initialize(dir, certPrefix, certPrefix, SECMOD_DB, NSS_INIT_READONLY);
if (rv != SECSuccess) {
fputs("NSS_Init failed.\n", stderr);
exit(8);
}
/* all SSL3 cipher suites are enabled by default. */ /* all SSL3 cipher suites are enabled by default. */
if (cipherString) { if (cipherString) {
char *cstringSaved = cipherString; char *cstringSaved = cipherString;
@ -2681,9 +2683,7 @@ main(int argc, char **argv)
certNicknameArray[i]); certNicknameArray[i]);
exit(11); exit(11);
} }
#ifdef NSS_DISABLE_ECC
if (privKey[i]->keyType != ecKey) if (privKey[i]->keyType != ecKey)
#endif
setupCertStatus(certStatusArena, ocspStaplingMode, cert[i], i, &pwdata); setupCertStatus(certStatusArena, ocspStaplingMode, cert[i], i, &pwdata);
} }

View file

@ -1115,8 +1115,7 @@ extract_js(char *filename)
textStart = 0; textStart = 0;
startLine = 0; startLine = 0;
while (linenum = FB_GetLineNum(fb), (curchar = FB_GetChar(fb)) != while (linenum = FB_GetLineNum(fb), (curchar = FB_GetChar(fb)) != EOF) {
EOF) {
switch (state) { switch (state) {
case TEXT_HTML_STATE: case TEXT_HTML_STATE:
if (curchar == '<') { if (curchar == '<') {

View file

@ -1033,9 +1033,7 @@ main(int argc, char *argv[])
if (errorCount > 0 || warningCount > 0) { if (errorCount > 0 || warningCount > 0) {
PR_fprintf(outputFD, "%d error%s, %d warning%s.\n", PR_fprintf(outputFD, "%d error%s, %d warning%s.\n",
errorCount, errorCount,
errorCount == 1 ? "" : "s", warningCount, warningCount == 1 errorCount == 1 ? "" : "s", warningCount, warningCount == 1 ? "" : "s");
? ""
: "s");
} else { } else {
PR_fprintf(outputFD, "Directory %s signed successfully.\n", PR_fprintf(outputFD, "Directory %s signed successfully.\n",
jartree); jartree);

View file

@ -1572,10 +1572,7 @@ main(int argc, char **argv)
{ {
unsigned int j; unsigned int j;
for (j = 0; j < input.len; j++) for (j = 0; j < input.len; j++)
fprintf(stderr, "%2x%c", input.data[j], (j > 0 && fprintf(stderr, "%2x%c", input.data[j], (j > 0 && j % 35 == 0) ? '\n' : ' ');
j % 35 == 0)
? '\n'
: ' ');
} }
} }
if (input.len > 0) { /* skip if certs-only (or other zero content) */ if (input.len > 0) { /* skip if certs-only (or other zero content) */

View file

@ -1637,8 +1637,7 @@ print_ssl3_handshake(unsigned char *recordBuf,
PR_snprintf(certFileName, sizeof certFileName, "cert.%03d", PR_snprintf(certFileName, sizeof certFileName, "cert.%03d",
++certFileNumber); ++certFileNumber);
cfd = cfd =
PR_Open(certFileName, PR_WRONLY | PR_Open(certFileName, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
PR_CREATE_FILE | PR_TRUNCATE,
0664); 0664);
if (!cfd) { if (!cfd) {
PR_fprintf(PR_STDOUT, PR_fprintf(PR_STDOUT,
@ -1722,8 +1721,7 @@ print_ssl3_handshake(unsigned char *recordBuf,
0 && 0 &&
sslhexparse) { sslhexparse) {
PR_fprintf(PR_STDOUT, " = {\n"); PR_fprintf(PR_STDOUT, " = {\n");
print_hex(dnLen, hsdata + print_hex(dnLen, hsdata + pos);
pos);
PR_fprintf(PR_STDOUT, " }\n"); PR_fprintf(PR_STDOUT, " }\n");
} else { } else {
PR_fprintf(PR_STDOUT, "\n"); PR_fprintf(PR_STDOUT, "\n");
@ -1796,8 +1794,7 @@ print_ssl3_handshake(unsigned char *recordBuf,
PR_snprintf(ocspFileName, sizeof ocspFileName, "ocsp.%03d", PR_snprintf(ocspFileName, sizeof ocspFileName, "ocsp.%03d",
++ocspFileNumber); ++ocspFileNumber);
ofd = PR_Open(ocspFileName, PR_WRONLY | ofd = PR_Open(ocspFileName, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
PR_CREATE_FILE | PR_TRUNCATE,
0664); 0664);
if (!ofd) { if (!ofd) {
PR_fprintf(PR_STDOUT, PR_fprintf(PR_STDOUT,
@ -2167,8 +2164,7 @@ print_ssl(DataBufferList *s, int length, unsigned char *buffer)
break; break;
case 22: /* handshake */ case 22: /* handshake */
print_ssl3_handshake(recordBuf, recordLen - print_ssl3_handshake(recordBuf, recordLen - s->hMACsize,
s->hMACsize,
&sr, s); &sr, s);
break; break;

View file

@ -886,8 +886,10 @@ PRBool
LoggedIn(CERTCertificate *cert, SECKEYPrivateKey *key) LoggedIn(CERTCertificate *cert, SECKEYPrivateKey *key)
{ {
if ((cert->slot) && (key->pkcs11Slot) && if ((cert->slot) && (key->pkcs11Slot) &&
(PR_TRUE == PK11_IsLoggedIn(cert->slot, NULL)) && (!PK11_NeedLogin(cert->slot) ||
(PR_TRUE == PK11_IsLoggedIn(key->pkcs11Slot, NULL))) { PR_TRUE == PK11_IsLoggedIn(cert->slot, NULL)) &&
(!PK11_NeedLogin(key->pkcs11Slot) ||
PR_TRUE == PK11_IsLoggedIn(key->pkcs11Slot, NULL))) {
return PR_TRUE; return PR_TRUE;
} }

View file

@ -31,6 +31,7 @@
#include "ocsp.h" #include "ocsp.h"
#include "ssl.h" #include "ssl.h"
#include "sslproto.h" #include "sslproto.h"
#include "sslexp.h"
#include "pk11func.h" #include "pk11func.h"
#include "secmod.h" #include "secmod.h"
#include "plgetopt.h" #include "plgetopt.h"
@ -95,6 +96,7 @@ PRBool verbose;
int dumpServerChain = 0; int dumpServerChain = 0;
int renegotiationsToDo = 0; int renegotiationsToDo = 0;
int renegotiationsDone = 0; int renegotiationsDone = 0;
PRBool initializedServerSessionCache = PR_FALSE;
static char *progName; static char *progName;
@ -178,7 +180,7 @@ PrintUsageHeader(const char *progName)
"[-n nickname] [-Bafosvx] [-c ciphers] [-Y] [-Z]\n" "[-n nickname] [-Bafosvx] [-c ciphers] [-Y] [-Z]\n"
"[-V [min-version]:[max-version]] [-K] [-T] [-U]\n" "[-V [min-version]:[max-version]] [-K] [-T] [-U]\n"
"[-r N] [-w passwd] [-W pwfile] [-q [-t seconds]] [-I groups]\n" "[-r N] [-w passwd] [-W pwfile] [-q [-t seconds]] [-I groups]\n"
"[-A requestfile] [-L totalconnections]\n" "[-A requestfile] [-L totalconnections] [-P {client,server}] [-Q]\n"
"\n", "\n",
progName); progName);
} }
@ -202,7 +204,7 @@ PrintParameterUsage(void)
fprintf(stderr, "%-20s Print certificate chain information\n", "-C"); fprintf(stderr, "%-20s Print certificate chain information\n", "-C");
fprintf(stderr, "%-20s (use -C twice to print more certificate details)\n", ""); fprintf(stderr, "%-20s (use -C twice to print more certificate details)\n", "");
fprintf(stderr, "%-20s (use -C three times to include PEM format certificate dumps)\n", ""); fprintf(stderr, "%-20s (use -C three times to include PEM format certificate dumps)\n", "");
fprintf(stderr, "%-20s Nickname of key and cert for client auth\n", fprintf(stderr, "%-20s Nickname of key and cert\n",
"-n nickname"); "-n nickname");
fprintf(stderr, fprintf(stderr,
"%-20s Restricts the set of enabled SSL/TLS protocols versions.\n" "%-20s Restricts the set of enabled SSL/TLS protocols versions.\n"
@ -251,6 +253,9 @@ PrintParameterUsage(void)
"%-20s The following values are valid:\n" "%-20s The following values are valid:\n"
"%-20s P256, P384, P521, x25519, FF2048, FF3072, FF4096, FF6144, FF8192\n", "%-20s P256, P384, P521, x25519, FF2048, FF3072, FF4096, FF6144, FF8192\n",
"-I", "", ""); "-I", "", "");
fprintf(stderr, "%-20s Enable alternative TLS 1.3 handshake\n", "-X alt-server-hello");
fprintf(stderr, "%-20s Use DTLS\n", "-P {client, server}");
fprintf(stderr, "%-20s Exit after handshake\n", "-Q");
} }
static void static void
@ -914,6 +919,12 @@ char *requestString = NULL;
PRInt32 requestStringLen = 0; PRInt32 requestStringLen = 0;
PRBool requestSent = PR_FALSE; PRBool requestSent = PR_FALSE;
PRBool enableZeroRtt = PR_FALSE; PRBool enableZeroRtt = PR_FALSE;
PRBool enableAltServerHello = PR_FALSE;
PRBool useDTLS = PR_FALSE;
PRBool actAsServer = PR_FALSE;
PRBool stopAfterHandshake = PR_FALSE;
PRBool requestToExit = PR_FALSE;
char *versionString = NULL;
static int static int
writeBytesToServer(PRFileDesc *s, const char *buf, int nb) writeBytesToServer(PRFileDesc *s, const char *buf, int nb)
@ -996,12 +1007,129 @@ handshakeCallback(PRFileDesc *fd, void *client_data)
writeBytesToServer(fd, requestString, requestStringLen); writeBytesToServer(fd, requestString, requestStringLen);
} }
} }
if (stopAfterHandshake) {
requestToExit = PR_TRUE;
}
} }
#define REQUEST_WAITING (requestString && !requestSent) #define REQUEST_WAITING (requestString && !requestSent)
static SECStatus
installServerCertificate(PRFileDesc *s, char *nickname)
{
CERTCertificate *cert;
SECKEYPrivateKey *privKey = NULL;
if (!nickname) {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
return SECFailure;
}
cert = PK11_FindCertFromNickname(nickname, &pwdata);
if (cert == NULL) {
return SECFailure;
}
privKey = PK11_FindKeyByAnyCert(cert, &pwdata);
if (privKey == NULL) {
return SECFailure;
}
if (SSL_ConfigServerCert(s, cert, privKey, NULL, 0) != SECSuccess) {
return SECFailure;
}
SECKEY_DestroyPrivateKey(privKey);
CERT_DestroyCertificate(cert);
return SECSuccess;
}
static SECStatus
bindToClient(PRFileDesc *s)
{
PRStatus status;
status = PR_Bind(s, &addr);
if (status != PR_SUCCESS) {
return SECFailure;
}
for (;;) {
/* Bind the remote address on first packet. This must happen
* before we SSL-ize the socket because we need to get the
* peer's address before SSLizing. Recvfrom gives us that
* while not consuming any data. */
unsigned char tmp;
PRNetAddr remote;
int nb;
nb = PR_RecvFrom(s, &tmp, 1, PR_MSG_PEEK,
&remote, PR_INTERVAL_NO_TIMEOUT);
if (nb != 1)
continue;
status = PR_Connect(s, &remote, PR_INTERVAL_NO_TIMEOUT);
if (status != PR_SUCCESS) {
SECU_PrintError(progName, "server bind to remote end failed");
return SECFailure;
}
return SECSuccess;
}
/* Unreachable. */
}
static SECStatus
connectToServer(PRFileDesc *s, PRPollDesc *pollset)
{
PRStatus status;
PRInt32 filesReady;
status = PR_Connect(s, &addr, PR_INTERVAL_NO_TIMEOUT);
if (status != PR_SUCCESS) {
if (PR_GetError() == PR_IN_PROGRESS_ERROR) {
if (verbose)
SECU_PrintError(progName, "connect");
milliPause(50 * multiplier);
pollset[SSOCK_FD].in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT;
pollset[SSOCK_FD].out_flags = 0;
pollset[SSOCK_FD].fd = s;
while (1) {
FPRINTF(stderr,
"%s: about to call PR_Poll for connect completion!\n",
progName);
filesReady = PR_Poll(pollset, 1, PR_INTERVAL_NO_TIMEOUT);
if (filesReady < 0) {
SECU_PrintError(progName, "unable to connect (poll)");
return SECFailure;
}
FPRINTF(stderr,
"%s: PR_Poll returned 0x%02x for socket out_flags.\n",
progName, pollset[SSOCK_FD].out_flags);
if (filesReady == 0) { /* shouldn't happen! */
SECU_PrintError(progName, "%s: PR_Poll returned zero!\n");
return SECFailure;
}
status = PR_GetConnectStatus(pollset);
if (status == PR_SUCCESS) {
break;
}
if (PR_GetError() != PR_IN_PROGRESS_ERROR) {
SECU_PrintError(progName, "unable to connect (poll)");
return SECFailure;
}
SECU_PrintError(progName, "poll");
milliPause(50 * multiplier);
}
} else {
SECU_PrintError(progName, "unable to connect");
return SECFailure;
}
}
return SECSuccess;
}
static int static int
run_client(void) run(void)
{ {
int headerSeparatorPtrnId = 0; int headerSeparatorPtrnId = 0;
int error = 0; int error = 0;
@ -1017,13 +1145,23 @@ run_client(void)
requestSent = PR_FALSE; requestSent = PR_FALSE;
/* Create socket */ /* Create socket */
if (useDTLS) {
s = PR_OpenUDPSocket(addr.raw.family);
} else {
s = PR_OpenTCPSocket(addr.raw.family); s = PR_OpenTCPSocket(addr.raw.family);
}
if (s == NULL) { if (s == NULL) {
SECU_PrintError(progName, "error creating socket"); SECU_PrintError(progName, "error creating socket");
error = 1; error = 1;
goto done; goto done;
} }
if (actAsServer) {
if (bindToClient(s) != SECSuccess) {
return 1;
}
}
opt.option = PR_SockOpt_Nonblocking; opt.option = PR_SockOpt_Nonblocking;
opt.value.non_blocking = PR_TRUE; /* default */ opt.value.non_blocking = PR_TRUE; /* default */
if (serverCertAuth.testFreshStatusFromSideChannel) { if (serverCertAuth.testFreshStatusFromSideChannel) {
@ -1036,13 +1174,16 @@ run_client(void)
goto done; goto done;
} }
if (useDTLS) {
s = DTLS_ImportFD(NULL, s);
} else {
s = SSL_ImportFD(NULL, s); s = SSL_ImportFD(NULL, s);
}
if (s == NULL) { if (s == NULL) {
SECU_PrintError(progName, "error importing socket"); SECU_PrintError(progName, "error importing socket");
error = 1; error = 1;
goto done; goto done;
} }
SSL_SetPKCS11PinArg(s, &pwdata); SSL_SetPKCS11PinArg(s, &pwdata);
rv = SSL_OptionSet(s, SSL_SECURITY, 1); rv = SSL_OptionSet(s, SSL_SECURITY, 1);
@ -1052,7 +1193,7 @@ run_client(void)
goto done; goto done;
} }
rv = SSL_OptionSet(s, SSL_HANDSHAKE_AS_CLIENT, 1); rv = SSL_OptionSet(s, actAsServer ? SSL_HANDSHAKE_AS_SERVER : SSL_HANDSHAKE_AS_CLIENT, 1);
if (rv != SECSuccess) { if (rv != SECSuccess) {
SECU_PrintError(progName, "error enabling client handshake"); SECU_PrintError(progName, "error enabling client handshake");
error = 1; error = 1;
@ -1178,6 +1319,16 @@ run_client(void)
} }
} }
/* Alternate ServerHello content type (TLS 1.3 only) */
if (enableAltServerHello) {
rv = SSL_UseAltServerHelloType(s, PR_TRUE);
if (rv != SECSuccess) {
SECU_PrintError(progName, "error enabling alternate ServerHello type");
error = 1;
goto done;
}
}
/* require the use of fixed finite-field DH groups */ /* require the use of fixed finite-field DH groups */
if (requireDHNamedGroups) { if (requireDHNamedGroups) {
rv = SSL_OptionSet(s, SSL_REQUIRE_DH_NAMED_GROUPS, PR_TRUE); rv = SSL_OptionSet(s, SSL_REQUIRE_DH_NAMED_GROUPS, PR_TRUE);
@ -1212,7 +1363,21 @@ run_client(void)
if (override) { if (override) {
SSL_BadCertHook(s, ownBadCertHandler, NULL); SSL_BadCertHook(s, ownBadCertHandler, NULL);
} }
if (actAsServer) {
rv = installServerCertificate(s, nickname);
if (rv != SECSuccess) {
SECU_PrintError(progName, "error installing server cert");
return 1;
}
rv = SSL_ConfigServerSessionIDCache(1024, 0, 0, ".");
if (rv != SECSuccess) {
SECU_PrintError(progName, "error configuring session cache");
return 1;
}
initializedServerSessionCache = PR_TRUE;
} else {
SSL_GetClientAuthDataHook(s, own_GetClientAuthData, (void *)nickname); SSL_GetClientAuthDataHook(s, own_GetClientAuthData, (void *)nickname);
}
SSL_HandshakeCallback(s, handshakeCallback, hs2SniHostName); SSL_HandshakeCallback(s, handshakeCallback, hs2SniHostName);
if (hs1SniHostName) { if (hs1SniHostName) {
SSL_SetURL(s, hs1SniHostName); SSL_SetURL(s, hs1SniHostName);
@ -1220,56 +1385,27 @@ run_client(void)
SSL_SetURL(s, host); SSL_SetURL(s, host);
} }
/* Try to connect to the server */ if (actAsServer) {
status = PR_Connect(s, &addr, PR_INTERVAL_NO_TIMEOUT); rv = SSL_ResetHandshake(s, PR_TRUE /* server */);
if (status != PR_SUCCESS) { if (rv != SECSuccess) {
if (PR_GetError() == PR_IN_PROGRESS_ERROR) { return 1;
if (verbose)
SECU_PrintError(progName, "connect");
milliPause(50 * multiplier);
pollset[SSOCK_FD].in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT;
pollset[SSOCK_FD].out_flags = 0;
pollset[SSOCK_FD].fd = s;
while (1) {
FPRINTF(stderr,
"%s: about to call PR_Poll for connect completion!\n",
progName);
filesReady = PR_Poll(pollset, 1, PR_INTERVAL_NO_TIMEOUT);
if (filesReady < 0) {
SECU_PrintError(progName, "unable to connect (poll)");
error = 1;
goto done;
}
FPRINTF(stderr,
"%s: PR_Poll returned 0x%02x for socket out_flags.\n",
progName, pollset[SSOCK_FD].out_flags);
if (filesReady == 0) { /* shouldn't happen! */
FPRINTF(stderr, "%s: PR_Poll returned zero!\n", progName);
error = 1;
goto done;
}
status = PR_GetConnectStatus(pollset);
if (status == PR_SUCCESS) {
break;
}
if (PR_GetError() != PR_IN_PROGRESS_ERROR) {
SECU_PrintError(progName, "unable to connect (poll)");
error = 1;
goto done;
}
SECU_PrintError(progName, "poll");
milliPause(50 * multiplier);
} }
} else { } else {
SECU_PrintError(progName, "unable to connect"); /* Try to connect to the server */
rv = connectToServer(s, pollset);
if (rv != SECSuccess) {
;
error = 1; error = 1;
goto done; goto done;
} }
} }
pollset[SSOCK_FD].fd = s; pollset[SSOCK_FD].fd = s;
pollset[SSOCK_FD].in_flags = PR_POLL_EXCEPT | pollset[SSOCK_FD].in_flags = PR_POLL_EXCEPT;
(clientSpeaksFirst ? 0 : PR_POLL_READ); if (!actAsServer)
pollset[SSOCK_FD].in_flags |= (clientSpeaksFirst ? 0 : PR_POLL_READ);
else
pollset[SSOCK_FD].in_flags |= PR_POLL_READ;
pollset[STDIN_FD].fd = PR_GetSpecialFD(PR_StandardInput); pollset[STDIN_FD].fd = PR_GetSpecialFD(PR_StandardInput);
if (!REQUEST_WAITING) { if (!REQUEST_WAITING) {
pollset[STDIN_FD].in_flags = PR_POLL_READ; pollset[STDIN_FD].in_flags = PR_POLL_READ;
@ -1319,9 +1455,11 @@ run_client(void)
** Select on stdin and on the socket. Write data from stdin to ** Select on stdin and on the socket. Write data from stdin to
** socket, read data from socket and write to stdout. ** socket, read data from socket and write to stdout.
*/ */
requestToExit = PR_FALSE;
FPRINTF(stderr, "%s: ready...\n", progName); FPRINTF(stderr, "%s: ready...\n", progName);
while ((pollset[SSOCK_FD].in_flags | pollset[STDIN_FD].in_flags) || while (!requestToExit &&
REQUEST_WAITING) { ((pollset[SSOCK_FD].in_flags | pollset[STDIN_FD].in_flags) ||
REQUEST_WAITING)) {
char buf[4000]; /* buffer for stdin */ char buf[4000]; /* buffer for stdin */
int nb; /* num bytes read from stdin. */ int nb; /* num bytes read from stdin. */
@ -1507,12 +1645,10 @@ main(int argc, char **argv)
} }
} }
SSL_VersionRangeGetSupported(ssl_variant_stream, &enabledVersions);
/* XXX: 'B' was used in the past but removed in 3.28, /* XXX: 'B' was used in the past but removed in 3.28,
* please leave some time before resuing it. */ * please leave some time before resuing it. */
optstate = PL_CreateOptState(argc, argv, optstate = PL_CreateOptState(argc, argv,
"46A:CDFGHI:KL:M:OR:STUV:W:YZa:bc:d:fgh:m:n:op:qr:st:uvw:z"); "46A:CDFGHI:KL:M:OP:QR:STUV:W:X:YZa:bc:d:fgh:m:n:op:qr:st:uvw:z");
while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) { while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
switch (optstate->option) { switch (optstate->option) {
case '?': case '?':
@ -1593,6 +1729,21 @@ main(int argc, char **argv)
}; };
break; break;
case 'P':
useDTLS = PR_TRUE;
if (!strcmp(optstate->value, "server")) {
actAsServer = 1;
} else {
if (strcmp(optstate->value, "client")) {
Usage(progName);
}
}
break;
case 'Q':
stopAfterHandshake = PR_TRUE;
break;
case 'R': case 'R':
rootModule = PORT_Strdup(optstate->value); rootModule = PORT_Strdup(optstate->value);
break; break;
@ -1610,14 +1761,16 @@ main(int argc, char **argv)
break; break;
case 'V': case 'V':
if (SECU_ParseSSLVersionRangeString(optstate->value, versionString = PORT_Strdup(optstate->value);
enabledVersions, &enabledVersions) != break;
SECSuccess) {
fprintf(stderr, "Bad version specified.\n"); case 'X':
if (!strcmp(optstate->value, "alt-server-hello")) {
enableAltServerHello = PR_TRUE;
} else {
Usage(progName); Usage(progName);
} }
break; break;
case 'Y': case 'Y':
PrintCipherUsage(progName); PrintCipherUsage(progName);
exit(0); exit(0);
@ -1727,9 +1880,20 @@ main(int argc, char **argv)
break; break;
} }
} }
PL_DestroyOptState(optstate); PL_DestroyOptState(optstate);
SSL_VersionRangeGetSupported(useDTLS ? ssl_variant_datagram : ssl_variant_stream, &enabledVersions);
if (versionString) {
if (SECU_ParseSSLVersionRangeString(versionString,
enabledVersions, &enabledVersions) !=
SECSuccess) {
fprintf(stderr, "Bad version specified.\n");
Usage(progName);
}
PORT_Free(versionString);
}
if (optstatus == PL_OPT_BAD) { if (optstatus == PL_OPT_BAD) {
Usage(progName); Usage(progName);
} }
@ -1758,7 +1922,7 @@ main(int argc, char **argv)
PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1); PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
PK11_SetPasswordFunc(SECU_GetModulePassword); PK11_SetPasswordFunc(SECU_GetModulePassword);
memset(&addr, 0, sizeof(addr));
status = PR_StringToNetAddr(host, &addr); status = PR_StringToNetAddr(host, &addr);
if (status == PR_SUCCESS) { if (status == PR_SUCCESS) {
addr.inet.port = PR_htons(portno); addr.inet.port = PR_htons(portno);
@ -1770,6 +1934,7 @@ main(int argc, char **argv)
addrInfo = PR_GetAddrInfoByName(host, PR_AF_UNSPEC, addrInfo = PR_GetAddrInfoByName(host, PR_AF_UNSPEC,
PR_AI_ADDRCONFIG | PR_AI_NOCANONNAME); PR_AI_ADDRCONFIG | PR_AI_NOCANONNAME);
if (!addrInfo) { if (!addrInfo) {
fprintf(stderr, "HOSTNAME=%s\n", host);
SECU_PrintError(progName, "error looking up host"); SECU_PrintError(progName, "error looking up host");
error = 1; error = 1;
goto done; goto done;
@ -1884,7 +2049,7 @@ main(int argc, char **argv)
} }
while (numConnections--) { while (numConnections--) {
error = run_client(); error = run();
if (error) { if (error) {
goto done; goto done;
} }
@ -1915,6 +2080,12 @@ done:
} }
if (NSS_IsInitialized()) { if (NSS_IsInitialized()) {
SSL_ClearSessionCache(); SSL_ClearSessionCache();
if (initializedServerSessionCache) {
if (SSL_ShutdownServerSessionIDCache() != SECSuccess) {
error = 1;
}
}
if (NSS_Shutdown() != SECSuccess) { if (NSS_Shutdown() != SECSuccess) {
error = 1; error = 1;
} }

View file

@ -96,7 +96,6 @@
'mozilla_client%': 0, 'mozilla_client%': 0,
'moz_fold_libs%': 0, 'moz_fold_libs%': 0,
'moz_folded_library_name%': '', 'moz_folded_library_name%': '',
'ssl_enable_zlib%': 1,
'sanitizer_flags%': 0, 'sanitizer_flags%': 0,
'test_build%': 0, 'test_build%': 0,
'no_zdefs%': 0, 'no_zdefs%': 0,
@ -109,6 +108,7 @@
'nss_public_dist_dir%': '<(nss_dist_dir)/public', 'nss_public_dist_dir%': '<(nss_dist_dir)/public',
'nss_private_dist_dir%': '<(nss_dist_dir)/private', 'nss_private_dist_dir%': '<(nss_dist_dir)/private',
'only_dev_random%': 1, 'only_dev_random%': 1,
'disable_fips%': 1,
}, },
'target_defaults': { 'target_defaults': {
# Settings specific to targets should go here. # Settings specific to targets should go here.
@ -125,6 +125,12 @@
'<(nss_dist_dir)/private/<(module)', '<(nss_dist_dir)/private/<(module)',
], ],
'conditions': [ 'conditions': [
[ 'disable_fips==1', {
'defines': [
'NSS_FIPS_DISABLED',
'NSS_NO_INIT_SUPPORT',
],
}],
[ 'OS!="android" and OS!="mac" and OS!="win"', { [ 'OS!="android" and OS!="mac" and OS!="win"', {
'libraries': [ 'libraries': [
'-lpthread', '-lpthread',
@ -167,7 +173,7 @@
}, },
}, },
}], }],
[ 'target_arch=="arm64" or target_arch=="aarch64"', { [ 'target_arch=="arm64" or target_arch=="aarch64" or target_arch=="sparc64" or target_arch=="ppc64" or target_arch=="ppc64le" or target_arch=="s390x" or target_arch=="mips64"', {
'defines': [ 'defines': [
'NSS_USE_64', 'NSS_USE_64',
], ],
@ -294,7 +300,6 @@
'Common': { 'Common': {
'abstract': 1, 'abstract': 1,
'defines': [ 'defines': [
'NSS_NO_INIT_SUPPORT',
'USE_UTIL_DIRECTLY', 'USE_UTIL_DIRECTLY',
'NO_NSPR_10_SUPPORT', 'NO_NSPR_10_SUPPORT',
'SSL_DISABLE_DEPRECATED_CIPHER_SUITE_NAMES', 'SSL_DISABLE_DEPRECATED_CIPHER_SUITE_NAMES',

View file

@ -146,10 +146,6 @@ endif
# [16.0] Global environ ment defines # [16.0] Global environ ment defines
####################################################################### #######################################################################
ifdef NSS_DISABLE_ECC
DEFINES += -DNSS_DISABLE_ECC
endif
ifdef NSS_ALLOW_UNSUPPORTED_CRITICAL ifdef NSS_ALLOW_UNSUPPORTED_CRITICAL
DEFINES += -DNSS_ALLOW_UNSUPPORTED_CRITICAL DEFINES += -DNSS_ALLOW_UNSUPPORTED_CRITICAL
endif endif
@ -203,8 +199,3 @@ DEFINES += -DNO_NSPR_10_SUPPORT
# Hide old, deprecated, TLS cipher suite names when building NSS # Hide old, deprecated, TLS cipher suite names when building NSS
DEFINES += -DSSL_DISABLE_DEPRECATED_CIPHER_SUITE_NAMES DEFINES += -DSSL_DISABLE_DEPRECATED_CIPHER_SUITE_NAMES
# Mozilla's mozilla/modules/zlib/src/zconf.h adds the MOZ_Z_ prefix to zlib
# exported symbols, which causes problem when NSS is built as part of Mozilla.
# So we add a NSS_SSL_ENABLE_ZLIB variable to allow Mozilla to turn this off.
NSS_SSL_ENABLE_ZLIB = 1

View file

@ -10,4 +10,3 @@
*/ */
#error "Do not include this header file." #error "Do not include this header file."

View file

@ -24,7 +24,7 @@ def main():
# If we aren't clang, make sure we have gcc 4.8 at least # If we aren't clang, make sure we have gcc 4.8 at least
if not cc_is_clang: if not cc_is_clang:
try: try:
v = subprocess.check_output([cc, '-dumpversion'], stderr=sink) v = subprocess.check_output([cc, '-dumpversion'], stderr=sink).decode("utf-8")
v = v.strip(' \r\n').split('.') v = v.strip(' \r\n').split('.')
v = list(map(int, v)) v = list(map(int, v))
if v[0] < 4 or (v[0] == 4 and v[1] < 8): if v[0] < 4 or (v[0] == 4 and v[1] < 8):

View file

@ -0,0 +1,4 @@
---
Language: Cpp
BasedOnStyle: Google
...

View file

@ -0,0 +1,49 @@
#! gmake
#
# 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/.
#######################################################################
# (1) Include initial platform-independent assignments (MANDATORY). #
#######################################################################
include manifest.mn
#######################################################################
# (2) Include "global" configuration information. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/config.mk
#######################################################################
# (3) Include "component" configuration information. (OPTIONAL) #
#######################################################################
ifeq (WINNT,$(OS_ARCH))
OS_CFLAGS += -EHsc
else
CXXFLAGS += -std=c++0x
endif
#######################################################################
# (4) Include "local" platform-dependent assignments (OPTIONAL). #
#######################################################################
include config.mk
#######################################################################
# (5) Execute "global" rules. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/rules.mk
#######################################################################
# (6) Execute "component" rules. (OPTIONAL) #
#######################################################################
#######################################################################
# (7) Execute "local" rules. (OPTIONAL). #
#######################################################################

View file

@ -0,0 +1,11 @@
######################################
## PLEASE READ BEFORE USING CPPUTIL ##
######################################
This is a static library supposed to be mainly used by NSS internally. We use
it for testing, fuzzing, and a few new tools written in C++ that we're
experimenting with.
You might find it handy to use for your own projects but please be aware that
we will make no promises your application won't break in the future. We will
provide no support if you decide to link against it.

View file

@ -0,0 +1,15 @@
#
# 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/.
#
# Override TARGETS variable so that only static libraries
# are specifed as dependencies within rules.mk.
#
TARGETS = $(LIBRARY)
SHARED_LIBRARY =
IMPORT_LIBRARY =
PROGRAM =

View file

@ -0,0 +1,29 @@
# 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',
],
'targets': [
{
'target_name': 'cpputil',
'type': 'static_library',
'sources': [
'databuffer.cc',
'dummy_io.cc',
'dummy_io_fwd.cc',
'tls_parser.cc',
],
'dependencies': [
'<(DEPTH)/exports.gyp:nss_exports',
],
'direct_dependent_settings': {
'include_dirs': [
'<(DEPTH)/cpputil',
],
},
},
],
}

View file

@ -0,0 +1,12 @@
/* 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 cpputil_h__
#define cpputil_h__
static unsigned char* toUcharPtr(const uint8_t* v) {
return const_cast<unsigned char*>(static_cast<const unsigned char*>(v));
}
#endif // cpputil_h__

View file

@ -0,0 +1,127 @@
/* -*- 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 "databuffer.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <iomanip>
#include <iostream>
#if defined(WIN32) || defined(WIN64)
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
namespace nss_test {
void DataBuffer::Assign(const uint8_t* data, size_t len) {
if (data) {
Allocate(len);
memcpy(static_cast<void*>(data_), static_cast<const void*>(data), len);
} else {
assert(len == 0);
data_ = nullptr;
len_ = 0;
}
}
// Write will do a new allocation and expand the size of the buffer if needed.
// Returns the offset of the end of the write.
size_t DataBuffer::Write(size_t index, const uint8_t* val, size_t count) {
assert(val);
if (index + count > len_) {
size_t newlen = index + count;
uint8_t* tmp = new uint8_t[newlen]; // Always > 0.
if (data_) {
memcpy(static_cast<void*>(tmp), static_cast<const void*>(data_), len_);
}
if (index > len_) {
memset(static_cast<void*>(tmp + len_), 0, index - len_);
}
delete[] data_;
data_ = tmp;
len_ = newlen;
}
if (data_) {
memcpy(static_cast<void*>(data_ + index), static_cast<const void*>(val),
count);
}
return index + count;
}
// Write an integer, also performing host-to-network order conversion.
// Returns the offset of the end of the write.
size_t DataBuffer::Write(size_t index, uint32_t val, size_t count) {
assert(count <= sizeof(uint32_t));
uint32_t nvalue = htonl(val);
auto* addr = reinterpret_cast<const uint8_t*>(&nvalue);
return Write(index, addr + sizeof(uint32_t) - count, count);
}
void DataBuffer::Splice(const uint8_t* ins, size_t ins_len, size_t index,
size_t remove) {
assert(ins);
uint8_t* old_value = data_;
size_t old_len = len_;
// The amount of stuff remaining from the tail of the old.
size_t tail_len = old_len - (std::min)(old_len, index + remove);
// The new length: the head of the old, the new, and the tail of the old.
len_ = index + ins_len + tail_len;
data_ = new uint8_t[len_ ? len_ : 1];
// The head of the old.
if (old_value) {
Write(0, old_value, (std::min)(old_len, index));
}
// Maybe a gap.
if (old_value && index > old_len) {
memset(old_value + index, 0, index - old_len);
}
// The new.
Write(index, ins, ins_len);
// The tail of the old.
if (tail_len > 0) {
Write(index + ins_len, old_value + index + remove, tail_len);
}
delete[] old_value;
}
// This can't use the same trick as Write(), since we might be reading from a
// smaller data source.
bool DataBuffer::Read(size_t index, size_t count, uint64_t* val) const {
assert(count <= sizeof(uint64_t));
assert(val);
if ((index > len()) || (count > (len() - index))) {
return false;
}
*val = 0;
for (size_t i = 0; i < count; ++i) {
*val = (*val << 8) | data()[index + i];
}
return true;
}
bool DataBuffer::Read(size_t index, size_t count, uint32_t* val) const {
assert(count <= sizeof(uint32_t));
uint64_t tmp;
if (!Read(index, count, &tmp)) {
return false;
}
*val = tmp & 0xffffffff;
return true;
}
size_t DataBuffer::logging_limit = 32;
/* static */ void DataBuffer::SetLogLimit(size_t limit) {
DataBuffer::logging_limit = limit;
}
} // namespace nss_test

View file

@ -0,0 +1,110 @@
/* -*- 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 databuffer_h__
#define databuffer_h__
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <iostream>
namespace nss_test {
class DataBuffer {
public:
DataBuffer() : data_(nullptr), len_(0) {}
DataBuffer(const uint8_t* data, size_t len) : data_(nullptr), len_(0) {
Assign(data, len);
}
DataBuffer(const DataBuffer& other) : data_(nullptr), len_(0) {
Assign(other);
}
~DataBuffer() { delete[] data_; }
DataBuffer& operator=(const DataBuffer& other) {
if (&other != this) {
Assign(other);
}
return *this;
}
void Allocate(size_t len) {
delete[] data_;
data_ = new uint8_t[len ? len : 1]; // Don't depend on new [0].
len_ = len;
}
void Truncate(size_t len) { len_ = (std::min)(len_, len); }
void Assign(const DataBuffer& other) { Assign(other.data(), other.len()); }
void Assign(const uint8_t* data, size_t len);
// Write will do a new allocation and expand the size of the buffer if needed.
// Returns the offset of the end of the write.
size_t Write(size_t index, const uint8_t* val, size_t count);
size_t Write(size_t index, const DataBuffer& buf) {
return Write(index, buf.data(), buf.len());
}
// Write an integer, also performing host-to-network order conversion.
// Returns the offset of the end of the write.
size_t Write(size_t index, uint32_t val, size_t count);
// Starting at |index|, remove |remove| bytes and replace them with the
// contents of |buf|.
void Splice(const DataBuffer& buf, size_t index, size_t remove = 0) {
Splice(buf.data(), buf.len(), index, remove);
}
void Splice(const uint8_t* ins, size_t ins_len, size_t index,
size_t remove = 0);
void Append(const DataBuffer& buf) { Splice(buf, len_); }
bool Read(size_t index, size_t count, uint64_t* val) const;
bool Read(size_t index, size_t count, uint32_t* val) const;
const uint8_t* data() const { return data_; }
uint8_t* data() { return data_; }
size_t len() const { return len_; }
bool empty() const { return len_ == 0; }
static void SetLogLimit(size_t limit);
friend std::ostream& operator<<(std::ostream& stream, const DataBuffer& buf);
private:
static size_t logging_limit;
uint8_t* data_;
size_t len_;
};
inline std::ostream& operator<<(std::ostream& stream, const DataBuffer& buf) {
stream << "[" << buf.len() << "] ";
for (size_t i = 0; i < buf.len(); ++i) {
if (i >= DataBuffer::logging_limit) {
stream << "...";
break;
}
stream << std::hex << std::setfill('0') << std::setw(2)
<< static_cast<unsigned>(buf.data()[i]);
}
stream << std::dec;
return stream;
}
inline bool operator==(const DataBuffer& a, const DataBuffer& b) {
return (a.empty() && b.empty()) ||
(a.len() == b.len() && 0 == memcmp(a.data(), b.data(), a.len()));
}
inline bool operator!=(const DataBuffer& a, const DataBuffer& b) {
return !(a == b);
}
} // namespace nss_test
#endif

View file

@ -0,0 +1,225 @@
/* 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 <iostream>
#include "prerror.h"
#include "prio.h"
#include "dummy_io.h"
#define UNIMPLEMENTED() \
std::cerr << "Unimplemented: " << __FUNCTION__ << std::endl; \
assert(false);
extern const struct PRIOMethods DummyMethodsForward;
ScopedPRFileDesc DummyIOLayerMethods::CreateFD(PRDescIdentity id,
DummyIOLayerMethods *methods) {
ScopedPRFileDesc fd(PR_CreateIOLayerStub(id, &DummyMethodsForward));
assert(fd);
if (!fd) {
return nullptr;
}
fd->secret = reinterpret_cast<PRFilePrivate *>(methods);
return fd;
}
PRStatus DummyIOLayerMethods::Close(PRFileDesc *f) {
f->secret = nullptr;
f->dtor(f);
return PR_SUCCESS;
}
int32_t DummyIOLayerMethods::Read(PRFileDesc *f, void *buf, int32_t length) {
UNIMPLEMENTED();
return -1;
}
int32_t DummyIOLayerMethods::Write(PRFileDesc *f, const void *buf,
int32_t length) {
UNIMPLEMENTED();
return -1;
}
int32_t DummyIOLayerMethods::Available(PRFileDesc *f) {
UNIMPLEMENTED();
return -1;
}
int64_t DummyIOLayerMethods::Available64(PRFileDesc *f) {
UNIMPLEMENTED();
return -1;
}
PRStatus DummyIOLayerMethods::Sync(PRFileDesc *f) {
UNIMPLEMENTED();
return PR_FAILURE;
}
int32_t DummyIOLayerMethods::Seek(PRFileDesc *f, int32_t offset,
PRSeekWhence how) {
UNIMPLEMENTED();
return -1;
}
int64_t DummyIOLayerMethods::Seek64(PRFileDesc *f, int64_t offset,
PRSeekWhence how) {
UNIMPLEMENTED();
return -1;
}
PRStatus DummyIOLayerMethods::FileInfo(PRFileDesc *f, PRFileInfo *info) {
UNIMPLEMENTED();
return PR_FAILURE;
}
PRStatus DummyIOLayerMethods::FileInfo64(PRFileDesc *f, PRFileInfo64 *info) {
UNIMPLEMENTED();
return PR_FAILURE;
}
int32_t DummyIOLayerMethods::Writev(PRFileDesc *f, const PRIOVec *iov,
int32_t iov_size, PRIntervalTime to) {
UNIMPLEMENTED();
return -1;
}
PRStatus DummyIOLayerMethods::Connect(PRFileDesc *f, const PRNetAddr *addr,
PRIntervalTime to) {
UNIMPLEMENTED();
return PR_FAILURE;
}
PRFileDesc *DummyIOLayerMethods::Accept(PRFileDesc *sd, PRNetAddr *addr,
PRIntervalTime to) {
UNIMPLEMENTED();
return nullptr;
}
PRStatus DummyIOLayerMethods::Bind(PRFileDesc *f, const PRNetAddr *addr) {
UNIMPLEMENTED();
return PR_FAILURE;
}
PRStatus DummyIOLayerMethods::Listen(PRFileDesc *f, int32_t depth) {
UNIMPLEMENTED();
return PR_FAILURE;
}
PRStatus DummyIOLayerMethods::Shutdown(PRFileDesc *f, int32_t how) {
return PR_SUCCESS;
}
int32_t DummyIOLayerMethods::Recv(PRFileDesc *f, void *buf, int32_t buflen,
int32_t flags, PRIntervalTime to) {
UNIMPLEMENTED();
return -1;
}
// Note: this is always nonblocking and assumes a zero timeout.
int32_t DummyIOLayerMethods::Send(PRFileDesc *f, const void *buf,
int32_t amount, int32_t flags,
PRIntervalTime to) {
return Write(f, buf, amount);
}
int32_t DummyIOLayerMethods::Recvfrom(PRFileDesc *f, void *buf, int32_t amount,
int32_t flags, PRNetAddr *addr,
PRIntervalTime to) {
UNIMPLEMENTED();
return -1;
}
int32_t DummyIOLayerMethods::Sendto(PRFileDesc *f, const void *buf,
int32_t amount, int32_t flags,
const PRNetAddr *addr, PRIntervalTime to) {
UNIMPLEMENTED();
return -1;
}
int16_t DummyIOLayerMethods::Poll(PRFileDesc *f, int16_t in_flags,
int16_t *out_flags) {
UNIMPLEMENTED();
return -1;
}
int32_t DummyIOLayerMethods::AcceptRead(PRFileDesc *sd, PRFileDesc **nd,
PRNetAddr **raddr, void *buf,
int32_t amount, PRIntervalTime t) {
UNIMPLEMENTED();
return -1;
}
int32_t DummyIOLayerMethods::TransmitFile(PRFileDesc *sd, PRFileDesc *f,
const void *headers, int32_t hlen,
PRTransmitFileFlags flags,
PRIntervalTime t) {
UNIMPLEMENTED();
return -1;
}
// TODO: Modify to return unique names for each channel
// somehow, as opposed to always the same static address. The current
// implementation messes up the session cache, which is why it's off
// elsewhere
PRStatus DummyIOLayerMethods::Getpeername(PRFileDesc *f, PRNetAddr *addr) {
addr->inet.family = PR_AF_INET;
addr->inet.port = 0;
addr->inet.ip = 0;
return PR_SUCCESS;
}
PRStatus DummyIOLayerMethods::Getsockname(PRFileDesc *f, PRNetAddr *addr) {
UNIMPLEMENTED();
return PR_FAILURE;
}
PRStatus DummyIOLayerMethods::Getsockoption(PRFileDesc *f,
PRSocketOptionData *opt) {
switch (opt->option) {
case PR_SockOpt_Nonblocking:
opt->value.non_blocking = PR_TRUE;
return PR_SUCCESS;
default:
UNIMPLEMENTED();
break;
}
return PR_FAILURE;
}
PRStatus DummyIOLayerMethods::Setsockoption(PRFileDesc *f,
const PRSocketOptionData *opt) {
switch (opt->option) {
case PR_SockOpt_Nonblocking:
return PR_SUCCESS;
case PR_SockOpt_NoDelay:
return PR_SUCCESS;
default:
UNIMPLEMENTED();
break;
}
return PR_FAILURE;
}
int32_t DummyIOLayerMethods::Sendfile(PRFileDesc *out, PRSendFileData *in,
PRTransmitFileFlags flags,
PRIntervalTime to) {
UNIMPLEMENTED();
return -1;
}
PRStatus DummyIOLayerMethods::ConnectContinue(PRFileDesc *f, int16_t flags) {
UNIMPLEMENTED();
return PR_FAILURE;
}
int32_t DummyIOLayerMethods::Reserved(PRFileDesc *f) {
UNIMPLEMENTED();
return -1;
}

View file

@ -0,0 +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/. */
#ifndef dummy_io_h__
#define dummy_io_h__
#include "prerror.h"
#include "prio.h"
#include "scoped_ptrs.h"
class DummyIOLayerMethods {
public:
static ScopedPRFileDesc CreateFD(PRDescIdentity id,
DummyIOLayerMethods *methods);
virtual PRStatus Close(PRFileDesc *f);
virtual int32_t Read(PRFileDesc *f, void *buf, int32_t length);
virtual int32_t Write(PRFileDesc *f, const void *buf, int32_t length);
virtual int32_t Available(PRFileDesc *f);
virtual int64_t Available64(PRFileDesc *f);
virtual PRStatus Sync(PRFileDesc *f);
virtual int32_t Seek(PRFileDesc *f, int32_t offset, PRSeekWhence how);
virtual int64_t Seek64(PRFileDesc *f, int64_t offset, PRSeekWhence how);
virtual PRStatus FileInfo(PRFileDesc *f, PRFileInfo *info);
virtual PRStatus FileInfo64(PRFileDesc *f, PRFileInfo64 *info);
virtual int32_t Writev(PRFileDesc *f, const PRIOVec *iov, int32_t iov_size,
PRIntervalTime to);
virtual PRStatus Connect(PRFileDesc *f, const PRNetAddr *addr,
PRIntervalTime to);
virtual PRFileDesc *Accept(PRFileDesc *sd, PRNetAddr *addr,
PRIntervalTime to);
virtual PRStatus Bind(PRFileDesc *f, const PRNetAddr *addr);
virtual PRStatus Listen(PRFileDesc *f, int32_t depth);
virtual PRStatus Shutdown(PRFileDesc *f, int32_t how);
virtual int32_t Recv(PRFileDesc *f, void *buf, int32_t buflen, int32_t flags,
PRIntervalTime to);
virtual int32_t Send(PRFileDesc *f, const void *buf, int32_t amount,
int32_t flags, PRIntervalTime to);
virtual int32_t Recvfrom(PRFileDesc *f, void *buf, int32_t amount,
int32_t flags, PRNetAddr *addr, PRIntervalTime to);
virtual int32_t Sendto(PRFileDesc *f, const void *buf, int32_t amount,
int32_t flags, const PRNetAddr *addr,
PRIntervalTime to);
virtual int16_t Poll(PRFileDesc *f, int16_t in_flags, int16_t *out_flags);
virtual int32_t AcceptRead(PRFileDesc *sd, PRFileDesc **nd, PRNetAddr **raddr,
void *buf, int32_t amount, PRIntervalTime t);
virtual int32_t TransmitFile(PRFileDesc *sd, PRFileDesc *f,
const void *headers, int32_t hlen,
PRTransmitFileFlags flags, PRIntervalTime t);
virtual PRStatus Getpeername(PRFileDesc *f, PRNetAddr *addr);
virtual PRStatus Getsockname(PRFileDesc *f, PRNetAddr *addr);
virtual PRStatus Getsockoption(PRFileDesc *f, PRSocketOptionData *opt);
virtual PRStatus Setsockoption(PRFileDesc *f, const PRSocketOptionData *opt);
virtual int32_t Sendfile(PRFileDesc *out, PRSendFileData *in,
PRTransmitFileFlags flags, PRIntervalTime to);
virtual PRStatus ConnectContinue(PRFileDesc *f, int16_t flags);
virtual int32_t Reserved(PRFileDesc *f);
};
#endif // dummy_io_h__

View file

@ -0,0 +1,162 @@
/* 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 "prio.h"
#include "dummy_io.h"
static DummyIOLayerMethods *ToMethods(PRFileDesc *f) {
return reinterpret_cast<DummyIOLayerMethods *>(f->secret);
}
static PRStatus DummyClose(PRFileDesc *f) { return ToMethods(f)->Close(f); }
static int32_t DummyRead(PRFileDesc *f, void *buf, int32_t length) {
return ToMethods(f)->Read(f, buf, length);
}
static int32_t DummyWrite(PRFileDesc *f, const void *buf, int32_t length) {
return ToMethods(f)->Write(f, buf, length);
}
static int32_t DummyAvailable(PRFileDesc *f) {
return ToMethods(f)->Available(f);
}
static int64_t DummyAvailable64(PRFileDesc *f) {
return ToMethods(f)->Available64(f);
}
static PRStatus DummySync(PRFileDesc *f) { return ToMethods(f)->Sync(f); }
static int32_t DummySeek(PRFileDesc *f, int32_t offset, PRSeekWhence how) {
return ToMethods(f)->Seek(f, offset, how);
}
static int64_t DummySeek64(PRFileDesc *f, int64_t offset, PRSeekWhence how) {
return ToMethods(f)->Seek64(f, offset, how);
}
static PRStatus DummyFileInfo(PRFileDesc *f, PRFileInfo *info) {
return ToMethods(f)->FileInfo(f, info);
}
static PRStatus DummyFileInfo64(PRFileDesc *f, PRFileInfo64 *info) {
return ToMethods(f)->FileInfo64(f, info);
}
static int32_t DummyWritev(PRFileDesc *f, const PRIOVec *iov, int32_t iov_size,
PRIntervalTime to) {
return ToMethods(f)->Writev(f, iov, iov_size, to);
}
static PRStatus DummyConnect(PRFileDesc *f, const PRNetAddr *addr,
PRIntervalTime to) {
return ToMethods(f)->Connect(f, addr, to);
}
static PRFileDesc *DummyAccept(PRFileDesc *f, PRNetAddr *addr,
PRIntervalTime to) {
return ToMethods(f)->Accept(f, addr, to);
}
static PRStatus DummyBind(PRFileDesc *f, const PRNetAddr *addr) {
return ToMethods(f)->Bind(f, addr);
}
static PRStatus DummyListen(PRFileDesc *f, int32_t depth) {
return ToMethods(f)->Listen(f, depth);
}
static PRStatus DummyShutdown(PRFileDesc *f, int32_t how) {
return ToMethods(f)->Shutdown(f, how);
}
static int32_t DummyRecv(PRFileDesc *f, void *buf, int32_t buflen,
int32_t flags, PRIntervalTime to) {
return ToMethods(f)->Recv(f, buf, buflen, flags, to);
}
static int32_t DummySend(PRFileDesc *f, const void *buf, int32_t amount,
int32_t flags, PRIntervalTime to) {
return ToMethods(f)->Send(f, buf, amount, flags, to);
}
static int32_t DummyRecvfrom(PRFileDesc *f, void *buf, int32_t amount,
int32_t flags, PRNetAddr *addr,
PRIntervalTime to) {
return ToMethods(f)->Recvfrom(f, buf, amount, flags, addr, to);
}
static int32_t DummySendto(PRFileDesc *f, const void *buf, int32_t amount,
int32_t flags, const PRNetAddr *addr,
PRIntervalTime to) {
return ToMethods(f)->Sendto(f, buf, amount, flags, addr, to);
}
static int16_t DummyPoll(PRFileDesc *f, int16_t in_flags, int16_t *out_flags) {
return ToMethods(f)->Poll(f, in_flags, out_flags);
}
static int32_t DummyAcceptRead(PRFileDesc *f, PRFileDesc **nd,
PRNetAddr **raddr, void *buf, int32_t amount,
PRIntervalTime t) {
return ToMethods(f)->AcceptRead(f, nd, raddr, buf, amount, t);
}
static int32_t DummyTransmitFile(PRFileDesc *sd, PRFileDesc *f,
const void *headers, int32_t hlen,
PRTransmitFileFlags flags, PRIntervalTime t) {
return ToMethods(f)->TransmitFile(sd, f, headers, hlen, flags, t);
}
static PRStatus DummyGetpeername(PRFileDesc *f, PRNetAddr *addr) {
return ToMethods(f)->Getpeername(f, addr);
}
static PRStatus DummyGetsockname(PRFileDesc *f, PRNetAddr *addr) {
return ToMethods(f)->Getsockname(f, addr);
}
static PRStatus DummyGetsockoption(PRFileDesc *f, PRSocketOptionData *opt) {
return ToMethods(f)->Getsockoption(f, opt);
}
static PRStatus DummySetsockoption(PRFileDesc *f,
const PRSocketOptionData *opt) {
return ToMethods(f)->Setsockoption(f, opt);
}
static int32_t DummySendfile(PRFileDesc *f, PRSendFileData *in,
PRTransmitFileFlags flags, PRIntervalTime to) {
return ToMethods(f)->Sendfile(f, in, flags, to);
}
static PRStatus DummyConnectContinue(PRFileDesc *f, int16_t flags) {
return ToMethods(f)->ConnectContinue(f, flags);
}
static int32_t DummyReserved(PRFileDesc *f) {
return ToMethods(f)->Reserved(f);
}
extern const struct PRIOMethods DummyMethodsForward = {
PR_DESC_LAYERED, DummyClose,
DummyRead, DummyWrite,
DummyAvailable, DummyAvailable64,
DummySync, DummySeek,
DummySeek64, DummyFileInfo,
DummyFileInfo64, DummyWritev,
DummyConnect, DummyAccept,
DummyBind, DummyListen,
DummyShutdown, DummyRecv,
DummySend, DummyRecvfrom,
DummySendto, DummyPoll,
DummyAcceptRead, DummyTransmitFile,
DummyGetsockname, DummyGetpeername,
DummyReserved, DummyReserved,
DummyGetsockoption, DummySetsockoption,
DummySendfile, DummyConnectContinue,
DummyReserved, DummyReserved,
DummyReserved, DummyReserved};

View file

@ -0,0 +1,24 @@
#
# 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/.
CORE_DEPTH = ..
DEPTH = ..
MODULE = nss
LIBRARY_NAME = cpputil
ifeq ($(NSS_BUILD_UTIL_ONLY),1)
CPPSRCS = \
$(NULL)
else
CPPSRCS = \
databuffer.cc \
dummy_io.cc \
dummy_io_fwd.cc \
tls_parser.cc \
$(NULL)
endif
EXPORTS = \
$(NULL)

View file

@ -0,0 +1,74 @@
/* -*- 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 scoped_ptrs_h__
#define scoped_ptrs_h__
#include <memory>
#include "cert.h"
#include "keyhi.h"
#include "pk11pub.h"
#include "pkcs11uri.h"
struct ScopedDelete {
void operator()(CERTCertificate* cert) { CERT_DestroyCertificate(cert); }
void operator()(CERTCertificateList* list) {
CERT_DestroyCertificateList(list);
}
void operator()(CERTName* name) { CERT_DestroyName(name); }
void operator()(CERTCertList* list) { CERT_DestroyCertList(list); }
void operator()(CERTSubjectPublicKeyInfo* spki) {
SECKEY_DestroySubjectPublicKeyInfo(spki);
}
void operator()(PK11SlotInfo* slot) { PK11_FreeSlot(slot); }
void operator()(PK11SymKey* key) { PK11_FreeSymKey(key); }
void operator()(PRFileDesc* fd) { PR_Close(fd); }
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()(SECKEYPrivateKeyList* list) {
SECKEY_DestroyPrivateKeyList(list);
}
void operator()(PK11URI* uri) { PK11URI_DestroyURI(uri); }
void operator()(PLArenaPool* arena) { PORT_FreeArena(arena, PR_FALSE); }
void operator()(PK11Context* context) { PK11_DestroyContext(context, true); }
void operator()(PK11GenericObject* obj) { PK11_DestroyGenericObject(obj); }
};
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(CERTCertList);
SCOPED(CERTName);
SCOPED(CERTSubjectPublicKeyInfo);
SCOPED(PK11SlotInfo);
SCOPED(PK11SymKey);
SCOPED(PRFileDesc);
SCOPED(SECAlgorithmID);
SCOPED(SECItem);
SCOPED(SECKEYPublicKey);
SCOPED(SECKEYPrivateKey);
SCOPED(SECKEYPrivateKeyList);
SCOPED(PK11URI);
SCOPED(PLArenaPool);
SCOPED(PK11Context);
SCOPED(PK11GenericObject);
#undef SCOPED
#endif // scoped_ptrs_h__

View file

@ -0,0 +1,39 @@
/* -*- 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 scoped_ptrs_util_h__
#define scoped_ptrs_util_h__
#include <memory>
#include "pkcs11uri.h"
#include "secoid.h"
struct ScopedDelete {
void operator()(SECAlgorithmID* id) { SECOID_DestroyAlgorithmID(id, true); }
void operator()(SECItem* item) { SECITEM_FreeItem(item, true); }
void operator()(PK11URI* uri) { PK11URI_DestroyURI(uri); }
void operator()(PLArenaPool* arena) { PORT_FreeArena(arena, PR_FALSE); }
};
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(SECAlgorithmID);
SCOPED(SECItem);
SCOPED(PK11URI);
#undef SCOPED
#endif // scoped_ptrs_util_h__

View file

@ -0,0 +1,73 @@
/* -*- 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_parser.h"
namespace nss_test {
bool TlsParser::Read(uint8_t* val) {
if (remaining() < 1) {
return false;
}
*val = *ptr();
consume(1);
return true;
}
bool TlsParser::Read(uint32_t* val, size_t size) {
if (size > sizeof(uint32_t)) {
return false;
}
uint32_t v = 0;
for (size_t i = 0; i < size; ++i) {
uint8_t tmp;
if (!Read(&tmp)) {
return false;
}
v = (v << 8) | tmp;
}
*val = v;
return true;
}
bool TlsParser::Read(DataBuffer* val, size_t len) {
if (remaining() < len) {
return false;
}
val->Assign(ptr(), len);
consume(len);
return true;
}
bool TlsParser::ReadVariable(DataBuffer* val, size_t len_size) {
uint32_t len;
if (!Read(&len, len_size)) {
return false;
}
return Read(val, len);
}
bool TlsParser::Skip(size_t len) {
if (len > remaining()) {
return false;
}
consume(len);
return true;
}
bool TlsParser::SkipVariable(size_t len_size) {
uint32_t len;
if (!Read(&len, len_size)) {
return false;
}
return Skip(len);
}
} // namespace nss_test

View file

@ -0,0 +1,145 @@
/* -*- 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_parser_h_
#define tls_parser_h_
#include <cstdint>
#include <cstring>
#include <memory>
#if defined(WIN32) || defined(WIN64)
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
#include "databuffer.h"
#include "sslt.h"
namespace nss_test {
const uint8_t kTlsChangeCipherSpecType = 20;
const uint8_t kTlsAlertType = 21;
const uint8_t kTlsHandshakeType = 22;
const uint8_t kTlsApplicationDataType = 23;
const uint8_t kTlsAltHandshakeType = 24;
const uint8_t kTlsAckType = 25;
const uint8_t kTlsHandshakeClientHello = 1;
const uint8_t kTlsHandshakeServerHello = 2;
const uint8_t kTlsHandshakeNewSessionTicket = 4;
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 kTlsAlertCloseNotify = 0;
const uint8_t kTlsAlertUnexpectedMessage = 10;
const uint8_t kTlsAlertBadRecordMac = 20;
const uint8_t kTlsAlertRecordOverflow = 22;
const uint8_t kTlsAlertHandshakeFailure = 40;
const uint8_t kTlsAlertIllegalParameter = 47;
const uint8_t kTlsAlertDecodeError = 50;
const uint8_t kTlsAlertDecryptError = 51;
const uint8_t kTlsAlertProtocolVersion = 70;
const uint8_t kTlsAlertInternalError = 80;
const uint8_t kTlsAlertInappropriateFallback = 86;
const uint8_t kTlsAlertMissingExtension = 109;
const uint8_t kTlsAlertUnsupportedExtension = 110;
const uint8_t kTlsAlertUnrecognizedName = 112;
const uint8_t kTlsAlertNoApplicationProtocol = 120;
const uint8_t kTlsFakeChangeCipherSpec[] = {
kTlsChangeCipherSpecType, // Type
0xfe,
0xff, // Version
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x10, // Fictitious sequence #
0x00,
0x01, // Length
0x01 // Value
};
static const uint8_t kTls13PskKe = 0;
static const uint8_t kTls13PskDhKe = 1;
static const uint8_t kTls13PskAuth = 0;
static const uint8_t kTls13PskSignAuth = 1;
inline std::ostream& operator<<(std::ostream& os, SSLProtocolVariant v) {
return os << ((v == ssl_variant_stream) ? "TLS" : "DTLS");
}
inline bool IsDtls(uint16_t version) { return (version & 0x8000) == 0x8000; }
inline uint16_t NormalizeTlsVersion(uint16_t version) {
if (version == 0xfeff) {
return 0x0302; // special: DTLS 1.0 == TLS 1.1
}
if (IsDtls(version)) {
return (version ^ 0xffff) + 0x0201;
}
return version;
}
inline uint16_t TlsVersionToDtlsVersion(uint16_t version) {
if (version == 0x0302) {
return 0xfeff;
}
if (version == 0x0304) {
return version;
}
return 0xffff - version + 0x0201;
}
inline size_t WriteVariable(DataBuffer* target, size_t index,
const DataBuffer& buf, size_t len_size) {
index = target->Write(index, static_cast<uint32_t>(buf.len()), len_size);
return target->Write(index, buf.data(), buf.len());
}
class TlsParser {
public:
TlsParser(const uint8_t* data, size_t len) : buffer_(data, len), offset_(0) {}
explicit TlsParser(const DataBuffer& buf) : buffer_(buf), offset_(0) {}
bool Read(uint8_t* val);
// Read an integral type of specified width.
bool Read(uint32_t* val, size_t size);
// Reads len bytes into dest buffer, overwriting it.
bool Read(DataBuffer* dest, size_t len);
// Reads bytes into dest buffer, overwriting it. The number of bytes is
// determined by reading from len_size bytes from the stream first.
bool ReadVariable(DataBuffer* dest, size_t len_size);
bool Skip(size_t len);
bool SkipVariable(size_t len_size);
size_t consumed() const { return offset_; }
size_t remaining() const { return buffer_.len() - offset_; }
private:
void consume(size_t len) { offset_ += len; }
const uint8_t* ptr() const { return buffer_.data() + offset_; }
DataBuffer buffer_;
size_t offset_;
};
} // namespace nss_test
#endif

View file

@ -455,6 +455,16 @@ of the attribute codes:
<listitem><para>Set an alternate exponent value to use in generating a new RSA public key for the database, instead of the default value of 65537. The available alternate values are 3 and 17.</para></listitem> <listitem><para>Set an alternate exponent value to use in generating a new RSA public key for the database, instead of the default value of 65537. The available alternate values are 3 and 17.</para></listitem>
</varlistentry> </varlistentry>
<varlistentry>
<term>--pss</term>
<listitem><para>Restrict the generated certificate (with the <option>-S</option> option) or certificate request (with the <option>-R</option> option) to be used with the RSA-PSS signature scheme. This only works when the private key of the certificate or certificate request is RSA.</para></listitem>
</varlistentry>
<varlistentry>
<term>--pss-sign</term>
<listitem><para>Sign the generated certificate with the RSA-PSS signature scheme (with the <option>-C</option> or <option>-S</option> option). This only works when the private key of the signer's certificate is RSA. If the signer's certificate is restricted to RSA-PSS, it is not necessary to specify this option.</para></listitem>
</varlistentry>
<varlistentry> <varlistentry>
<term>-z noise-file</term> <term>-z noise-file</term>
<listitem><para>Read a seed value from the specified file to generate a new private and public key pair. This argument makes it possible to use hardware-generated seed values or manually create a value from the keyboard. The minimum file size is 20 bytes.</para></listitem> <listitem><para>Read a seed value from the specified file to generate a new private and public key pair. This argument makes it possible to use hardware-generated seed values or manually create a value from the keyboard. The minimum file size is 20 bytes.</para></listitem>

View file

@ -1,4 +1,4 @@
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>CERTUTIL</title><meta name="generator" content="DocBook XSL Stylesheets V1.78.1"><link rel="home" href="index.html" title="CERTUTIL"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">CERTUTIL</th></tr></table><hr></div><div class="refentry"><a name="certutil"></a><div class="titlepage"></div><div class="refnamediv"><h2>Name</h2><p>certutil — Manage keys and certificate in both NSS databases and other NSS tokens</p></div><div class="refsynopsisdiv"><h2>Synopsis</h2><div class="cmdsynopsis"><p><code class="command">certutil</code> [<em class="replaceable"><code>options</code></em>] [[<em class="replaceable"><code>arguments</code></em>]]</p></div></div><div class="refsection"><a name="idm139774553663312"></a><h2>STATUS</h2><p>This documentation is still work in progress. Please contribute to the initial review in <a class="ulink" href="https://bugzilla.mozilla.org/show_bug.cgi?id=836477" target="_top">Mozilla NSS bug 836477</a> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>CERTUTIL</title><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot"><link rel="home" href="index.html" title="CERTUTIL"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">CERTUTIL</th></tr></table><hr></div><div class="refentry"><a name="certutil"></a><div class="titlepage"></div><div class="refnamediv"><h2>Name</h2><p>certutil — Manage keys and certificate in both NSS databases and other NSS tokens</p></div><div class="refsynopsisdiv"><h2>Synopsis</h2><div class="cmdsynopsis"><p><code class="command">certutil</code> [<em class="replaceable"><code>options</code></em>] [[<em class="replaceable"><code>arguments</code></em>]]</p></div></div><div class="refsection"><a name="idm140440587239488"></a><h2>STATUS</h2><p>This documentation is still work in progress. Please contribute to the initial review in <a class="ulink" href="https://bugzilla.mozilla.org/show_bug.cgi?id=836477" target="_top">Mozilla NSS bug 836477</a>
</p></div><div class="refsection"><a name="description"></a><h2>Description</h2><p>The Certificate Database Tool, <span class="command"><strong>certutil</strong></span>, is a command-line utility that can create and modify certificate and key databases. It can specifically list, generate, modify, or delete certificates, create or change the password, generate new public and private key pairs, display the contents of the key database, or delete key pairs within the key database.</p><p>Certificate issuance, part of the key and certificate management process, requires that keys and certificates be created in the key database. This document discusses certificate and key database management. For information on the security module database management, see the <span class="command"><strong>modutil</strong></span> manpage.</p></div><div class="refsection"><a name="options"></a><h2>Command Options and Arguments</h2><p>Running <span class="command"><strong>certutil</strong></span> always requires one and only one command option to specify the type of certificate operation. Each command option may take zero or more arguments. The command option <code class="option">-H</code> will list all the command options and their relevant arguments.</p><p><span class="command"><strong>Command Options</strong></span></p><div class="variablelist"><dl class="variablelist"><dt><span class="term">-A </span></dt><dd><p>Add an existing certificate to a certificate database. The certificate database should already exist; if one is not present, this command option will initialize one by default.</p></dd><dt><span class="term">-B</span></dt><dd><p>Run a series of commands from the specified batch file. This requires the <code class="option">-i</code> argument.</p></dd><dt><span class="term">-C </span></dt><dd><p>Create a new binary certificate file from a binary certificate request file. Use the <code class="option">-i</code> argument to specify the certificate request file. If this argument is not used, <span class="command"><strong>certutil</strong></span> prompts for a filename. </p></dd><dt><span class="term">-D </span></dt><dd><p>Delete a certificate from the certificate database.</p></dd><dt><span class="term">--rename </span></dt><dd><p>Change the database nickname of a certificate.</p></dd><dt><span class="term">-E </span></dt><dd><p>Add an email certificate to the certificate database.</p></dd><dt><span class="term">-F</span></dt><dd><p>Delete a private key from a key database. Specify the key to delete with the -n argument. Specify the database from which to delete the key with the </p></div><div class="refsection"><a name="description"></a><h2>Description</h2><p>The Certificate Database Tool, <span class="command"><strong>certutil</strong></span>, is a command-line utility that can create and modify certificate and key databases. It can specifically list, generate, modify, or delete certificates, create or change the password, generate new public and private key pairs, display the contents of the key database, or delete key pairs within the key database.</p><p>Certificate issuance, part of the key and certificate management process, requires that keys and certificates be created in the key database. This document discusses certificate and key database management. For information on the security module database management, see the <span class="command"><strong>modutil</strong></span> manpage.</p></div><div class="refsection"><a name="options"></a><h2>Command Options and Arguments</h2><p>Running <span class="command"><strong>certutil</strong></span> always requires one and only one command option to specify the type of certificate operation. Each command option may take zero or more arguments. The command option <code class="option">-H</code> will list all the command options and their relevant arguments.</p><p><span class="command"><strong>Command Options</strong></span></p><div class="variablelist"><dl class="variablelist"><dt><span class="term">-A </span></dt><dd><p>Add an existing certificate to a certificate database. The certificate database should already exist; if one is not present, this command option will initialize one by default.</p></dd><dt><span class="term">-B</span></dt><dd><p>Run a series of commands from the specified batch file. This requires the <code class="option">-i</code> argument.</p></dd><dt><span class="term">-C </span></dt><dd><p>Create a new binary certificate file from a binary certificate request file. Use the <code class="option">-i</code> argument to specify the certificate request file. If this argument is not used, <span class="command"><strong>certutil</strong></span> prompts for a filename. </p></dd><dt><span class="term">-D </span></dt><dd><p>Delete a certificate from the certificate database.</p></dd><dt><span class="term">--rename </span></dt><dd><p>Change the database nickname of a certificate.</p></dd><dt><span class="term">-E </span></dt><dd><p>Add an email certificate to the certificate database.</p></dd><dt><span class="term">-F</span></dt><dd><p>Delete a private key from a key database. Specify the key to delete with the -n argument. Specify the database from which to delete the key with the
<code class="option">-d</code> argument. Use the <code class="option">-k</code> argument to specify explicitly whether to delete a DSA, RSA, or ECC key. If you don't use the <code class="option">-k</code> argument, the option looks for an RSA key matching the specified nickname. <code class="option">-d</code> argument. Use the <code class="option">-k</code> argument to specify explicitly whether to delete a DSA, RSA, or ECC key. If you don't use the <code class="option">-k</code> argument, the option looks for an RSA key matching the specified nickname.
</p><p> </p><p>
@ -20,7 +20,8 @@ Add one or multiple extensions that certutil cannot encode yet, by loading their
duplicate nicknames. Giving a key type generates a new key pair; duplicate nicknames. Giving a key type generates a new key pair;
giving the ID of an existing key reuses that key pair (which is giving the ID of an existing key reuses that key pair (which is
required to renew certificates). required to renew certificates).
</p></dd><dt><span class="term">-l </span></dt><dd><p>Display detailed information when validating a certificate with the -V option.</p></dd><dt><span class="term">-m serial-number</span></dt><dd><p>Assign a unique serial number to a certificate being created. This operation should be performed by a CA. If no serial number is provided a default serial number is made from the current time. Serial numbers are limited to integers </p></dd><dt><span class="term">-n nickname</span></dt><dd><p>Specify the nickname of a certificate or key to list, create, add to a database, modify, or validate. Bracket the nickname string with quotation marks if it contains spaces.</p></dd><dt><span class="term">-o output-file</span></dt><dd><p>Specify the output file name for new certificates or binary certificate requests. Bracket the output-file string with quotation marks if it contains spaces. If this argument is not used the output destination defaults to standard output.</p></dd><dt><span class="term">-P dbPrefix</span></dt><dd><p>Specify the prefix used on the certificate and key database file. This argument is provided to support legacy servers. Most applications do not use a database prefix.</p></dd><dt><span class="term">-p phone</span></dt><dd><p>Specify a contact telephone number to include in new certificates or certificate requests. Bracket this string with quotation marks if it contains spaces.</p></dd><dt><span class="term">-q pqgfile or curve-name</span></dt><dd><p>Read an alternate PQG value from the specified file when generating DSA key pairs. If this argument is not used, <span class="command"><strong>certutil</strong></span> generates its own PQG value. PQG files are created with a separate DSA utility.</p><p>Elliptic curve name is one of the ones from nistp256, nistp384, nistp521, curve25519.</p><p>If a token is available that supports more curves, the foolowing curves are supported as well: </p></dd><dt><span class="term">-l </span></dt><dd><p>Display detailed information when validating a certificate with the -V option.</p></dd><dt><span class="term">-m serial-number</span></dt><dd><p>Assign a unique serial number to a certificate being created. This operation should be performed by a CA. If no serial number is provided a default serial number is made from the current time. Serial numbers are limited to integers </p></dd><dt><span class="term">-n nickname</span></dt><dd><p>Specify the nickname of a certificate or key to list, create, add to a database, modify, or validate. Bracket the nickname string with quotation marks if it contains spaces.</p></dd><dt><span class="term">-o output-file</span></dt><dd><p>Specify the output file name for new certificates or binary certificate requests. Bracket the output-file string with quotation marks if it contains spaces. If this argument is not used the output destination defaults to standard output.</p></dd><dt><span class="term">-P dbPrefix</span></dt><dd><p>Specify the prefix used on the certificate and key database file. This argument is provided to support legacy servers. Most applications do not use a database prefix.</p></dd><dt><span class="term">-p phone</span></dt><dd><p>Specify a contact telephone number to include in new certificates or certificate requests. Bracket this string with quotation marks if it contains spaces.</p></dd><dt><span class="term">-q pqgfile or curve-name</span></dt><dd><p>Read an alternate PQG value from the specified file when generating DSA key pairs. If this argument is not used, <span class="command"><strong>certutil</strong></span> generates its own PQG value. PQG files are created with a separate DSA utility.</p><p>Elliptic curve name is one of the ones from nistp256, nistp384, nistp521, curve25519.</p><p>
If a token is available that supports more curves, the foolowing curves are supported as well:
sect163k1, nistk163, sect163r1, sect163r2, sect163k1, nistk163, sect163r1, sect163r2,
nistb163, sect193r1, sect193r2, sect233k1, nistk233, nistb163, sect193r1, sect193r2, sect233k1, nistk233,
sect233r1, nistb233, sect239k1, sect283k1, nistk283, sect233r1, nistb233, sect239k1, sect283k1, nistk283,
@ -37,8 +38,8 @@ Add one or multiple extensions that certutil cannot encode yet, by loading their
c2pnb272w1, c2pnb304w1, c2pnb272w1, c2pnb304w1,
c2tnb359w1, c2pnb368w1, c2tnb431r1, secp112r1, c2tnb359w1, c2pnb368w1, c2tnb431r1, secp112r1,
secp112r2, secp128r1, secp128r2, sect113r1, sect113r2, secp112r2, secp128r1, secp128r2, sect113r1, sect113r2,
sect131r1, sect131r2</p> sect131r1, sect131r2
</dd><dt><span class="term">-r </span></dt><dd><p>Display a certificate's binary DER encoding when listing information about that certificate with the -L option.</p></dd><dt><span class="term">-s subject</span></dt><dd><p>Identify a particular certificate owner for new certificates or certificate requests. Bracket this string with quotation marks if it contains spaces. The subject identification format follows RFC #1485.</p></dd><dt><span class="term">-t trustargs</span></dt><dd><p>Specify the trust attributes to modify in an existing certificate or to apply to a certificate when creating it or adding it to a database. There are three available trust categories for each certificate, expressed in the order <span class="emphasis"><em>SSL, email, object signing</em></span> for each trust setting. In each category position, use none, any, or all </p></dd><dt><span class="term">-r </span></dt><dd><p>Display a certificate's binary DER encoding when listing information about that certificate with the -L option.</p></dd><dt><span class="term">-s subject</span></dt><dd><p>Identify a particular certificate owner for new certificates or certificate requests. Bracket this string with quotation marks if it contains spaces. The subject identification format follows RFC #1485.</p></dd><dt><span class="term">-t trustargs</span></dt><dd><p>Specify the trust attributes to modify in an existing certificate or to apply to a certificate when creating it or adding it to a database. There are three available trust categories for each certificate, expressed in the order <span class="emphasis"><em>SSL, email, object signing</em></span> for each trust setting. In each category position, use none, any, or all
of the attribute codes: of the attribute codes:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<span class="command"><strong>p</strong></span> - Valid peer <span class="command"><strong>p</strong></span> - Valid peer
@ -59,7 +60,7 @@ of the attribute codes:
the certificate or adding it to a database. Express the offset in integers, the certificate or adding it to a database. Express the offset in integers,
using a minus sign (-) to indicate a negative offset. If this argument is using a minus sign (-) to indicate a negative offset. If this argument is
not used, the validity period begins at the current system time. The length not used, the validity period begins at the current system time. The length
of the validity period is set with the -v argument. </p></dd><dt><span class="term">-X </span></dt><dd><p>Force the key and certificate database to open in read-write mode. This is used with the <code class="option">-U</code> and <code class="option">-L</code> command options.</p></dd><dt><span class="term">-x </span></dt><dd><p>Use <span class="command"><strong>certutil</strong></span> to generate the signature for a certificate being created or added to a database, rather than obtaining a signature from a separate CA.</p></dd><dt><span class="term">-y exp</span></dt><dd><p>Set an alternate exponent value to use in generating a new RSA public key for the database, instead of the default value of 65537. The available alternate values are 3 and 17.</p></dd><dt><span class="term">-z noise-file</span></dt><dd><p>Read a seed value from the specified file to generate a new private and public key pair. This argument makes it possible to use hardware-generated seed values or manually create a value from the keyboard. The minimum file size is 20 bytes.</p></dd><dt><span class="term">-Z hashAlg</span></dt><dd><p>Specify the hash algorithm to use with the -C, -S or -R command options. Possible keywords:</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>MD2</p></li><li class="listitem"><p>MD4</p></li><li class="listitem"><p>MD5</p></li><li class="listitem"><p>SHA1</p></li><li class="listitem"><p>SHA224</p></li><li class="listitem"><p>SHA256</p></li><li class="listitem"><p>SHA384</p></li><li class="listitem"><p>SHA512</p></li></ul></div></dd><dt><span class="term">-0 SSO_password</span></dt><dd><p>Set a site security officer password on a token.</p></dd><dt><span class="term">-1 | --keyUsage keyword,keyword</span></dt><dd><p>Set an X.509 V3 Certificate Type Extension in the certificate. There are several available keywords:</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> of the validity period is set with the -v argument. </p></dd><dt><span class="term">-X </span></dt><dd><p>Force the key and certificate database to open in read-write mode. This is used with the <code class="option">-U</code> and <code class="option">-L</code> command options.</p></dd><dt><span class="term">-x </span></dt><dd><p>Use <span class="command"><strong>certutil</strong></span> to generate the signature for a certificate being created or added to a database, rather than obtaining a signature from a separate CA.</p></dd><dt><span class="term">-y exp</span></dt><dd><p>Set an alternate exponent value to use in generating a new RSA public key for the database, instead of the default value of 65537. The available alternate values are 3 and 17.</p></dd><dt><span class="term">--pss</span></dt><dd><p>Restrict the generated certificate (with the <code class="option">-S</code> option) or certificate request (with the <code class="option">-R</code> option) to be used with the RSA-PSS signature scheme. This only works when the private key of the certificate or certificate request is RSA.</p></dd><dt><span class="term">--pss-sign</span></dt><dd><p>Sign the generated certificate with the RSA-PSS signature scheme (with the <code class="option">-C</code> or <code class="option">-S</code> option). This only works when the private key of the signer's certificate is RSA. If the signer's certificate is restricted to RSA-PSS, it is not necessary to specify this option.</p></dd><dt><span class="term">-z noise-file</span></dt><dd><p>Read a seed value from the specified file to generate a new private and public key pair. This argument makes it possible to use hardware-generated seed values or manually create a value from the keyboard. The minimum file size is 20 bytes.</p></dd><dt><span class="term">-Z hashAlg</span></dt><dd><p>Specify the hash algorithm to use with the -C, -S or -R command options. Possible keywords:</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>MD2</p></li><li class="listitem"><p>MD4</p></li><li class="listitem"><p>MD5</p></li><li class="listitem"><p>SHA1</p></li><li class="listitem"><p>SHA224</p></li><li class="listitem"><p>SHA256</p></li><li class="listitem"><p>SHA384</p></li><li class="listitem"><p>SHA512</p></li></ul></div></dd><dt><span class="term">-0 SSO_password</span></dt><dd><p>Set a site security officer password on a token.</p></dd><dt><span class="term">-1 | --keyUsage keyword,keyword</span></dt><dd><p>Set an X.509 V3 Certificate Type Extension in the certificate. There are several available keywords:</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
digitalSignature digitalSignature
</p></li><li class="listitem"><p> </p></li><li class="listitem"><p>
nonRepudiation nonRepudiation

View file

@ -1,5 +1,5 @@
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>PK12UTIL</title><meta name="generator" content="DocBook XSL Stylesheets V1.78.1"><link rel="home" href="index.html" title="PK12UTIL"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">PK12UTIL</th></tr></table><hr></div><div class="refentry"><a name="pk12util"></a><div class="titlepage"></div><div class="refnamediv"><h2>Name</h2><p>pk12util — Export and import keys and certificate to or from a PKCS #12 file and the NSS database</p></div><div class="refsynopsisdiv"><h2>Synopsis</h2><div class="cmdsynopsis"><p><code class="command">pk12util</code> [-i p12File|-l p12File|-o p12File] [-d [sql:]directory] [-h tokenname] [-P dbprefix] [-r] [-v] [-k slotPasswordFile|-K slotPassword] [-w p12filePasswordFile|-W p12filePassword]</p></div></div><div class="refsection"><a name="idm233250345408"></a><h2>STATUS</h2><p>This documentation is still work in progress. Please contribute to the initial review in <a class="ulink" href="https://bugzilla.mozilla.org/show_bug.cgi?id=836477" target="_top">Mozilla NSS bug 836477</a> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>PK12UTIL</title><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot"><link rel="home" href="index.html" title="PK12UTIL"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">PK12UTIL</th></tr></table><hr></div><div class="refentry"><a name="pk12util"></a><div class="titlepage"></div><div class="refnamediv"><h2>Name</h2><p>pk12util — Export and import keys and certificate to or from a PKCS #12 file and the NSS database</p></div><div class="refsynopsisdiv"><h2>Synopsis</h2><div class="cmdsynopsis"><p><code class="command">pk12util</code> [-i p12File|-l p12File|-o p12File] [-d [sql:]directory] [-h tokenname] [-P dbprefix] [-r] [-v] [-k slotPasswordFile|-K slotPassword] [-w p12filePasswordFile|-W p12filePassword]</p></div></div><div class="refsection"><a name="idm139975398059856"></a><h2>STATUS</h2><p>This documentation is still work in progress. Please contribute to the initial review in <a class="ulink" href="https://bugzilla.mozilla.org/show_bug.cgi?id=836477" target="_top">Mozilla NSS bug 836477</a>
</p></div><div class="refsection"><a name="description"></a><h2>Description</h2><p>The PKCS #12 utility, <span class="command"><strong>pk12util</strong></span>, enables sharing certificates among any server that supports PKCS#12. The tool can import certificates and keys from PKCS#12 files into security databases, export certificates, and list certificates and keys.</p></div><div class="refsection"><a name="options"></a><h2>Options and Arguments</h2><p><span class="command"><strong>Options</strong></span></p><div class="variablelist"><dl class="variablelist"><dt><span class="term">-i p12file</span></dt><dd><p>Import keys and certificates from a PKCS#12 file into a security database.</p></dd><dt><span class="term">-l p12file</span></dt><dd><p>List the keys and certificates in PKCS#12 file.</p></dd><dt><span class="term">-o p12file</span></dt><dd><p>Export keys and certificates from the security database to a PKCS#12 file.</p></dd></dl></div><p><span class="command"><strong>Arguments</strong></span></p><div class="variablelist"><dl class="variablelist"><dt><span class="term">-c keyCipher</span></dt><dd><p>Specify the key encryption algorithm.</p></dd><dt><span class="term">-C certCipher</span></dt><dd><p>Specify the key cert (overall package) encryption algorithm.</p></dd><dt><span class="term">-d [sql:]directory</span></dt><dd><p>Specify the database directory into which to import to or export from certificates and keys.</p><p><span class="command"><strong>pk12util</strong></span> supports two types of databases: the legacy security databases (<code class="filename">cert8.db</code>, <code class="filename">key3.db</code>, and <code class="filename">secmod.db</code>) and new SQLite databases (<code class="filename">cert9.db</code>, <code class="filename">key4.db</code>, and <code class="filename">pkcs11.txt</code>). If the prefix <span class="command"><strong>sql:</strong></span> is not used, then the tool assumes that the given databases are in the old format.</p></dd><dt><span class="term">-h tokenname</span></dt><dd><p>Specify the name of the token to import into or export from.</p></dd><dt><span class="term">-k slotPasswordFile</span></dt><dd><p>Specify the text file containing the slot's password.</p></dd><dt><span class="term">-K slotPassword</span></dt><dd><p>Specify the slot's password.</p></dd><dt><span class="term">-m | --key-len keyLength</span></dt><dd><p>Specify the desired length of the symmetric key to be used to encrypt the private key.</p></dd><dt><span class="term">-n | --cert-key-len certKeyLength</span></dt><dd><p>Specify the desired length of the symmetric key to be used to encrypt the certificates and other meta-data.</p></dd><dt><span class="term">-n certname</span></dt><dd><p>Specify the nickname of the cert and private key to export.</p></dd><dt><span class="term">-P prefix</span></dt><dd><p>Specify the prefix used on the certificate and key databases. This option is provided as a special case. </p></div><div class="refsection"><a name="description"></a><h2>Description</h2><p>The PKCS #12 utility, <span class="command"><strong>pk12util</strong></span>, enables sharing certificates among any server that supports PKCS #12. The tool can import certificates and keys from PKCS #12 files into security databases, export certificates, and list certificates and keys.</p></div><div class="refsection"><a name="options"></a><h2>Options and Arguments</h2><p><span class="command"><strong>Options</strong></span></p><div class="variablelist"><dl class="variablelist"><dt><span class="term">-i p12file</span></dt><dd><p>Import keys and certificates from a PKCS #12 file into a security database.</p></dd><dt><span class="term">-l p12file</span></dt><dd><p>List the keys and certificates in PKCS #12 file.</p></dd><dt><span class="term">-o p12file</span></dt><dd><p>Export keys and certificates from the security database to a PKCS #12 file.</p></dd></dl></div><p><span class="command"><strong>Arguments</strong></span></p><div class="variablelist"><dl class="variablelist"><dt><span class="term">-c keyCipher</span></dt><dd><p>Specify the key encryption algorithm.</p></dd><dt><span class="term">-C certCipher</span></dt><dd><p>Specify the certiticate encryption algorithm.</p></dd><dt><span class="term">-d [sql:]directory</span></dt><dd><p>Specify the database directory into which to import to or export from certificates and keys.</p><p><span class="command"><strong>pk12util</strong></span> supports two types of databases: the legacy security databases (<code class="filename">cert8.db</code>, <code class="filename">key3.db</code>, and <code class="filename">secmod.db</code>) and new SQLite databases (<code class="filename">cert9.db</code>, <code class="filename">key4.db</code>, and <code class="filename">pkcs11.txt</code>). If the prefix <span class="command"><strong>sql:</strong></span> is not used, then the tool assumes that the given databases are in the old format.</p></dd><dt><span class="term">-h tokenname</span></dt><dd><p>Specify the name of the token to import into or export from.</p></dd><dt><span class="term">-k slotPasswordFile</span></dt><dd><p>Specify the text file containing the slot's password.</p></dd><dt><span class="term">-K slotPassword</span></dt><dd><p>Specify the slot's password.</p></dd><dt><span class="term">-m | --key-len keyLength</span></dt><dd><p>Specify the desired length of the symmetric key to be used to encrypt the private key.</p></dd><dt><span class="term">-n | --cert-key-len certKeyLength</span></dt><dd><p>Specify the desired length of the symmetric key to be used to encrypt the certificates and other meta-data.</p></dd><dt><span class="term">-n certname</span></dt><dd><p>Specify the nickname of the cert and private key to export.</p></dd><dt><span class="term">-P prefix</span></dt><dd><p>Specify the prefix used on the certificate and key databases. This option is provided as a special case.
Changing the names of the certificate and key databases is not recommended.</p></dd><dt><span class="term">-r</span></dt><dd><p>Dumps all of the data in raw (binary) form. This must be saved as a DER file. The default is to return information in a pretty-print ASCII format, which displays the information about the certificates and public keys in the p12 file.</p></dd><dt><span class="term">-v </span></dt><dd><p>Enable debug logging when importing.</p></dd><dt><span class="term">-w p12filePasswordFile</span></dt><dd><p>Specify the text file containing the pkcs #12 file password.</p></dd><dt><span class="term">-W p12filePassword</span></dt><dd><p>Specify the pkcs #12 file password.</p></dd></dl></div></div><div class="refsection"><a name="return-codes"></a><h2>Return Codes</h2><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> 0 - No error</p></li><li class="listitem"><p> 1 - User Cancelled</p></li><li class="listitem"><p> 2 - Usage error</p></li><li class="listitem"><p> 6 - NLS init error</p></li><li class="listitem"><p> 8 - Certificate DB open error</p></li><li class="listitem"><p> 9 - Key DB open error</p></li><li class="listitem"><p> 10 - File initialization error</p></li><li class="listitem"><p> 11 - Unicode conversion error</p></li><li class="listitem"><p> 12 - Temporary file creation error</p></li><li class="listitem"><p> 13 - PKCS11 get slot error</p></li><li class="listitem"><p> 14 - PKCS12 decoder start error</p></li><li class="listitem"><p> 15 - error read from import file</p></li><li class="listitem"><p> 16 - pkcs12 decode error</p></li><li class="listitem"><p> 17 - pkcs12 decoder verify error</p></li><li class="listitem"><p> 18 - pkcs12 decoder validate bags error</p></li><li class="listitem"><p> 19 - pkcs12 decoder import bags error</p></li><li class="listitem"><p> 20 - key db conversion version 3 to version 2 error</p></li><li class="listitem"><p> 21 - cert db conversion version 7 to version 5 error</p></li><li class="listitem"><p> 22 - cert and key dbs patch error</p></li><li class="listitem"><p> 23 - get default cert db error</p></li><li class="listitem"><p> 24 - find cert by nickname error</p></li><li class="listitem"><p> 25 - create export context error</p></li><li class="listitem"><p> 26 - PKCS12 add password itegrity error</p></li><li class="listitem"><p> 27 - cert and key Safes creation error</p></li><li class="listitem"><p> 28 - PKCS12 add cert and key error</p></li><li class="listitem"><p> 29 - PKCS12 encode error</p></li></ul></div></div><div class="refsection"><a name="examples"></a><h2>Examples</h2><p><span class="command"><strong>Importing Keys and Certificates</strong></span></p><p>The most basic usage of <span class="command"><strong>pk12util</strong></span> for importing a certificate or key is the PKCS #12 input file (<code class="option">-i</code>) and some way to specify the security database being accessed (either <code class="option">-d</code> for a directory or <code class="option">-h</code> for a token). Changing the names of the certificate and key databases is not recommended.</p></dd><dt><span class="term">-r</span></dt><dd><p>Dumps all of the data in raw (binary) form. This must be saved as a DER file. The default is to return information in a pretty-print ASCII format, which displays the information about the certificates and public keys in the p12 file.</p></dd><dt><span class="term">-v </span></dt><dd><p>Enable debug logging when importing.</p></dd><dt><span class="term">-w p12filePasswordFile</span></dt><dd><p>Specify the text file containing the pkcs #12 file password.</p></dd><dt><span class="term">-W p12filePassword</span></dt><dd><p>Specify the pkcs #12 file password.</p></dd></dl></div></div><div class="refsection"><a name="return-codes"></a><h2>Return Codes</h2><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> 0 - No error</p></li><li class="listitem"><p> 1 - User Cancelled</p></li><li class="listitem"><p> 2 - Usage error</p></li><li class="listitem"><p> 6 - NLS init error</p></li><li class="listitem"><p> 8 - Certificate DB open error</p></li><li class="listitem"><p> 9 - Key DB open error</p></li><li class="listitem"><p> 10 - File initialization error</p></li><li class="listitem"><p> 11 - Unicode conversion error</p></li><li class="listitem"><p> 12 - Temporary file creation error</p></li><li class="listitem"><p> 13 - PKCS11 get slot error</p></li><li class="listitem"><p> 14 - PKCS12 decoder start error</p></li><li class="listitem"><p> 15 - error read from import file</p></li><li class="listitem"><p> 16 - pkcs12 decode error</p></li><li class="listitem"><p> 17 - pkcs12 decoder verify error</p></li><li class="listitem"><p> 18 - pkcs12 decoder validate bags error</p></li><li class="listitem"><p> 19 - pkcs12 decoder import bags error</p></li><li class="listitem"><p> 20 - key db conversion version 3 to version 2 error</p></li><li class="listitem"><p> 21 - cert db conversion version 7 to version 5 error</p></li><li class="listitem"><p> 22 - cert and key dbs patch error</p></li><li class="listitem"><p> 23 - get default cert db error</p></li><li class="listitem"><p> 24 - find cert by nickname error</p></li><li class="listitem"><p> 25 - create export context error</p></li><li class="listitem"><p> 26 - PKCS12 add password itegrity error</p></li><li class="listitem"><p> 27 - cert and key Safes creation error</p></li><li class="listitem"><p> 28 - PKCS12 add cert and key error</p></li><li class="listitem"><p> 29 - PKCS12 encode error</p></li></ul></div></div><div class="refsection"><a name="examples"></a><h2>Examples</h2><p><span class="command"><strong>Importing Keys and Certificates</strong></span></p><p>The most basic usage of <span class="command"><strong>pk12util</strong></span> for importing a certificate or key is the PKCS #12 input file (<code class="option">-i</code>) and some way to specify the security database being accessed (either <code class="option">-d</code> for a directory or <code class="option">-h</code> for a token).
</p><p> </p><p>
pk12util -i p12File [-h tokenname] [-v] [-d [sql:]directory] [-P dbprefix] [-k slotPasswordFile|-K slotPassword] [-w p12filePasswordFile|-W p12filePassword] pk12util -i p12File [-h tokenname] [-v] [-d [sql:]directory] [-P dbprefix] [-k slotPasswordFile|-K slotPassword] [-w p12filePasswordFile|-W p12filePassword]
@ -48,7 +48,7 @@ Key(shrouded):
Certificate Friendly Name: Thawte Personal Freemail Issuing CA - Thawte Consulting Certificate Friendly Name: Thawte Personal Freemail Issuing CA - Thawte Consulting
Certificate Friendly Name: Thawte Freemail Member's Thawte Consulting (Pty) Ltd. ID Certificate Friendly Name: Thawte Freemail Member's Thawte Consulting (Pty) Ltd. ID
</pre></div><div class="refsection"><a name="encryption"></a><h2>Password Encryption</h2><p>PKCS#12 provides for not only the protection of the private keys but also the certificate and meta-data associated with the keys. Password-based encryption is used to protect private keys on export to a PKCS#12 file and, optionally, the entire package. If no algorithm is specified, the tool defaults to using <span class="command"><strong>PKCS12 V2 PBE with SHA1 and 3KEY Triple DES-cbc</strong></span> for private key encryption. <span class="command"><strong>PKCS12 V2 PBE with SHA1 and 40 Bit RC4</strong></span> is the default for the overall package encryption when not in FIPS mode. When in FIPS mode, there is no package encryption.</p><p>The private key is always protected with strong encryption by default.</p><p>Several types of ciphers are supported.</p><div class="variablelist"><dl class="variablelist"><dt><span class="term">Symmetric CBC ciphers for PKCS#5 V2</span></dt><dd><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>DES-CBC</p></li><li class="listitem"><p>RC2-CBC</p></li><li class="listitem"><p>RC5-CBCPad</p></li><li class="listitem"><p>DES-EDE3-CBC (the default for key encryption)</p></li><li class="listitem"><p>AES-128-CBC</p></li><li class="listitem"><p>AES-192-CBC</p></li><li class="listitem"><p>AES-256-CBC</p></li><li class="listitem"><p>CAMELLIA-128-CBC</p></li><li class="listitem"><p>CAMELLIA-192-CBC</p></li><li class="listitem"><p>CAMELLIA-256-CBC</p></li></ul></div></dd><dt><span class="term">PKCS#12 PBE ciphers</span></dt><dd><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>PKCS #12 PBE with Sha1 and 128 Bit RC4</p></li><li class="listitem"><p>PKCS #12 PBE with Sha1 and 40 Bit RC4</p></li><li class="listitem"><p>PKCS #12 PBE with Sha1 and Triple DES CBC</p></li><li class="listitem"><p>PKCS #12 PBE with Sha1 and 128 Bit RC2 CBC</p></li><li class="listitem"><p>PKCS #12 PBE with Sha1 and 40 Bit RC2 CBC</p></li><li class="listitem"><p>PKCS12 V2 PBE with SHA1 and 128 Bit RC4</p></li><li class="listitem"><p>PKCS12 V2 PBE with SHA1 and 40 Bit RC4 (the default for non-FIPS mode)</p></li><li class="listitem"><p>PKCS12 V2 PBE with SHA1 and 3KEY Triple DES-cbc</p></li><li class="listitem"><p>PKCS12 V2 PBE with SHA1 and 2KEY Triple DES-cbc</p></li><li class="listitem"><p>PKCS12 V2 PBE with SHA1 and 128 Bit RC2 CBC</p></li><li class="listitem"><p>PKCS12 V2 PBE with SHA1 and 40 Bit RC2 CBC</p></li></ul></div></dd><dt><span class="term">PKCS#5 PBE ciphers</span></dt><dd><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>PKCS #5 Password Based Encryption with MD2 and DES CBC</p></li><li class="listitem"><p>PKCS #5 Password Based Encryption with MD5 and DES CBC</p></li><li class="listitem"><p>PKCS #5 Password Based Encryption with SHA1 and DES CBC</p></li></ul></div></dd></dl></div><p>With PKCS#12, the crypto provider may be the soft token module or an external hardware module. If the cryptographic module does not support the requested algorithm, then the next best fit will be selected (usually the default). If no suitable replacement for the desired algorithm can be found, the tool returns the error <span class="emphasis"><em>no security module can perform the requested operation</em></span>.</p></div><div class="refsection"><a name="databases"></a><h2>NSS Database Types</h2><p>NSS originally used BerkeleyDB databases to store security information. </pre></div><div class="refsection"><a name="encryption"></a><h2>Password Encryption</h2><p>PKCS #12 provides for not only the protection of the private keys but also the certificate and meta-data associated with the keys. Password-based encryption is used to protect private keys on export to a PKCS #12 file and, optionally, the associated certificates. If no algorithm is specified, the tool defaults to using PKCS #12 SHA-1 and 3-key triple DES for private key encryption. When not in FIPS mode, PKCS #12 SHA-1 and 40-bit RC4 is used for certificate encryption. When in FIPS mode, there is no certificate encryption. If certificate encryption is not wanted, specify <strong class="userinput"><code>"NONE"</code></strong> as the argument of the <code class="option">-C</code> option.</p><p>The private key is always protected with strong encryption by default.</p><p>Several types of ciphers are supported.</p><div class="variablelist"><dl class="variablelist"><dt><span class="term">PKCS #5 password-based encryption</span></dt><dd><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>PBES2 with AES-CBC-Pad as underlying encryption scheme (<strong class="userinput"><code>"AES-128-CBC"</code></strong>, <strong class="userinput"><code>"AES-192-CBC"</code></strong>, and <strong class="userinput"><code>"AES-256-CBC"</code></strong>)</p></li></ul></div></dd><dt><span class="term">PKCS #12 password-based encryption</span></dt><dd><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>SHA-1 and 128-bit RC4 (<strong class="userinput"><code>"PKCS #12 V2 PBE With SHA-1 And 128 Bit RC4"</code></strong> or <strong class="userinput"><code>"RC4"</code></strong>)</p></li><li class="listitem"><p>SHA-1 and 40-bit RC4 (<strong class="userinput"><code>"PKCS #12 V2 PBE With SHA-1 And 40 Bit RC4"</code></strong>) (used by default for certificate encryption in non-FIPS mode)</p></li><li class="listitem"><p>SHA-1 and 3-key triple-DES (<strong class="userinput"><code>"PKCS #12 V2 PBE With SHA-1 And 3KEY Triple DES-CBC"</code></strong> or <strong class="userinput"><code>"DES-EDE3-CBC"</code></strong>)</p></li><li class="listitem"><p>SHA-1 and 128-bit RC2 (<strong class="userinput"><code>"PKCS #12 V2 PBE With SHA-1 And 128 Bit RC2 CBC"</code></strong> or <strong class="userinput"><code>"RC2-CBC"</code></strong>)</p></li><li class="listitem"><p>SHA-1 and 40-bit RC2 (<strong class="userinput"><code>"PKCS #12 V2 PBE With SHA-1 And 40 Bit RC2 CBC"</code></strong>)</p></li></ul></div></dd></dl></div><p>With PKCS #12, the crypto provider may be the soft token module or an external hardware module. If the cryptographic module does not support the requested algorithm, then the next best fit will be selected (usually the default). If no suitable replacement for the desired algorithm can be found, the tool returns the error <span class="emphasis"><em>no security module can perform the requested operation</em></span>.</p></div><div class="refsection"><a name="databases"></a><h2>NSS Database Types</h2><p>NSS originally used BerkeleyDB databases to store security information.
The last versions of these <span class="emphasis"><em>legacy</em></span> databases are:</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> The last versions of these <span class="emphasis"><em>legacy</em></span> databases are:</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
cert8.db for certificates cert8.db for certificates
</p></li><li class="listitem"><p> </p></li><li class="listitem"><p>
@ -68,7 +68,7 @@ BerkleyDB. These new databases provide more accessibility and performance:</p><d
Using the SQLite databases must be manually specified by using the <span class="command"><strong>sql:</strong></span> prefix with the given security directory. For example:</p><pre class="programlisting"># pk12util -i /tmp/cert-files/users.p12 -d sql:/home/my/sharednssdb</pre><p>To set the shared database type as the default type for the tools, set the <code class="envar">NSS_DEFAULT_DB_TYPE</code> environment variable to <code class="envar">sql</code>:</p><pre class="programlisting">export NSS_DEFAULT_DB_TYPE="sql"</pre><p>This line can be set added to the <code class="filename">~/.bashrc</code> file to make the change permanent.</p><p>Most applications do not use the shared database by default, but they can be configured to use them. For example, this how-to article covers how to configure Firefox and Thunderbird to use the new shared NSS databases:</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> Using the SQLite databases must be manually specified by using the <span class="command"><strong>sql:</strong></span> prefix with the given security directory. For example:</p><pre class="programlisting"># pk12util -i /tmp/cert-files/users.p12 -d sql:/home/my/sharednssdb</pre><p>To set the shared database type as the default type for the tools, set the <code class="envar">NSS_DEFAULT_DB_TYPE</code> environment variable to <code class="envar">sql</code>:</p><pre class="programlisting">export NSS_DEFAULT_DB_TYPE="sql"</pre><p>This line can be set added to the <code class="filename">~/.bashrc</code> file to make the change permanent.</p><p>Most applications do not use the shared database by default, but they can be configured to use them. For example, this how-to article covers how to configure Firefox and Thunderbird to use the new shared NSS databases:</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
https://wiki.mozilla.org/NSS_Shared_DB_Howto</p></li></ul></div><p>For an engineering draft on the changes in the shared NSS databases, see the NSS project wiki:</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> https://wiki.mozilla.org/NSS_Shared_DB_Howto</p></li></ul></div><p>For an engineering draft on the changes in the shared NSS databases, see the NSS project wiki:</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
https://wiki.mozilla.org/NSS_Shared_DB https://wiki.mozilla.org/NSS_Shared_DB
</p></li></ul></div></div><div class="refsection"><a name="seealso"></a><h2>See Also</h2><p>certutil (1)</p><p>modutil (1)</p><p>The NSS wiki has information on the new database design and how to configure applications to use it.</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> </p></li></ul></div></div><div class="refsection"><a name="compatibility"></a><h2>Compatibility Notes</h2><p>The exporting behavior of <span class="command"><strong>pk12util</strong></span> has changed over time, while importing files exported with older versions of NSS is still supported.</p><p>Until the 3.30 release, <span class="command"><strong>pk12util</strong></span> used the UTF-16 encoding for the PKCS #5 password-based encryption schemes, while the recommendation is to encode passwords in UTF-8 if the used encryption scheme is defined outside of the PKCS #12 standard.</p><p>Until the 3.31 release, even when <strong class="userinput"><code>"AES-128-CBC"</code></strong> or <strong class="userinput"><code>"AES-192-CBC"</code></strong> is given from the command line, <span class="command"><strong>pk12util</strong></span> always used 256-bit AES as the underlying encryption scheme.</p><p>For historical reasons, <span class="command"><strong>pk12util</strong></span> accepts password-based encryption schemes not listed in this document. However, those schemes are not officially supported and may have issues in interoperability with other tools.</p></div><div class="refsection"><a name="seealso"></a><h2>See Also</h2><p>certutil (1)</p><p>modutil (1)</p><p>The NSS wiki has information on the new database design and how to configure applications to use it.</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
https://wiki.mozilla.org/NSS_Shared_DB_Howto</p></li><li class="listitem"><p> https://wiki.mozilla.org/NSS_Shared_DB_Howto</p></li><li class="listitem"><p>
https://wiki.mozilla.org/NSS_Shared_DB https://wiki.mozilla.org/NSS_Shared_DB
</p></li></ul></div></div><div class="refsection"><a name="resources"></a><h2>Additional Resources</h2><p>For information about NSS and other tools related to NSS (like JSS), check out the NSS project wiki at <a class="ulink" href="http://www.mozilla.org/projects/security/pki/nss/" target="_top">http://www.mozilla.org/projects/security/pki/nss/</a>. The NSS site relates directly to NSS code changes and releases.</p><p>Mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto</p><p>IRC: Freenode at #dogtag-pki</p></div><div class="refsection"><a name="authors"></a><h2>Authors</h2><p>The NSS tools were written and maintained by developers with Netscape, Red Hat, Sun, Oracle, Mozilla, and Google.</p><p> </p></li></ul></div></div><div class="refsection"><a name="resources"></a><h2>Additional Resources</h2><p>For information about NSS and other tools related to NSS (like JSS), check out the NSS project wiki at <a class="ulink" href="http://www.mozilla.org/projects/security/pki/nss/" target="_top">http://www.mozilla.org/projects/security/pki/nss/</a>. The NSS site relates directly to NSS code changes and releases.</p><p>Mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto</p><p>IRC: Freenode at #dogtag-pki</p></div><div class="refsection"><a name="authors"></a><h2>Authors</h2><p>The NSS tools were written and maintained by developers with Netscape, Red Hat, Sun, Oracle, Mozilla, and Google.</p><p>

View file

@ -1,13 +1,13 @@
'\" t '\" t
.\" Title: CERTUTIL .\" Title: CERTUTIL
.\" Author: [see the "Authors" section] .\" Author: [see the "Authors" section]
.\" Generator: DocBook XSL Stylesheets v1.78.1 <http://docbook.sf.net/> .\" Generator: DocBook XSL Stylesheets vsnapshot <http://docbook.sf.net/>
.\" Date: 8 September 2016 .\" Date: 27 October 2017
.\" Manual: NSS Security Tools .\" Manual: NSS Security Tools
.\" Source: nss-tools .\" Source: nss-tools
.\" Language: English .\" Language: English
.\" .\"
.TH "CERTUTIL" "1" "8 September 2016" "nss-tools" "NSS Security Tools" .TH "CERTUTIL" "1" "27 October 2017" "nss-tools" "NSS Security Tools"
.\" ----------------------------------------------------------------- .\" -----------------------------------------------------------------
.\" * Define some portability stuff .\" * Define some portability stuff
.\" ----------------------------------------------------------------- .\" -----------------------------------------------------------------
@ -371,7 +371,7 @@ Read an alternate PQG value from the specified file when generating DSA key pair
\fBcertutil\fR \fBcertutil\fR
generates its own PQG value\&. PQG files are created with a separate DSA utility\&. generates its own PQG value\&. PQG files are created with a separate DSA utility\&.
.sp .sp
Elliptic curve name is one of the ones from nistp256, nistp384, nistp521, curve25519. Elliptic curve name is one of the ones from nistp256, nistp384, nistp521, curve25519\&.
.sp .sp
If a token is available that supports more curves, the foolowing curves are supported as well: sect163k1, nistk163, sect163r1, sect163r2, nistb163, sect193r1, sect193r2, sect233k1, nistk233, sect233r1, nistb233, sect239k1, sect283k1, nistk283, sect283r1, nistb283, sect409k1, nistk409, sect409r1, nistb409, sect571k1, nistk571, sect571r1, nistb571, secp160k1, secp160r1, secp160r2, secp192k1, secp192r1, nistp192, secp224k1, secp224r1, nistp224, secp256k1, secp256r1, secp384r1, secp521r1, prime192v1, prime192v2, prime192v3, prime239v1, prime239v2, prime239v3, c2pnb163v1, c2pnb163v2, c2pnb163v3, c2pnb176v1, c2tnb191v1, c2tnb191v2, c2tnb191v3, c2pnb208w1, c2tnb239v1, c2tnb239v2, c2tnb239v3, c2pnb272w1, c2pnb304w1, c2tnb359w1, c2pnb368w1, c2tnb431r1, secp112r1, secp112r2, secp128r1, secp128r2, sect113r1, sect113r2, sect131r1, sect131r2 If a token is available that supports more curves, the foolowing curves are supported as well: sect163k1, nistk163, sect163r1, sect163r2, nistb163, sect193r1, sect193r2, sect233k1, nistk233, sect233r1, nistb233, sect239k1, sect283k1, nistk283, sect283r1, nistb283, sect409k1, nistk409, sect409r1, nistb409, sect571k1, nistk571, sect571r1, nistb571, secp160k1, secp160r1, secp160r2, secp192k1, secp192r1, nistp192, secp224k1, secp224r1, nistp224, secp256k1, secp256r1, secp384r1, secp521r1, prime192v1, prime192v2, prime192v3, prime239v1, prime239v2, prime239v3, c2pnb163v1, c2pnb163v2, c2pnb163v3, c2pnb176v1, c2tnb191v1, c2tnb191v2, c2tnb191v3, c2pnb208w1, c2tnb239v1, c2tnb239v2, c2tnb239v3, c2pnb272w1, c2pnb304w1, c2tnb359w1, c2pnb368w1, c2tnb431r1, secp112r1, secp112r2, secp128r1, secp128r2, sect113r1, sect113r2, sect131r1, sect131r2
.RE .RE
@ -609,6 +609,24 @@ to generate the signature for a certificate being created or added to a database
Set an alternate exponent value to use in generating a new RSA public key for the database, instead of the default value of 65537\&. The available alternate values are 3 and 17\&. Set an alternate exponent value to use in generating a new RSA public key for the database, instead of the default value of 65537\&. The available alternate values are 3 and 17\&.
.RE .RE
.PP .PP
\-\-pss
.RS 4
Restrict the generated certificate (with the
\fB\-S\fR
option) or certificate request (with the
\fB\-R\fR
option) to be used with the RSA\-PSS signature scheme\&. This only works when the private key of the certificate or certificate request is RSA\&.
.RE
.PP
\-\-pss\-sign
.RS 4
Sign the generated certificate with the RSA\-PSS signature scheme (with the
\fB\-C\fR
or
\fB\-S\fR
option)\&. This only works when the private key of the signer\*(Aqs certificate is RSA\&. If the signer\*(Aqs certificate is restricted to RSA\-PSS, it is not necessary to specify this option\&.
.RE
.PP
\-z noise\-file \-z noise\-file
.RS 4 .RS 4
Read a seed value from the specified file to generate a new private and public key pair\&. This argument makes it possible to use hardware\-generated seed values or manually create a value from the keyboard\&. The minimum file size is 20 bytes\&. Read a seed value from the specified file to generate a new private and public key pair\&. This argument makes it possible to use hardware\-generated seed values or manually create a value from the keyboard\&. The minimum file size is 20 bytes\&.
@ -1512,7 +1530,8 @@ There are ways to narrow the keys listed in the search results:
.IP \(bu 2.3 .IP \(bu 2.3
.\} .\}
To return a specific key, use the To return a specific key, use the
\fB\-n\fR\fIname\fR \fB\-n\fR
\fIname\fR
argument with the name of the key\&. argument with the name of the key\&.
.RE .RE
.sp .sp
@ -1525,7 +1544,8 @@ argument with the name of the key\&.
.IP \(bu 2.3 .IP \(bu 2.3
.\} .\}
If there are multiple security devices loaded, then the If there are multiple security devices loaded, then the
\fB\-h\fR\fItokenname\fR \fB\-h\fR
\fItokenname\fR
argument can search a specific token or all tokens\&. argument can search a specific token or all tokens\&.
.RE .RE
.sp .sp
@ -1538,7 +1558,8 @@ argument can search a specific token or all tokens\&.
.IP \(bu 2.3 .IP \(bu 2.3
.\} .\}
If there are multiple key types available, then the If there are multiple key types available, then the
\fB\-k\fR\fIkey\-type\fR \fB\-k\fR
\fIkey\-type\fR
argument can search a specific type of key, like RSA, DSA, or ECC\&. argument can search a specific type of key, like RSA, DSA, or ECC\&.
.RE .RE
.PP .PP

View file

@ -1,13 +1,13 @@
'\" t '\" t
.\" Title: PK12UTIL .\" Title: PK12UTIL
.\" Author: [see the "Authors" section] .\" Author: [see the "Authors" section]
.\" Generator: DocBook XSL Stylesheets v1.78.1 <http://docbook.sf.net/> .\" Generator: DocBook XSL Stylesheets vsnapshot <http://docbook.sf.net/>
.\" Date: 5 June 2014 .\" Date: 27 October 2017
.\" Manual: NSS Security Tools .\" Manual: NSS Security Tools
.\" Source: nss-tools .\" Source: nss-tools
.\" Language: English .\" Language: English
.\" .\"
.TH "PK12UTIL" "1" "5 June 2014" "nss-tools" "NSS Security Tools" .TH "PK12UTIL" "1" "27 October 2017" "nss-tools" "NSS Security Tools"
.\" ----------------------------------------------------------------- .\" -----------------------------------------------------------------
.\" * Define some portability stuff .\" * Define some portability stuff
.\" ----------------------------------------------------------------- .\" -----------------------------------------------------------------
@ -68,7 +68,7 @@ Specify the key encryption algorithm\&.
.PP .PP
\-C certCipher \-C certCipher
.RS 4 .RS 4
Specify the key cert (overall package) encryption algorithm\&. Specify the certiticate encryption algorithm\&.
.RE .RE
.PP .PP
\-d [sql:]directory \-d [sql:]directory
@ -559,17 +559,17 @@ Certificate Friendly Name: Thawte Freemail Member\*(Aqs Thawte Consulting (Pt
.\} .\}
.SH "PASSWORD ENCRYPTION" .SH "PASSWORD ENCRYPTION"
.PP .PP
PKCS#12 provides for not only the protection of the private keys but also the certificate and meta\-data associated with the keys\&. Password\-based encryption is used to protect private keys on export to a PKCS#12 file and, optionally, the entire package\&. If no algorithm is specified, the tool defaults to using PKCS #12 provides for not only the protection of the private keys but also the certificate and meta\-data associated with the keys\&. Password\-based encryption is used to protect private keys on export to a PKCS #12 file and, optionally, the associated certificates\&. If no algorithm is specified, the tool defaults to using PKCS #12 SHA\-1 and 3\-key triple DES for private key encryption\&. When not in FIPS mode, PKCS #12 SHA\-1 and 40\-bit RC4 is used for certificate encryption\&. When in FIPS mode, there is no certificate encryption\&. If certificate encryption is not wanted, specify
\fBPKCS12 V2 PBE with SHA1 and 3KEY Triple DES\-cbc\fR \fB"NONE"\fR
for private key encryption\&. as the argument of the
\fBPKCS12 V2 PBE with SHA1 and 40 Bit RC4\fR \fB\-C\fR
is the default for the overall package encryption when not in FIPS mode\&. When in FIPS mode, there is no package encryption\&. option\&.
.PP .PP
The private key is always protected with strong encryption by default\&. The private key is always protected with strong encryption by default\&.
.PP .PP
Several types of ciphers are supported\&. Several types of ciphers are supported\&.
.PP .PP
Symmetric CBC ciphers for PKCS#5 V2 PKCS #5 password\-based encryption
.RS 4 .RS 4
.sp .sp
.RS 4 .RS 4
@ -580,110 +580,13 @@ Symmetric CBC ciphers for PKCS#5 V2
.sp -1 .sp -1
.IP \(bu 2.3 .IP \(bu 2.3
.\} .\}
DES\-CBC PBES2 with AES\-CBC\-Pad as underlying encryption scheme (\fB"AES\-128\-CBC"\fR,
.RE \fB"AES\-192\-CBC"\fR, and
.sp \fB"AES\-256\-CBC"\fR)
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
RC2\-CBC
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
RC5\-CBCPad
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
DES\-EDE3\-CBC (the default for key encryption)
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
AES\-128\-CBC
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
AES\-192\-CBC
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
AES\-256\-CBC
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
CAMELLIA\-128\-CBC
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
CAMELLIA\-192\-CBC
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
CAMELLIA\-256\-CBC
.RE .RE
.RE .RE
.PP .PP
PKCS#12 PBE ciphers PKCS #12 password\-based encryption
.RS 4 .RS 4
.sp .sp
.RS 4 .RS 4
@ -694,7 +597,9 @@ PKCS#12 PBE ciphers
.sp -1 .sp -1
.IP \(bu 2.3 .IP \(bu 2.3
.\} .\}
PKCS #12 PBE with Sha1 and 128 Bit RC4 SHA\-1 and 128\-bit RC4 (\fB"PKCS #12 V2 PBE With SHA\-1 And 128 Bit RC4"\fR
or
\fB"RC4"\fR)
.RE .RE
.sp .sp
.RS 4 .RS 4
@ -705,7 +610,7 @@ PKCS #12 PBE with Sha1 and 128 Bit RC4
.sp -1 .sp -1
.IP \(bu 2.3 .IP \(bu 2.3
.\} .\}
PKCS #12 PBE with Sha1 and 40 Bit RC4 SHA\-1 and 40\-bit RC4 (\fB"PKCS #12 V2 PBE With SHA\-1 And 40 Bit RC4"\fR) (used by default for certificate encryption in non\-FIPS mode)
.RE .RE
.sp .sp
.RS 4 .RS 4
@ -716,7 +621,9 @@ PKCS #12 PBE with Sha1 and 40 Bit RC4
.sp -1 .sp -1
.IP \(bu 2.3 .IP \(bu 2.3
.\} .\}
PKCS #12 PBE with Sha1 and Triple DES CBC SHA\-1 and 3\-key triple\-DES (\fB"PKCS #12 V2 PBE With SHA\-1 And 3KEY Triple DES\-CBC"\fR
or
\fB"DES\-EDE3\-CBC"\fR)
.RE .RE
.sp .sp
.RS 4 .RS 4
@ -727,7 +634,9 @@ PKCS #12 PBE with Sha1 and Triple DES CBC
.sp -1 .sp -1
.IP \(bu 2.3 .IP \(bu 2.3
.\} .\}
PKCS #12 PBE with Sha1 and 128 Bit RC2 CBC SHA\-1 and 128\-bit RC2 (\fB"PKCS #12 V2 PBE With SHA\-1 And 128 Bit RC2 CBC"\fR
or
\fB"RC2\-CBC"\fR)
.RE .RE
.sp .sp
.RS 4 .RS 4
@ -738,110 +647,7 @@ PKCS #12 PBE with Sha1 and 128 Bit RC2 CBC
.sp -1 .sp -1
.IP \(bu 2.3 .IP \(bu 2.3
.\} .\}
PKCS #12 PBE with Sha1 and 40 Bit RC2 CBC SHA\-1 and 40\-bit RC2 (\fB"PKCS #12 V2 PBE With SHA\-1 And 40 Bit RC2 CBC"\fR)
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
PKCS12 V2 PBE with SHA1 and 128 Bit RC4
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
PKCS12 V2 PBE with SHA1 and 40 Bit RC4 (the default for non\-FIPS mode)
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
PKCS12 V2 PBE with SHA1 and 3KEY Triple DES\-cbc
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
PKCS12 V2 PBE with SHA1 and 2KEY Triple DES\-cbc
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
PKCS12 V2 PBE with SHA1 and 128 Bit RC2 CBC
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
PKCS12 V2 PBE with SHA1 and 40 Bit RC2 CBC
.RE
.RE
.PP
PKCS#5 PBE ciphers
.RS 4
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
PKCS #5 Password Based Encryption with MD2 and DES CBC
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
PKCS #5 Password Based Encryption with MD5 and DES CBC
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
PKCS #5 Password Based Encryption with SHA1 and DES CBC
.RE .RE
.RE .RE
.PP .PP
@ -987,6 +793,27 @@ For an engineering draft on the changes in the shared NSS databases, see the NSS
.\} .\}
https://wiki\&.mozilla\&.org/NSS_Shared_DB https://wiki\&.mozilla\&.org/NSS_Shared_DB
.RE .RE
.SH "COMPATIBILITY NOTES"
.PP
The exporting behavior of
\fBpk12util\fR
has changed over time, while importing files exported with older versions of NSS is still supported\&.
.PP
Until the 3\&.30 release,
\fBpk12util\fR
used the UTF\-16 encoding for the PKCS #5 password\-based encryption schemes, while the recommendation is to encode passwords in UTF\-8 if the used encryption scheme is defined outside of the PKCS #12 standard\&.
.PP
Until the 3\&.31 release, even when
\fB"AES\-128\-CBC"\fR
or
\fB"AES\-192\-CBC"\fR
is given from the command line,
\fBpk12util\fR
always used 256\-bit AES as the underlying encryption scheme\&.
.PP
For historical reasons,
\fBpk12util\fR
accepts password\-based encryption schemes not listed in this document\&. However, those schemes are not officially supported and may have issues in interoperability with other tools\&.
.SH "SEE ALSO" .SH "SEE ALSO"
.PP .PP
certutil (1) certutil (1)

View file

@ -78,7 +78,7 @@
<varlistentry> <varlistentry>
<term>-C certCipher</term> <term>-C certCipher</term>
<listitem><para>Specify the key cert (overall package) encryption algorithm.</para></listitem> <listitem><para>Specify the certiticate encryption algorithm.</para></listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry>
@ -304,53 +304,29 @@ Certificate Friendly Name: Thawte Freemail Member's Thawte Consulting (Pty) L
<refsection id="encryption"> <refsection id="encryption">
<title>Password Encryption</title> <title>Password Encryption</title>
<para>PKCS#12 provides for not only the protection of the private keys but also the certificate and meta-data associated with the keys. Password-based encryption is used to protect private keys on export to a PKCS#12 file and, optionally, the entire package. If no algorithm is specified, the tool defaults to using <command>PKCS12 V2 PBE with SHA1 and 3KEY Triple DES-cbc</command> for private key encryption. <command>PKCS12 V2 PBE with SHA1 and 40 Bit RC4</command> is the default for the overall package encryption when not in FIPS mode. When in FIPS mode, there is no package encryption.</para> <para>PKCS #12 provides for not only the protection of the private keys but also the certificate and meta-data associated with the keys. Password-based encryption is used to protect private keys on export to a PKCS #12 file and, optionally, the associated certificates. If no algorithm is specified, the tool defaults to using PKCS #12 SHA-1 and 3-key triple DES for private key encryption. When not in FIPS mode, PKCS #12 SHA-1 and 40-bit RC4 is used for certificate encryption. When in FIPS mode, there is no certificate encryption. If certificate encryption is not wanted, specify <userinput>"NONE"</userinput> as the argument of the <option>-C</option> option.</para>
<para>The private key is always protected with strong encryption by default.</para> <para>The private key is always protected with strong encryption by default.</para>
<para>Several types of ciphers are supported.</para> <para>Several types of ciphers are supported.</para>
<variablelist> <variablelist>
<varlistentry> <varlistentry>
<term>Symmetric CBC ciphers for PKCS#5 V2</term> <term>PKCS #5 password-based encryption</term>
<listitem> <listitem>
<itemizedlist> <itemizedlist>
<listitem><para>DES-CBC</para></listitem> <listitem><para>PBES2 with AES-CBC-Pad as underlying encryption scheme (<userinput>"AES-128-CBC"</userinput>, <userinput>"AES-192-CBC"</userinput>, and <userinput>"AES-256-CBC"</userinput>)</para></listitem>
<listitem><para>RC2-CBC</para></listitem>
<listitem><para>RC5-CBCPad</para></listitem>
<listitem><para>DES-EDE3-CBC (the default for key encryption)</para></listitem>
<listitem><para>AES-128-CBC</para></listitem>
<listitem><para>AES-192-CBC</para></listitem>
<listitem><para>AES-256-CBC</para></listitem>
<listitem><para>CAMELLIA-128-CBC</para></listitem>
<listitem><para>CAMELLIA-192-CBC</para></listitem>
<listitem><para>CAMELLIA-256-CBC</para></listitem>
</itemizedlist> </itemizedlist>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry>
<term>PKCS#12 PBE ciphers</term> <term>PKCS #12 password-based encryption</term>
<listitem> <listitem>
<itemizedlist> <itemizedlist>
<listitem><para>PKCS #12 PBE with Sha1 and 128 Bit RC4</para></listitem> <listitem><para>SHA-1 and 128-bit RC4 (<userinput>"PKCS #12 V2 PBE With SHA-1 And 128 Bit RC4"</userinput> or <userinput>"RC4"</userinput>)</para></listitem>
<listitem><para>PKCS #12 PBE with Sha1 and 40 Bit RC4</para></listitem> <listitem><para>SHA-1 and 40-bit RC4 (<userinput>"PKCS #12 V2 PBE With SHA-1 And 40 Bit RC4"</userinput>) (used by default for certificate encryption in non-FIPS mode)</para></listitem>
<listitem><para>PKCS #12 PBE with Sha1 and Triple DES CBC</para></listitem> <listitem><para>SHA-1 and 3-key triple-DES (<userinput>"PKCS #12 V2 PBE With SHA-1 And 3KEY Triple DES-CBC"</userinput> or <userinput>"DES-EDE3-CBC"</userinput>)</para></listitem>
<listitem><para>PKCS #12 PBE with Sha1 and 128 Bit RC2 CBC</para></listitem> <listitem><para>SHA-1 and 128-bit RC2 (<userinput>"PKCS #12 V2 PBE With SHA-1 And 128 Bit RC2 CBC"</userinput> or <userinput>"RC2-CBC"</userinput>)</para></listitem>
<listitem><para>PKCS #12 PBE with Sha1 and 40 Bit RC2 CBC</para></listitem> <listitem><para>SHA-1 and 40-bit RC2 (<userinput>"PKCS #12 V2 PBE With SHA-1 And 40 Bit RC2 CBC"</userinput>)</para></listitem>
<listitem><para>PKCS12 V2 PBE with SHA1 and 128 Bit RC4</para></listitem>
<listitem><para>PKCS12 V2 PBE with SHA1 and 40 Bit RC4 (the default for non-FIPS mode)</para></listitem>
<listitem><para>PKCS12 V2 PBE with SHA1 and 3KEY Triple DES-cbc</para></listitem>
<listitem><para>PKCS12 V2 PBE with SHA1 and 2KEY Triple DES-cbc</para></listitem>
<listitem><para>PKCS12 V2 PBE with SHA1 and 128 Bit RC2 CBC</para></listitem>
<listitem><para>PKCS12 V2 PBE with SHA1 and 40 Bit RC2 CBC</para></listitem>
</itemizedlist>
</listitem>
</varlistentry>
<varlistentry><term>PKCS#5 PBE ciphers</term>
<listitem>
<itemizedlist>
<listitem><para>PKCS #5 Password Based Encryption with MD2 and DES CBC</para></listitem>
<listitem><para>PKCS #5 Password Based Encryption with MD5 and DES CBC</para></listitem>
<listitem><para>PKCS #5 Password Based Encryption with SHA1 and DES CBC</para></listitem>
</itemizedlist> </itemizedlist>
</listitem> </listitem>
</varlistentry> </varlistentry>
@ -432,6 +408,14 @@ Using the SQLite databases must be manually specified by using the <command>sql:
</itemizedlist> </itemizedlist>
</refsection> </refsection>
<refsection id="compatibility">
<title>Compatibility Notes</title>
<para>The exporting behavior of <command>pk12util</command> has changed over time, while importing files exported with older versions of NSS is still supported.</para>
<para>Until the 3.30 release, <command>pk12util</command> used the UTF-16 encoding for the PKCS #5 password-based encryption schemes, while the recommendation is to encode passwords in UTF-8 if the used encryption scheme is defined outside of the PKCS #12 standard.</para>
<para>Until the 3.31 release, even when <userinput>"AES-128-CBC"</userinput> or <userinput>"AES-192-CBC"</userinput> is given from the command line, <command>pk12util</command> always used 256-bit AES as the underlying encryption scheme.</para>
<para>For historical reasons, <command>pk12util</command> accepts password-based encryption schemes not listed in this document. However, those schemes are not officially supported and may have issues in interoperability with other tools.</para>
</refsection>
<refsection id="seealso"> <refsection id="seealso">
<title>See Also</title> <title>See Also</title>
<para>certutil (1)</para> <para>certutil (1)</para>

View file

@ -1,6 +1,6 @@
#!/bin/sh #!/bin/sh
LIBFUZZER_REVISION=56bd1d43451cca4b6a11d3be316bb77ab159b09d LIBFUZZER_REVISION=6937e68f927b6aefe526fcb9db8953f497e6e74d
d=$(dirname $0) d=$(dirname $0)
$d/git-copy.sh https://chromium.googlesource.com/chromium/llvm-project/llvm/lib/Fuzzer $LIBFUZZER_REVISION $d/../libFuzzer $d/git-copy.sh https://chromium.googlesource.com/chromium/llvm-project/llvm/lib/Fuzzer $LIBFUZZER_REVISION $d/../libFuzzer

View file

@ -7,18 +7,18 @@ if [ $# -lt 3 ]; then
exit 2 exit 2
fi fi
REPO=$1 REPO="$1"
COMMIT=$2 COMMIT="$2"
DIR=$3 DIR="$3"
echo "Copy '$COMMIT' from '$REPO' to '$DIR'" echo "Copy '$COMMIT' from '$REPO' to '$DIR'"
if [ -f $DIR/.git-copy ]; then if [ -f "$DIR"/.git-copy ]; then
CURRENT=$(cat $DIR/.git-copy) CURRENT=$(cat "$DIR"/.git-copy)
if [ $(echo -n $COMMIT | wc -c) != "40" ]; then if [ $(echo -n "$COMMIT" | wc -c) != "40" ]; then
# On the off chance that $COMMIT is a remote head. # On the off chance that $COMMIT is a remote head.
ACTUAL=$(git ls-remote $REPO $COMMIT | cut -c 1-40 -) ACTUAL=$(git ls-remote "$REPO" "$COMMIT" | cut -c 1-40 -)
else else
ACTUAL=$COMMIT ACTUAL="$COMMIT"
fi fi
if [ "$CURRENT" = "$ACTUAL" ]; then if [ "$CURRENT" = "$ACTUAL" ]; then
echo "Up to date." echo "Up to date."
@ -26,8 +26,9 @@ if [ -f $DIR/.git-copy ]; then
fi fi
fi fi
git init -q $DIR rm -rf "$DIR"
git -C $DIR fetch -q --depth=1 $REPO $COMMIT:git-copy-tmp git init -q "$DIR"
git -C $DIR reset --hard git-copy-tmp git -C "$DIR" fetch -q --depth=1 "$REPO" "$COMMIT":git-copy-tmp
git -C $DIR rev-parse --verify HEAD > $DIR/.git-copy git -C "$DIR" reset --hard git-copy-tmp
rm -rf $DIR/.git git -C "$DIR" rev-parse --verify HEAD > "$DIR"/.git-copy
rm -rf "$DIR"/.git

View file

@ -19,6 +19,15 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
auto modulus = get_modulus(data, size, ctx); auto modulus = get_modulus(data, size, ctx);
// Compare with OpenSSL exp mod // Compare with OpenSSL exp mod
m1 = &std::get<1>(modulus); m1 = &std::get<1>(modulus);
// The exponent b (B) can get really big. Make it smaller if necessary.
if (MP_USED(&b) > 100) {
size_t shift = (MP_USED(&b) - 100) * MP_DIGIT_BIT;
mp_div_2d(&b, shift, &b, nullptr);
BN_rshift(B, B, shift);
}
check_equal(A, &a, max_size);
check_equal(B, &b, max_size);
check_equal(std::get<0>(modulus), m1, 3 * max_size);
assert(mp_exptmod(&a, &b, m1, &c) == MP_OKAY); assert(mp_exptmod(&a, &b, m1, &c) == MP_OKAY);
(void)BN_mod_exp(C, A, B, std::get<0>(modulus), ctx); (void)BN_mod_exp(C, A, B, std::get<0>(modulus), ctx);
check_equal(C, &c, 2 * max_size); check_equal(C, &c, 2 * max_size);

View file

@ -12,6 +12,12 @@ char *to_char(const uint8_t *x) {
return reinterpret_cast<char *>(const_cast<unsigned char *>(x)); return reinterpret_cast<char *>(const_cast<unsigned char *>(x));
} }
void print_bn(std::string label, BIGNUM *x) {
char *xc = BN_bn2hex(x);
std::cout << label << ": " << std::hex << xc << std::endl;
OPENSSL_free(xc);
}
// Check that the two numbers are equal. // Check that the two numbers are equal.
void check_equal(BIGNUM *b, mp_int *m, size_t max_size) { void check_equal(BIGNUM *b, mp_int *m, size_t max_size) {
char *bnBc = BN_bn2hex(b); char *bnBc = BN_bn2hex(b);

View file

@ -23,6 +23,7 @@ void parse_input(const uint8_t *data, size_t size, BIGNUM *A, BIGNUM *B,
void parse_input(const uint8_t *data, size_t size, BIGNUM *A, mp_int *a); void parse_input(const uint8_t *data, size_t size, BIGNUM *A, mp_int *a);
std::tuple<BIGNUM *, mp_int> get_modulus(const uint8_t *data, size_t size, std::tuple<BIGNUM *, mp_int> get_modulus(const uint8_t *data, size_t size,
BN_CTX *ctx); BN_CTX *ctx);
void print_bn(std::string label, BIGNUM *x);
// Initialise MPI and BN variables // Initialise MPI and BN variables
// XXX: Also silence unused variable warnings for R. // XXX: Also silence unused variable warnings for R.

View file

@ -2,11 +2,14 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <algorithm>
#include "shared.h" #include "shared.h"
#include "tls_parser.h" #include "tls_parser.h"
#include "ssl.h" #include "ssl.h"
extern "C" {
#include "sslimpl.h" #include "sslimpl.h"
}
using namespace nss_test; using namespace nss_test;
@ -39,7 +42,9 @@ class Record {
void truncate(size_t length) { void truncate(size_t length) {
assert(length >= 5 + gExtraHeaderBytes); assert(length >= 5 + gExtraHeaderBytes);
uint8_t *dest = const_cast<uint8_t *>(data_); uint8_t *dest = const_cast<uint8_t *>(data_);
(void)ssl_EncodeUintX(length - 5 - gExtraHeaderBytes, 2, &dest[3]); size_t l = length - (5 + gExtraHeaderBytes);
dest[3] = (l >> 8) & 0xff;
dest[4] = l & 0xff;
memmove(dest + length, data_ + size_, remaining_); memmove(dest + length, data_ + size_, remaining_);
} }
@ -222,8 +227,8 @@ size_t FragmentRecord(uint8_t *data, size_t size, size_t max_size,
} }
// Pick a record to fragment at random. // Pick a record to fragment at random.
std::uniform_int_distribution<size_t> dist(0, records.size() - 1); std::uniform_int_distribution<size_t> rand_record(0, records.size() - 1);
auto &rec = records.at(dist(rng)); auto &rec = records.at(rand_record(rng));
uint8_t *rdata = const_cast<uint8_t *>(rec->data()); uint8_t *rdata = const_cast<uint8_t *>(rec->data());
size_t length = rec->size(); size_t length = rec->size();
size_t content_length = length - 5; size_t content_length = length - 5;
@ -233,17 +238,21 @@ size_t FragmentRecord(uint8_t *data, size_t size, size_t max_size,
} }
// Assign a new length to the first fragment. // Assign a new length to the first fragment.
size_t new_length = content_length / 2; std::uniform_int_distribution<size_t> rand_size(1, content_length - 1);
uint8_t *content = ssl_EncodeUintX(new_length, 2, &rdata[3]); size_t first_length = rand_size(rng);
size_t second_length = content_length - first_length;
rdata[3] = (first_length >> 8) & 0xff;
rdata[4] = first_length & 0xff;
uint8_t *second_record = rdata + 5 + first_length;
// Make room for one more header. // Make room for the header of the second record.
memmove(content + new_length + 5, content + new_length, memmove(second_record + 5, second_record,
rec->remaining() + content_length - new_length); rec->remaining() + content_length - first_length);
// Write second header. // Write second header.
memcpy(content + new_length, rdata, 3); memcpy(second_record, rdata, 3);
(void)ssl_EncodeUintX(content_length - new_length, 2, second_record[3] = (second_length >> 8) & 0xff;
&content[new_length + 3]); second_record[4] = second_length & 0xff;
return size + 5; return size + 5;
} }

Some files were not shown because too many files have changed in this diff Show more