Compare commits

..

No commits in common. "33b4630f4bef0c44616b062e7013f1da0d4cfc9c" and "6118ae718ea974821bef43142d9b2afdfb67c9e3" have entirely different histories.

31 changed files with 1575 additions and 1008 deletions

6
.gitattributes vendored Normal file
View File

@ -0,0 +1,6 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# These are explicitly windows files and should use crlf
*.bat text eol=crlf

25
build.gradle Normal file
View File

@ -0,0 +1,25 @@
/**
Declares dependencies for Jdnssec-tools
**/
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
jar {
baseName = 'jdnssec-tools'
version = '0.17.1'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile fileTree(dir: 'lib', include: '*.jar')
}

View File

@ -1,2 +1,3 @@
#build.compiler=jikes
#build.compiler=modern
build.deprecation=true
build.debug=true

View File

@ -44,11 +44,11 @@
<javac srcdir="${build.src}"
destdir="${build.dest}"
classpathref="project.classpath"
deprecation="${build.deprecation}"
deprecation="true"
includeantruntime="false"
includes="com/verisignlabs/dnssec/"
debug="${build.debug}"
release="17" />
source="17"
target="17" />
</target>
<target name="sectools-jar" depends="usage,sectools">
@ -154,11 +154,13 @@
<target name="dist" depends="sectools-dist">
<echo message="do not forget to tag the release:" />
<echo message=" svn-tag ${version}" />
</target>
<target name="usage">
<echo message=" " />
<echo message="jdnssec-tools v. ${version} Build System" />
<echo message="SECTOOLS v. ${version} Build System" />
<echo message="--------------------------------" />
<echo message="Available Targets:" />
<echo message=" compile (default) - compiles the source code, creates jar" />

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
gradlew vendored Executable file
View File

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

BIN
lib/commons-cli-1.5.0.jar Normal file

Binary file not shown.

Binary file not shown.

BIN
lib/eddsa-0.3.0.jar Normal file

Binary file not shown.

View File

@ -56,7 +56,7 @@ public class DSTool extends CLBase {
public dsType createType = dsType.DS;
public String outputfile = null;
public String keyname = null;
public int digestId = DNSSEC.Digest.SHA256;
public int digestId = DNSSEC.Digest.SHA1;
public CLIState() {
super("jdnssec-dstool [..options..] keyfile");
@ -71,8 +71,7 @@ public class DSTool extends CLBase {
protected void setupOptions(Options opts) {
opts.addOption(Option.builder("D").longOpt("dlv").desc("Generate a DLV record instead.").build());
opts.addOption(Option.builder("C").longOpt("cds").desc("Generate a CDS record instead").build());
opts.addOption(
Option.builder("d").hasArg().argName("id").longOpt("digest").desc("The digest algorithm to use").build());
opts.addOption(Option.builder("d").hasArg().argName("id").longOpt("digest").desc("The digest algorithm to use").build());
opts.addOption(Option.builder("f").hasArg().argName("file").longOpt("output").desc("output to file").build());
}

View File

@ -44,8 +44,8 @@ public class KeyGen extends CLBase {
* state.
*/
protected static class CLIState extends CLIStateBase {
public int algorithm = 13;
public int keylength = 2048;
public int algorithm = 8;
public int keylength = 1024;
public boolean useLargeE = true;
public String outputfile = null;
public File keydir = null;
@ -77,10 +77,10 @@ public class KeyGen extends CLBase {
String[] algStrings = DnsKeyAlgorithm.getInstance().supportedAlgMnemonics();
String algStringSet = String.join(" | ", algStrings);
opts.addOption(Option.builder("a").hasArg().argName("algorithm")
.desc(algStringSet + " | alias, ECDSAP256SHA256 is default.").build());
.desc(algStringSet + " | alias, RSASHA256 is default.").build());
opts.addOption(Option.builder("b").hasArg().argName("size").desc(
"key size, in bits (default 2048). RSA: [512..4096], DSA: [512..1024], DH: [128..4096], ECDSA: ignored, EdDSA: ignored")
"key size, in bits (default 1024). RSA: [512..4096], DSA: [512..1024], DH: [128..4096], ECDSA: ignored, EdDSA: ignored")
.build());
opts.addOption(Option.builder("f").hasArg().argName("file").longOpt("output-file")
.desc("base filename from the public/private key files").build());

View File

@ -84,13 +84,13 @@ public class KeyInfoTool extends CLBase {
+ " (" + dnskey.getAlgorithm() + ")");
System.out.println("ID: " + dnskey.getFootprint());
System.out.println("KeyFileBase: " + BINDKeyUtils.keyFileBase(key));
DnsKeyAlgorithm.BaseAlgorithm basetype = dnskeyalg.baseType(dnskey.getAlgorithm());
int basetype = dnskeyalg.baseType(dnskey.getAlgorithm());
if (basetype == DnsKeyAlgorithm.BaseAlgorithm.RSA) {
if (basetype == DnsKeyAlgorithm.RSA) {
RSAPublicKey pub = (RSAPublicKey) key.getPublic();
System.out.println("RSA Public Exponent: " + pub.getPublicExponent());
System.out.println("RSA Modulus: " + pub.getModulus());
} else if (basetype == DnsKeyAlgorithm.BaseAlgorithm.DSA) {
} else if (basetype == DnsKeyAlgorithm.DSA) {
DSAPublicKey pub = (DSAPublicKey) key.getPublic();
System.out.println("DSA base (G): " + pub.getParams().getG());
System.out.println("DSA prime (P): " + pub.getParams().getP());

View File

@ -75,14 +75,10 @@ public class SignKeyset extends CLBase {
opts.addOption("a", "verify", false, "verify generated signatures>");
// Argument options
opts.addOption(Option.builder("D").hasArg().argName("dir").longOpt("key-directory")
.desc("directory where key files are found (default '.').").build());
opts.addOption(Option.builder("s").hasArg().argName("time/offset").longOpt("start-time")
.desc("signature starting time (default is now - 1 hour)").build());
opts.addOption(Option.builder("e").hasArg().argName("time/offset").longOpt("expire-time")
.desc("signature expiration time (default is start-time + 30 days)").build());
opts.addOption(
Option.builder("f").hasArg().argName("outfile").desc("file the signed keyset is written to").build());
opts.addOption(Option.builder("D").hasArg().argName("dir").longOpt("key-directory").desc("directory where key files are found (default '.').").build());
opts.addOption(Option.builder("s").hasArg().argName("time/offset").longOpt("start-time").desc("signature starting time (default is now - 1 hour)").build());
opts.addOption(Option.builder("e").hasArg().argName("time/offset").longOpt("expire-time").desc("signature expiration time (default is start-time + 30 days)").build());
opts.addOption(Option.builder("f").hasArg().argName("outfile").desc("file the signed keyset is written to").build());
}
@Override
@ -134,8 +130,10 @@ public class SignKeyset extends CLBase {
/**
* Verify the generated signatures.
*
* @param records a list of {@link org.xbill.DNS.Record}s.
* @param keypairs a list of keypairs used the sign the zone.
* @param records
* a list of {@link org.xbill.DNS.Record}s.
* @param keypairs
* a list of keypairs used the sign the zone.
* @return true if all of the signatures validated.
*/
private static boolean verifySigs(List<Record> records,
@ -171,12 +169,15 @@ public class SignKeyset extends CLBase {
/**
* Load the key pairs from the key files.
*
* @param keyfiles a string array containing the base names or paths of the
* keys to be loaded.
* @param startIndex the starting index of keyfiles string array to use. This
* allows us to use the straight command line argument
* array.
* @param inDirectory the directory to look in (may be null).
* @param keyfiles
* a string array containing the base names or paths of the
* keys
* to be loaded.
* @param startIndex
* the starting index of keyfiles string array to use. This
* allows us to use the straight command line argument array.
* @param inDirectory
* the directory to look in (may be null).
* @return a list of keypair objects.
*/
private static List<DnsKeyPair> getKeys(String[] keyfiles, int startIndex,

View File

@ -137,8 +137,10 @@ public class SignRRset extends CLBase {
/**
* Verify the generated signatures.
*
* @param records a list of {@link org.xbill.DNS.Record}s.
* @param keypairs a list of keypairs used the sign the zone.
* @param records
* a list of {@link org.xbill.DNS.Record}s.
* @param keypairs
* a list of keypairs used the sign the zone.
* @return true if all of the signatures validated.
*/
private static boolean verifySigs(List<Record> records, List<DnsKeyPair> keypairs) {
@ -174,12 +176,15 @@ public class SignRRset extends CLBase {
/**
* Load the key pairs from the key files.
*
* @param keyfiles a string array containing the base names or paths of the
* keys to be loaded.
* @param startIndex the starting index of keyfiles string array to use. This
* allows us to use the straight command line argument
* array.
* @param inDirectory the directory to look in (may be null).
* @param keyfiles
* a string array containing the base names or paths of the
* keys
* to be loaded.
* @param startIndex
* the starting index of keyfiles string array to use. This
* allows us to use the straight command line argument array.
* @param inDirectory
* the directory to look in (may be null).
* @return a list of keypair objects.
*/
private static List<DnsKeyPair> getKeys(String[] keyfiles, int startIndex,

View File

@ -79,8 +79,6 @@ public class SignZone extends CLBase {
public long nsec3paramttl = -1;
public boolean verboseSigning = false;
private static final Random rand = new Random();
public CLIState() {
super("jdnssec-signzone [..options..] zone_file [key_file ...]");
}
@ -200,8 +198,9 @@ public class SignZone extends CLBase {
if ((optstr = cli.getOptionValue('R')) != null) {
int length = parseInt(optstr, 0);
if (length > 0 && length <= 255) {
Random random = new Random();
salt = new byte[length];
rand.nextBytes(salt);
random.nextBytes(salt);
}
}
@ -242,8 +241,8 @@ public class SignZone extends CLBase {
/**
* Load a list of DNS names from a file.
*
* @param nameListFile the path of a file containing a bare list of DNS
* names.
* @param nameListFile
* the path of a file containing a bare list of DNS names.
* @return a list of {@link org.xbill.DNS.Name} objects.
*/
private static List<Name> getNameList(File nameListFile) throws IOException {
@ -255,6 +254,9 @@ public class SignZone extends CLBase {
try {
Name n = Name.fromString(line);
// force the name to be absolute.
// FIXME: we should probably get some fancy logic here to
// detect if the name needs the origin appended, or just the
// root.
if (!n.isAbsolute())
n = Name.concatenate(n, Name.root);
@ -272,12 +274,14 @@ public class SignZone extends CLBase {
/**
* Verify the generated signatures.
*
* @param records a list of {@link org.xbill.DNS.Record}s.
* @param keypairs a list of keypairs used the sign the zone.
* @param records
* a list of {@link org.xbill.DNS.Record}s.
* @param keypairs
* a list of keypairs used the sign the zone.
* @return true if all of the signatures validated.
*/
private static boolean verifyZoneSigs(List<Record> records,
List<DnsKeyPair> keypairs, List<DnsKeyPair> kskpairs) {
List<DnsKeyPair> keypairs) {
boolean secure = true;
DnsSecVerifier verifier = new DnsSecVerifier();
@ -285,9 +289,7 @@ public class SignZone extends CLBase {
for (DnsKeyPair pair : keypairs) {
verifier.addTrustedKey(pair);
}
for (DnsKeyPair pair : kskpairs) {
verifier.addTrustedKey(pair);
}
verifier.setVerifyAllSigs(true);
List<RRset> rrsets = SignUtils.assembleIntoRRsets(records);
@ -301,7 +303,6 @@ public class SignZone extends CLBase {
boolean result = verifier.verify(rrset);
if (!result) {
System.err.println("Signatures did not verify for RRset: " + rrset);
staticLog.fine("Signatures did not verify for RRset: " + rrset);
secure = false;
}
@ -313,12 +314,17 @@ public class SignZone extends CLBase {
/**
* Load the key pairs from the key files.
*
* @param keyfiles a string array containing the base names or paths of the
* keys to be loaded.
* @param startIndex the starting index of keyfiles string array to use. This
* allows us to use the straight command line argument
* array.
* @param inDirectory the directory to look in (may be null).
* @param keyfiles
* a string array containing the base names or paths of the
* keys to
* be loaded.
* @param startIndex
* the starting index of keyfiles string array to use. This
* allows
* us
* to use the straight command line argument array.
* @param inDirectory
* the directory to look in (may be null).
* @return a list of keypair objects.
*/
private static List<DnsKeyPair> getKeys(String[] keyfiles, int startIndex,
@ -412,12 +418,19 @@ public class SignZone extends CLBase {
/**
* Load keysets (which contain delegation point security info).
*
* @param inDirectory the directory to look for the keyset files (may be null,
* in which case it defaults to looking in the current
* working directory).
* @param zonename the name of the zone we are signing, so we can ignore
* keysets that do not belong in the zone.
* @return a list of {@link org.xbill.DNS.Record}s found in the keyset files.
* @param inDirectory
* the directory to look for the keyset files (may be null,
* in
* which
* case it defaults to looking in the current working
* directory).
* @param zonename
* the name of the zone we are signing, so we can ignore
* keysets
* that
* do not belong in the zone.
* @return a list of {@link org.xbill.DNS.Record}s found in the keyset
* files.
*/
private static List<Record> getKeysets(File inDirectory, Name zonename)
throws IOException {
@ -450,9 +463,13 @@ public class SignZone extends CLBase {
/**
* Determine if the given keypairs can be used to sign the zone.
*
* @param zonename the zone origin.
* @param keypairs a list of {@link DnsKeyPair} objects that will be used to
* sign the zone.
* @param zonename
* the zone origin.
* @param keypairs
* a list of {@link DnsKeyPair} objects that will be used to
* sign
* the
* zone.
* @return true if the keypairs valid.
*/
private static boolean keyPairsValidForZone(Name zonename, List<DnsKeyPair> keypairs) {
@ -486,70 +503,55 @@ public class SignZone extends CLBase {
return;
}
// Load the key pairs. Note that getKeys() always returns array.
// Load the key pairs.
List<DnsKeyPair> keypairs = getKeys(state.keyFiles, 0, state.keyDirectory);
List<DnsKeyPair> kskpairs = getKeys(state.kskFiles, 0, state.keyDirectory);
// If we didn't get any keys on the command line, look at the zone apex for
// any public keys.
if (keypairs.isEmpty()) {
if (keypairs == null && kskpairs == null) {
List<Record> dnskeys = ZoneUtils.findRRs(records, zonename, Type.DNSKEY);
keypairs = getKeys(dnskeys, state.keyDirectory);
}
// If we *still* don't have any key pairs, look for keys the key directory
// that match
if (keypairs.isEmpty()) {
if (keypairs == null && kskpairs == null) {
keypairs = findZoneKeys(state.keyDirectory, zonename);
}
// If we don't have any KSKs, but we do have more than one zone
// signing key (presumably), presume that the zone signing keys
// are just not differentiated and try to figure out which keys
// are actually KSKs by looking at the SEP flag.
if (kskpairs.isEmpty() && !keypairs.isEmpty()) {
// are actually ksks by looking at the SEP flag.
if ((kskpairs == null || kskpairs.isEmpty()) && keypairs != null
&& keypairs.size() > 1) {
for (Iterator<DnsKeyPair> i = keypairs.iterator(); i.hasNext();) {
DnsKeyPair pair = i.next();
DNSKEYRecord kr = pair.getDNSKEYRecord();
if ((kr.getFlags() & DNSKEYRecord.Flags.SEP_KEY) != 0) {
if (kskpairs == null)
kskpairs = new ArrayList<>();
kskpairs.add(pair);
i.remove();
}
}
}
// If we have zero keypairs at all, we are stuck.
if (keypairs.isEmpty() && kskpairs.isEmpty()) {
// If there are no ZSKs defined at this point (yet there are KSKs
// provided), all KSKs will be treated as ZSKs, as well.
if (keypairs == null || keypairs.isEmpty()) {
keypairs = kskpairs;
}
// If there *still* aren't any ZSKs defined, bail.
if (keypairs == null || keypairs.isEmpty()) {
System.err.println("No zone signing keys could be determined.");
state.usage();
return;
}
// If we only have one type of key (all ZSKs or all KSKs), then these are
// "CSKs" -- Combined signing keys, so assign one set to the other.
if (keypairs.isEmpty()) {
keypairs = kskpairs;
} else if (kskpairs.isEmpty()) {
kskpairs = keypairs;
}
// Output what keys we are using for what
if (keypairs == kskpairs) {
System.out.println("CSKs: ");
for (DnsKeyPair kp : keypairs) {
System.out.println(" - " + kp);
}
} else {
System.out.println("KSKs: ");
for (DnsKeyPair kp : kskpairs) {
System.out.println(" - " + kp);
}
System.out.println("ZSKs: ");
for (DnsKeyPair kp : keypairs) {
System.out.println(" - " + kp);
}
}
// default the output file, if not set.
if (state.outputfile == null && !state.zonefile.equals("-")) {
if (zonename.isAbsolute()) {
@ -569,12 +571,12 @@ public class SignZone extends CLBase {
// We force the signing keys to be in the zone by just appending
// them to the zone here. Currently JCEDnsSecSigner.signZone
// removes duplicate records.
if (!kskpairs.isEmpty()) {
if (kskpairs != null) {
for (DnsKeyPair pair : kskpairs) {
records.add(pair.getDNSKEYRecord());
}
}
if (!keypairs.isEmpty()) {
if (keypairs != null) {
for (DnsKeyPair pair : keypairs) {
records.add(pair.getDNSKEYRecord());
}
@ -606,11 +608,15 @@ public class SignZone extends CLBase {
// write out the signed zone
ZoneUtils.writeZoneFile(signedRecords, state.outputfile);
System.out.println("zone signing complete");
if (state.verifySigs) {
// FIXME: ugh.
if (kskpairs != null) {
keypairs.addAll(kskpairs);
}
log.fine("verifying generated signatures");
boolean res = verifyZoneSigs(signedRecords, keypairs, kskpairs);
boolean res = verifyZoneSigs(signedRecords, keypairs);
if (res) {
System.out.println("Generated signatures verified");
@ -618,6 +624,7 @@ public class SignZone extends CLBase {
System.out.println("Generated signatures did not verify.");
}
}
}
public static void main(String[] args) {

View File

@ -100,6 +100,7 @@ public class ZoneFormat extends CLBase {
private static void formatZone(List<Record> zone) {
for (Record r : zone) {
System.out.println(r.toString());
}

View File

@ -46,8 +46,7 @@ import org.xbill.DNS.utils.base64;
*/
public class BINDKeyUtils {
private BINDKeyUtils() {
}
private BINDKeyUtils() { }
/**
* Calculate the BIND9 key file base name (i.e., without the ".key" or
@ -61,7 +60,8 @@ public class BINDKeyUtils {
/** Reads in the DNSKEYRecord from the public key file */
private static DNSKEYRecord loadPublicKeyFile(File publicKeyFile)
throws IOException {
try (Master m = new Master(publicKeyFile.getAbsolutePath(), null, 600)) {
Master m = new Master(publicKeyFile.getAbsolutePath(), null, 600);
Record r;
DNSKEYRecord result = null;
@ -73,7 +73,6 @@ public class BINDKeyUtils {
return result;
}
}
/** Reads in the private key verbatim from the private key file */
private static String loadPrivateKeyFile(File privateKeyFile)
@ -107,12 +106,17 @@ public class BINDKeyUtils {
* Given the information necessary to construct the path to a BIND9 generated
* key pair, load the key pair.
*
* @param signer the DNS name of the key.
* @param algorithm the DNSSEC algorithm of the key.
* @param keyid the DNSSEC key footprint.
* @param inDirectory the directory to look for the files (may be null).
* @param signer
* the DNS name of the key.
* @param algorithm
* the DNSSEC algorithm of the key.
* @param keyid
* the DNSSEC key footprint.
* @param inDirectory
* the directory to look for the files (may be null).
* @return the loaded key pair.
* @throws IOException if there was a problem reading the BIND9 files.
* @throws IOException
* if there was a problem reading the BIND9 files.
*/
public static DnsKeyPair loadKeyPair(Name signer, int algorithm, int keyid,
File inDirectory) throws IOException {
@ -124,12 +128,16 @@ public class BINDKeyUtils {
/**
* Given a base path to a BIND9 key pair, load the key pair.
*
* @param keyFileBasePath the base filename (or real filename for either the
* public or private key) of the key.
* @param inDirectory the directory to look in, if the keyFileBasePath is
* @param keyFileBasePath
* the base filename (or real filename for either the
* public or
* private key) of the key.
* @param inDirectory
* the directory to look in, if the keyFileBasePath is
* relative.
* @return the loaded key pair.
* @throws IOException if there was a problem reading the files
* @throws IOException
* if there was a problem reading the files
*/
public static DnsKeyPair loadKeyPair(String keyFileBasePath, File inDirectory)
throws IOException {
@ -154,12 +162,15 @@ public class BINDKeyUtils {
* Given a base path to a BIND9 key pair, load the public part (only) of the
* key pair
*
* @param keyFileBasePath the base or real path to the public part of a key
* @param keyFileBasePath
* the base or real path to the public part of a key
* pair.
* @param inDirectory the directory to look in if the path is relative
* (may be null).
* @param inDirectory
* the directory to look in if the path is relative (may
* be null).
* @return a {@link DnsKeyPair} containing just the public key information.
* @throws IOException if there was a problem reading the public key file.
* @throws IOException
* if there was a problem reading the public key file.
*/
public static DnsKeyPair loadKey(String keyFileBasePath, File inDirectory)
throws IOException {
@ -179,11 +190,15 @@ public class BINDKeyUtils {
* "keyset-[signer]." where [signer] is the DNS owner name of the key. The
* keyset may be signed, but doesn't have to be.
*
* @param keysetFileName the name of the keyset file.
* @param inDirectory the directory to look in if the path is relative (may
* be null, defaults to the current working directory).
* @param keysetFileName
* the name of the keyset file.
* @param inDirectory
* the directory to look in if the path is relative (may
* be null,
* defaults to the current working directory).
* @return a RRset contain the KEY records and any associated SIG records.
* @throws IOException if there was a problem reading the keyset file.
* @throws IOException
* if there was a problem reading the keyset file.
*/
public static RRset loadKeySet(String keysetFileName, File inDirectory)
throws IOException {
@ -203,8 +218,8 @@ public class BINDKeyUtils {
/**
* Calculate the key file base for this key pair.
*
* @param pair the {@link DnsKeyPair} to work from. It only needs a public
* key.
* @param pair
* the {@link DnsKeyPair} to work from. It only needs a public key.
* @return the base name of the key files.
*/
public static String keyFileBase(DnsKeyPair pair) {
@ -244,7 +259,8 @@ public class BINDKeyUtils {
* Given a the contents of a BIND9 private key file, convert it into a native
* {@link java.security.PrivateKey} object.
*
* @param privateKeyString the contents of a BIND9 key file in string form.
* @param privateKeyString
* the contents of a BIND9 key file in string form.
* @return a {@link java.security.PrivateKey}
*/
public static PrivateKey convertPrivateKeyString(String privateKeyString) {
@ -267,8 +283,10 @@ public class BINDKeyUtils {
* Given a native private key, convert it into a BIND9 private key file
* format.
*
* @param priv the private key to convert.
* @param pub the private key's corresponding public key. Some algorithms
* @param priv
* the private key to convert.
* @param pub
* the private key's corresponding public key. Some algorithms
* require information from both.
* @return a string containing the contents of a BIND9 private key file.
*/
@ -309,11 +327,16 @@ public class BINDKeyUtils {
/**
* This routine will write out the BIND9 dnssec-* tool compatible files.
*
* @param baseFileName use this base file name. If null, the standard BIND9
* base file name will be computed.
* @param pair the keypair in question.
* @param inDirectory the directory to write to (may be null).
* @throws IOException if there is a problem writing the files.
* @param baseFileName
* use this base file name. If null, the standard BIND9 base
* file
* name will be computed.
* @param pair
* the keypair in question.
* @param inDirectory
* the directory to write to (may be null).
* @throws IOException
* if there is a problem writing the files.
*/
public static void writeKeyFiles(String baseFileName, DnsKeyPair pair,
File inDirectory) throws IOException {
@ -346,8 +369,10 @@ public class BINDKeyUtils {
* This routine will write out the BIND9 dnssec-* tool compatible files to the
* standard file names.
*
* @param pair the key pair in question.
* @param inDirectory the directory to write to (may be null).
* @param pair
* the key pair in question.
* @param inDirectory
* the directory to write to (may be null).
*/
public static void writeKeyFiles(DnsKeyPair pair, File inDirectory)
throws IOException {

View File

@ -34,6 +34,7 @@ import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.spec.ECFieldFp;
@ -42,7 +43,6 @@ import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.EllipticCurve;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.NamedParameterSpec;
import java.security.spec.RSAKeyGenParameterSpec;
import java.util.Arrays;
import java.util.HashMap;
@ -51,6 +51,12 @@ import java.util.logging.Logger;
import org.xbill.DNS.DNSSEC;
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
// for now, we need to import the EdDSA parameter spec classes
// because they have no generic form in java.security.spec.*
// sadly, this will currently fail if you don't have the lib.
import net.i2p.crypto.eddsa.spec.EdDSAParameterSpec;
/**
* This class handles translating DNS signing algorithm identifiers into various
* usable java implementations.
@ -66,24 +72,21 @@ public class DnsKeyAlgorithm {
// Our base algorithm numbers. This is a normalization of the DNSSEC
// algorithms (which are really signature algorithms). Thus RSASHA1,
// RSASHA256, etc. all boil down to 'RSA' here. Similary, ECDSAP256SHA256 and
// ECDSAP384SHA384 both become 'ECDSA'.
public enum BaseAlgorithm {
UNKNOWN,
RSA,
DH,
DSA,
ECC_GOST,
ECDSA,
EDDSA;
}
// RSASHA256, etc. all boil down to 'RSA' here.
public static final int UNKNOWN = -1;
public static final int RSA = 1;
public static final int DH = 2;
public static final int DSA = 3;
public static final int ECC_GOST = 4;
public static final int ECDSA = 5;
public static final int EDDSA = 6;
private static class AlgEntry {
public int dnssecAlgorithm;
public String sigName;
public BaseAlgorithm baseType;
public int baseType;
public AlgEntry(int algorithm, String sigName, BaseAlgorithm baseType) {
public AlgEntry(int algorithm, String sigName, int baseType) {
this.dnssecAlgorithm = algorithm;
this.sigName = sigName;
this.baseType = baseType;
@ -93,20 +96,18 @@ public class DnsKeyAlgorithm {
private static class ECAlgEntry extends AlgEntry {
public ECParameterSpec ecSpec;
public ECAlgEntry(int algorithm, String sigName, BaseAlgorithm baseType, ECParameterSpec spec) {
public ECAlgEntry(int algorithm, String sigName, int baseType, ECParameterSpec spec) {
super(algorithm, sigName, baseType);
this.ecSpec = spec;
}
}
private static class EdAlgEntry extends AlgEntry {
public String curveName;
public NamedParameterSpec paramSpec;
public EdDSAParameterSpec edSpec;
public EdAlgEntry(int algorithm, String sigName, BaseAlgorithm baseType, String curveName) {
public EdAlgEntry(int algorithm, String sigName, int baseType, EdDSAParameterSpec spec) {
super(algorithm, sigName, baseType);
this.curveName = curveName;
this.paramSpec = new NamedParameterSpec(curveName);
this.edSpec = spec;
}
}
@ -142,15 +143,24 @@ public class DnsKeyAlgorithm {
private static DnsKeyAlgorithm mInstance = null;
public DnsKeyAlgorithm() {
// Attempt to add the bouncycastle provider. This is so we can use this
// provider if it is available, but not require the user to add it as one of
// the java.security providers.
// Attempt to add the bouncycastle provider.
// This is so we can use this provider if it is available, but not require
// the user to add it as one of the java.security providers.
try {
Class<?> bcProviderClass = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
Provider bcProvider = (Provider) bcProviderClass.getDeclaredConstructor().newInstance();
Security.addProvider(bcProvider);
} catch (ReflectiveOperationException e) {
log.fine("Unable to load BC provider");
log.info("Unable to load BC provider");
}
// Attempt to add the EdDSA-Java provider.
try {
Class<?> eddsaProviderClass = Class.forName("net.i2p.crypto.eddsa.EdDSASecurityProvider");
Provider eddsaProvider = (Provider) eddsaProviderClass.getDeclaredConstructor().newInstance();
Security.addProvider(eddsaProvider);
} catch (ReflectiveOperationException e) {
log.warning("Unable to load EdDSA provider");
}
initialize();
@ -162,16 +172,16 @@ public class DnsKeyAlgorithm {
mIdToMnemonicMap = new HashMap<>();
// Load the standard DNSSEC algorithms.
addAlgorithm(DNSSEC.Algorithm.RSAMD5, "MD5withRSA", BaseAlgorithm.RSA);
addAlgorithm(DNSSEC.Algorithm.RSAMD5, "MD5withRSA", RSA);
addMnemonic("RSAMD5", DNSSEC.Algorithm.RSAMD5);
addAlgorithm(DNSSEC.Algorithm.DH, "", BaseAlgorithm.DH);
addAlgorithm(DNSSEC.Algorithm.DH, "", DH);
addMnemonic("DH", DNSSEC.Algorithm.DH);
addAlgorithm(DNSSEC.Algorithm.DSA, "SHA1withDSA", BaseAlgorithm.DSA);
addAlgorithm(DNSSEC.Algorithm.DSA, "SHA1withDSA", DSA);
addMnemonic("DSA", DNSSEC.Algorithm.DSA);
addAlgorithm(DNSSEC.Algorithm.RSASHA1, "SHA1withRSA", BaseAlgorithm.RSA);
addAlgorithm(DNSSEC.Algorithm.RSASHA1, "SHA1withRSA", RSA);
addMnemonic("RSASHA1", DNSSEC.Algorithm.RSASHA1);
addMnemonic("RSA", DNSSEC.Algorithm.RSASHA1);
@ -183,49 +193,42 @@ public class DnsKeyAlgorithm {
addMnemonic("NSEC3RSASHA1", DNSSEC.Algorithm.RSA_NSEC3_SHA1);
// Algorithms added by RFC 5702.
addAlgorithm(DNSSEC.Algorithm.RSASHA256, "SHA256withRSA", BaseAlgorithm.RSA);
addAlgorithm(DNSSEC.Algorithm.RSASHA256, "SHA256withRSA", RSA);
addMnemonic("RSASHA256", DNSSEC.Algorithm.RSASHA256);
addAlgorithm(DNSSEC.Algorithm.RSASHA512, "SHA512withRSA", BaseAlgorithm.RSA);
addAlgorithm(DNSSEC.Algorithm.RSASHA512, "SHA512withRSA", RSA);
addMnemonic("RSASHA512", DNSSEC.Algorithm.RSASHA512);
// ECC-GOST is not supported by Java 1.8's Sun crypto provider. The
// bouncycastle.org provider, however, does support it.
// GostR3410-2001-CryptoPro-A is the named curve in the BC provider, but we
// will get the parameters directly.
addAlgorithm(DNSSEC.Algorithm.ECC_GOST, "GOST3411withECGOST3410", BaseAlgorithm.ECC_GOST, null);
addAlgorithm(DNSSEC.Algorithm.ECC_GOST, "GOST3411withECGOST3410", ECC_GOST, null);
addMnemonic("ECCGOST", DNSSEC.Algorithm.ECC_GOST);
addMnemonic("ECC-GOST", DNSSEC.Algorithm.ECC_GOST);
addAlgorithm(DNSSEC.Algorithm.ECDSAP256SHA256, "SHA256withECDSA", BaseAlgorithm.ECDSA, "secp256r1");
addAlgorithm(DNSSEC.Algorithm.ECDSAP256SHA256, "SHA256withECDSA", ECDSA, "secp256r1");
addMnemonic("ECDSAP256SHA256", DNSSEC.Algorithm.ECDSAP256SHA256);
addMnemonic("ECDSA-P256", DNSSEC.Algorithm.ECDSAP256SHA256);
addAlgorithm(DNSSEC.Algorithm.ECDSAP384SHA384, "SHA384withECDSA", BaseAlgorithm.ECDSA, "secp384r1");
addAlgorithm(DNSSEC.Algorithm.ECDSAP384SHA384, "SHA384withECDSA", ECDSA, "secp384r1");
addMnemonic("ECDSAP384SHA384", DNSSEC.Algorithm.ECDSAP384SHA384);
addMnemonic("ECDSA-P384", DNSSEC.Algorithm.ECDSAP384SHA384);
// For the Edwards Curve implementations, we just initialize Signature and
// KeyPairGenerator with the curve name.
addAlgorithm(15, "Ed25519", BaseAlgorithm.EDDSA, "Ed25519");
// EdDSA is not supported by either the Java 1.8 Sun crypto
// provider or bouncycastle. It is added by the Ed25519-Java
// library. We don't have a corresponding constant in
// org.xbill.DNS.DNSSEC yet, though.
addAlgorithm(15, "NONEwithEdDSA", EDDSA, "Ed25519");
addMnemonic("ED25519", 15);
addAlgorithm(16, "Ed448", BaseAlgorithm.EDDSA, "Ed448");
addMnemonic(("ED448"), 16);
}
private void addAlgorithm(int algorithm, String sigName, BaseAlgorithm baseType) {
private void addAlgorithm(int algorithm, String sigName, int baseType) {
mAlgorithmMap.put(algorithm, new AlgEntry(algorithm, sigName, baseType));
}
/**
* Add a ECDSA (algorithms 13/14) to the set, looking up the curve names.
*
* @param algorithm the DNSSEC algorithm number.
* @param sigName the name of the signature scheme.
* @param curveName the official name of the elliptic curve in our crypto
* library (SunEC).
*/
private void addECDSAAlgorithm(int algorithm, String sigName, String curveName) {
private void addAlgorithm(int algorithm, String sigName, int baseType, String curveName) {
if (baseType == ECDSA) {
ECParameterSpec ecSpec = ECSpecFromAlgorithm(algorithm);
if (ecSpec == null)
ecSpec = ECSpecFromName(curveName);
@ -241,56 +244,28 @@ public class DnsKeyAlgorithm {
// If not, do not add the algorithm.
return;
}
ECAlgEntry entry = new ECAlgEntry(algorithm, sigName, BaseAlgorithm.ECDSA, ecSpec);
ECAlgEntry entry = new ECAlgEntry(algorithm, sigName, baseType, ecSpec);
mAlgorithmMap.put(algorithm, entry);
}
} else if (baseType == EDDSA) {
EdDSAParameterSpec edSpec = EdDSASpecFromName(curveName);
if (edSpec == null)
return;
/**
* Add an EdDSA (Edwards curve algorithms, DNSSEC algorithms 15/16), looking up
* the curve.
*
* @param algorithm the DNSSEC algorithm numer.
* @param sigName the name of the signing scheme. For EdDSA, this is the same
* as the curve.
* @param curveName the name of the curve.
*/
private void addEdDSAAlgorithm(int algorithm, String sigName, String curveName) {
// Check to see if we can get a Signature object for this algorithm.
try {
Signature.getInstance(sigName);
} catch (NoSuchAlgorithmException e) {
// for now, let's find out
log.severe("could not get signature for EdDSA curve" + curveName + ": " + e.getMessage());
log.severe("could not get signature for " + sigName + ": " + e.getMessage());
// If not, do not add the algorithm.
return;
}
EdAlgEntry entry = new EdAlgEntry(algorithm, sigName, BaseAlgorithm.EDDSA, curveName);
EdAlgEntry entry = new EdAlgEntry(algorithm, sigName, baseType, edSpec);
mAlgorithmMap.put(algorithm, entry);
}
/**
* Add an Elliptic Curve algorithm given a signing scheme and curve name.
*
* @param algorithm the DNSSEC algorithm number
* @param sigName the signature scheme (e.g., which crypto hash function are
* we using?)
* @param baseType the base type (either ECDSA or EDDSA).
* @param curveName the name of the curve.
*/
private void addAlgorithm(int algorithm, String sigName, BaseAlgorithm baseType, String curveName) {
if (baseType == BaseAlgorithm.ECDSA) {
addECDSAAlgorithm(algorithm, sigName, curveName);
} else if (baseType == BaseAlgorithm.EDDSA) {
addEdDSAAlgorithm(algorithm, sigName, curveName);
}
}
/**
* Add an alternate mnemonic for an algorithm.
*
* @param m the new mnemonic.
* @param alg the DNSSEC algorithm number.
*/
private void addMnemonic(String m, int alg) {
// Do not add mnemonics for algorithms that ended up not actually being
// supported.
@ -301,19 +276,19 @@ public class DnsKeyAlgorithm {
mIdToMnemonicMap.computeIfAbsent(alg, k -> m);
}
public void addAlias(int alias, String mnemonic, int origAlgorithm) {
public void addAlias(int alias, String mnemonic, int original_algorithm) {
if (mAlgorithmMap.containsKey(alias)) {
log.warning("Unable to alias algorithm " + alias + " because it already exists.");
return;
}
if (!mAlgorithmMap.containsKey(origAlgorithm)) {
if (!mAlgorithmMap.containsKey(original_algorithm)) {
log.warning("Unable to alias algorithm " + alias
+ " to unknown algorithm identifier " + origAlgorithm);
+ " to unknown algorithm identifier " + original_algorithm);
return;
}
mAlgorithmMap.put(alias, mAlgorithmMap.get(origAlgorithm));
mAlgorithmMap.put(alias, mAlgorithmMap.get(original_algorithm));
if (mnemonic != null) {
addMnemonic(mnemonic, alias);
@ -347,8 +322,8 @@ public class DnsKeyAlgorithm {
private ECParameterSpec ECSpecFromName(String stdName) {
try {
AlgorithmParameters ap = AlgorithmParameters.getInstance("EC");
ECGenParameterSpec ecgSpec = new ECGenParameterSpec(stdName);
ap.init(ecgSpec);
ECGenParameterSpec ecg_spec = new ECGenParameterSpec(stdName);
ap.init(ecg_spec);
return ap.getParameterSpec(ECParameterSpec.class);
} catch (NoSuchAlgorithmException e) {
log.info("Elliptic Curve not supported by any crypto provider: " + e.getMessage());
@ -358,6 +333,24 @@ public class DnsKeyAlgorithm {
return null;
}
// Fetch the curve parameters from a named EdDSA curve.
private EdDSAParameterSpec EdDSASpecFromName(String stdName) {
try {
EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName(stdName);
if (spec != null)
return spec;
throw new InvalidParameterSpecException("Edwards Curve " + stdName + " not found.");
}
// catch (NoSuchAlgorithmException e) {
// log.info("Edwards Curve not supported by any crypto provider: " +
// e.getMessage());
// }
catch (InvalidParameterSpecException e) {
log.info("Edwards Curve " + stdName + " not supported");
}
return null;
}
public String[] supportedAlgMnemonics() {
Set<Integer> keyset = mAlgorithmMap.keySet();
Integer[] algs = keyset.toArray(new Integer[keyset.size()]);
@ -395,10 +388,11 @@ public class DnsKeyAlgorithm {
}
/**
* Given one of the ECDSA algorithms (ECDSAP256SHA256, etc.) return the
* elliptic curve parameters.
* Given one of the ECDSA algorithms (ECDSAP256SHA256, etc.) return
* the elliptic curve parameters.
*
* @param algorithm The DNSSEC algorithm number.
* @param algorithm
* The DNSSEC algorithm number.
* @return The calculated JCA ECParameterSpec for that DNSSEC algorithm, or
* null if not a recognized/supported EC algorithm.
*/
@ -408,35 +402,37 @@ public class DnsKeyAlgorithm {
return null;
if (!(entry instanceof ECAlgEntry))
return null;
ECAlgEntry ecEntry = (ECAlgEntry) entry;
ECAlgEntry ec_entry = (ECAlgEntry) entry;
return ecEntry.ecSpec;
return ec_entry.ecSpec;
}
/**
* Given one of the EdDSA algorithms (ED25519 or ED448), return the named
* parameter spec.
* Given one of the EdDSA algorithms (Ed25519, Ed448) return the
* elliptic curve parameters.
*
* @param algorithm The DNSSEC algorithm number.
* @return The NamedParameterSpec for that DNSSEC algorithm, nor null if the
* algorithm wasn't a supported EdDSA algorithm.
* @param algorithm
* The DNSSEC algorithm number.
* @return The stored EdDSAParameterSpec for that algorithm, or
* null if not a recognized/supported EdDSA algorithm.
*/
public NamedParameterSpec getEdwardsCurveSpec(int algorithm) {
public EdDSAParameterSpec getEdwardsCurveParams(int algorithm) {
AlgEntry entry = getEntry(algorithm);
if (entry == null)
return null;
if (!(entry instanceof EdAlgEntry))
return null;
EdAlgEntry edEntry = (EdAlgEntry) entry;
EdAlgEntry ed_entry = (EdAlgEntry) entry;
return edEntry.paramSpec;
return ed_entry.edSpec;
}
/**
* Translate a possible algorithm alias back to the original DNSSEC algorithm
* number
*
* @param algorithm a DNSSEC algorithm that may be an alias.
* @param algorithm
* a DNSSEC algorithm that may be an alias.
* @return -1 if the algorithm isn't recognised, the orignal algorithm number
* if it is.
*/
@ -462,7 +458,8 @@ public class DnsKeyAlgorithm {
* Given an algorithm mnemonic, convert the mnemonic to a DNSSEC algorithm
* number.
*
* @param s The mnemonic string. This is case-insensitive.
* @param s
* The mnemonic string. This is case-insensitive.
* @return -1 if the mnemonic isn't recognized or supported, the algorithm
* number if it is.
*/
@ -476,7 +473,8 @@ public class DnsKeyAlgorithm {
/**
* Given a DNSSEC algorithm number, return the "preferred" mnemonic.
*
* @param algorithm A DNSSEC algorithm number.
* @param algorithm
* A DNSSEC algorithm number.
* @return The preferred mnemonic string, or null if not supported or
* recognized.
*/
@ -484,15 +482,15 @@ public class DnsKeyAlgorithm {
return mIdToMnemonicMap.get(algorithm);
}
public BaseAlgorithm baseType(int algorithm) {
public int baseType(int algorithm) {
AlgEntry entry = getEntry(algorithm);
if (entry != null)
return entry.baseType;
return BaseAlgorithm.UNKNOWN;
return UNKNOWN;
}
public boolean isDSA(int algorithm) {
return (baseType(algorithm) == BaseAlgorithm.DSA);
return (baseType(algorithm) == DSA);
}
public KeyPair generateKeyPair(int algorithm, int keysize, boolean useLargeExp)
@ -504,14 +502,14 @@ public class DnsKeyAlgorithm {
mRSAKeyGenerator = KeyPairGenerator.getInstance("RSA");
}
RSAKeyGenParameterSpec rsaSpec;
RSAKeyGenParameterSpec rsa_spec;
if (useLargeExp) {
rsaSpec = new RSAKeyGenParameterSpec(keysize, RSAKeyGenParameterSpec.F4);
rsa_spec = new RSAKeyGenParameterSpec(keysize, RSAKeyGenParameterSpec.F4);
} else {
rsaSpec = new RSAKeyGenParameterSpec(keysize, RSAKeyGenParameterSpec.F0);
rsa_spec = new RSAKeyGenParameterSpec(keysize, RSAKeyGenParameterSpec.F0);
}
try {
mRSAKeyGenerator.initialize(rsaSpec);
mRSAKeyGenerator.initialize(rsa_spec);
} catch (InvalidAlgorithmParameterException e) {
// Fold the InvalidAlgorithmParameterException into our existing
// thrown exception. Ugly, but requires less code change.
@ -562,9 +560,18 @@ public class DnsKeyAlgorithm {
break;
}
case EDDSA: {
EdAlgEntry entry = (EdAlgEntry) getEntry(algorithm);
mEdKeyGenerator = KeyPairGenerator.getInstance(entry.curveName);
if (mEdKeyGenerator == null) {
mEdKeyGenerator = KeyPairGenerator.getInstance("EdDSA");
}
EdDSAParameterSpec edSpec = getEdwardsCurveParams(algorithm);
try {
mEdKeyGenerator.initialize(edSpec, new SecureRandom());
} catch (InvalidAlgorithmParameterException e) {
// Fold the InvalidAlgorithmParameterException into our existing
// thrown exception. Ugly, but requires less code change.
throw new NoSuchAlgorithmException("invalid key parameter spec");
}
pair = mEdKeyGenerator.generateKeyPair();
break;
}

View File

@ -30,16 +30,12 @@ import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.EdECPrivateKey;
import java.security.interfaces.EdECPublicKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPrivateKeySpec;
import java.security.spec.EdECPrivateKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.NamedParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.StringTokenizer;
@ -54,6 +50,13 @@ import org.xbill.DNS.DNSSEC.DNSSECException;
import org.xbill.DNS.Name;
import org.xbill.DNS.utils.base64;
import net.i2p.crypto.eddsa.EdDSAPrivateKey;
// For now, just import the native EdDSA classes
import net.i2p.crypto.eddsa.EdDSAPublicKey;
import net.i2p.crypto.eddsa.spec.EdDSAParameterSpec;
import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec;
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec;
/**
* This class handles conversions between JCA key formats and DNSSEC and BIND9
* key formats.
@ -84,6 +87,7 @@ public class DnsKeyConverter {
// Because we have arbitrarily aliased algorithms, we need to possibly
// translate the aliased algorithm back to the actual algorithm.
int originalAlgorithm = mAlgorithms.originalAlgorithm(pKeyRecord.getAlgorithm());
if (originalAlgorithm <= 0)
@ -97,6 +101,16 @@ public class DnsKeyConverter {
pKeyRecord.getKey());
}
// do not rely on DNSJava's method for EdDSA for now.
if (mAlgorithms.baseType(originalAlgorithm) == DnsKeyAlgorithm.EDDSA) {
try {
return parseEdDSADNSKEYRecord(pKeyRecord);
} catch (InvalidKeySpecException e) {
// just to be expedient, recast this as a NoSuchAlgorithmException.
throw new NoSuchAlgorithmException(e.getMessage());
}
}
try {
// This uses DNSJava's DNSSEC.toPublicKey() method.
return pKeyRecord.getPublicKey();
@ -105,12 +119,30 @@ public class DnsKeyConverter {
}
}
/**
* Since we don't (yet) have support in DNSJava for parsing the
* newer EdDSA algorithms, here is a local version.
*/
private PublicKey parseEdDSADNSKEYRecord(DNSKEYRecord pKeyRecord)
throws IllegalArgumentException, NoSuchAlgorithmException, InvalidKeySpecException {
byte[] seed = pKeyRecord.getKey();
EdDSAPublicKeySpec spec = new EdDSAPublicKeySpec(seed,
mAlgorithms.getEdwardsCurveParams(pKeyRecord.getAlgorithm()));
KeyFactory factory = KeyFactory.getInstance("EdDSA");
return factory.generatePublic(spec);
}
/**
* Given a JCA public key and the ancillary data, generate a DNSKEY record.
*/
public DNSKEYRecord generateDNSKEYRecord(Name name, int dclass, long ttl,
int flags, int alg, PublicKey key) {
try {
if (mAlgorithms.baseType(alg) == DnsKeyAlgorithm.EDDSA) {
return generateEdDSADNSKEYRecord(name, dclass, ttl, flags, alg, key);
}
return new DNSKEYRecord(name, dclass, ttl, flags, DNSKEYRecord.Protocol.DNSSEC, alg,
key);
} catch (DNSSECException e) {
@ -120,6 +152,13 @@ public class DnsKeyConverter {
}
}
private DNSKEYRecord generateEdDSADNSKEYRecord(Name name, int dclass, long ttl,
int flags, int alg, PublicKey key) {
EdDSAPublicKey ed_key = (EdDSAPublicKey) key;
byte[] key_data = ed_key.getAbyte();
return new DNSKEYRecord(name, dclass, ttl, flags, DNSKEYRecord.Protocol.DNSSEC, alg,
key_data);
}
// Private Key Specific Parsing routines
/**
@ -129,9 +168,9 @@ public class DnsKeyConverter {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key);
try {
switch (mAlgorithms.baseType(algorithm)) {
case RSA:
case DnsKeyAlgorithm.RSA:
return mRSAKeyFactory.generatePrivate(spec);
case DSA:
case DnsKeyAlgorithm.DSA:
return mDSAKeyFactory.generatePrivate(spec);
default:
return null;
@ -186,17 +225,17 @@ public class DnsKeyConverter {
int alg = parseInt(val, -1);
switch (mAlgorithms.baseType(alg)) {
case RSA:
case DnsKeyAlgorithm.RSA:
return parsePrivateRSA(lines);
case DSA:
case DnsKeyAlgorithm.DSA:
return parsePrivateDSA(lines);
case DH:
case DnsKeyAlgorithm.DH:
return parsePrivateDH(lines);
case ECC_GOST:
case DnsKeyAlgorithm.ECC_GOST:
return parsePrivateECDSA(lines, alg);
case ECDSA:
case DnsKeyAlgorithm.ECDSA:
return parsePrivateECDSA(lines, alg);
case EDDSA:
case DnsKeyAlgorithm.EDDSA:
return parsePrivateEdDSA(lines, alg);
default:
throw new IOException("unsupported private key algorithm: " + val);
@ -233,12 +272,12 @@ public class DnsKeyConverter {
private PrivateKey parsePrivateRSA(StringTokenizer lines)
throws NoSuchAlgorithmException {
BigInteger modulus = null;
BigInteger publicExponent = null;
BigInteger privateExponent = null;
BigInteger primeP = null;
BigInteger primeQ = null;
BigInteger primePExponent = null;
BigInteger primeQExponent = null;
BigInteger public_exponent = null;
BigInteger private_exponent = null;
BigInteger prime_p = null;
BigInteger prime_q = null;
BigInteger prime_p_exponent = null;
BigInteger prime_q_exponent = null;
BigInteger coefficient = null;
while (lines.hasMoreTokens()) {
@ -257,28 +296,33 @@ public class DnsKeyConverter {
if (line.startsWith("Modulus: ")) {
modulus = new BigInteger(1, data);
// printBigIntCompare(data, modulus);
} else if (line.startsWith("PublicExponent: ")) {
publicExponent = new BigInteger(1, data);
public_exponent = new BigInteger(1, data);
// printBigIntCompare(data, public_exponent);
} else if (line.startsWith("PrivateExponent: ")) {
privateExponent = new BigInteger(1, data);
private_exponent = new BigInteger(1, data);
// printBigIntCompare(data, private_exponent);
} else if (line.startsWith("Prime1: ")) {
primeP = new BigInteger(1, data);
prime_p = new BigInteger(1, data);
// printBigIntCompare(data, prime_p);
} else if (line.startsWith("Prime2: ")) {
primeQ = new BigInteger(1, data);
prime_q = new BigInteger(1, data);
// printBigIntCompare(data, prime_q);
} else if (line.startsWith("Exponent1: ")) {
primePExponent = new BigInteger(1, data);
prime_p_exponent = new BigInteger(1, data);
} else if (line.startsWith("Exponent2: ")) {
primeQExponent = new BigInteger(1, data);
prime_q_exponent = new BigInteger(1, data);
} else if (line.startsWith("Coefficient: ")) {
coefficient = new BigInteger(1, data);
}
}
try {
KeySpec spec = new RSAPrivateCrtKeySpec(modulus, publicExponent,
privateExponent, primeP,
primeQ, primePExponent,
primeQExponent, coefficient);
KeySpec spec = new RSAPrivateCrtKeySpec(modulus, public_exponent,
private_exponent, prime_p,
prime_q, prime_p_exponent,
prime_q_exponent, coefficient);
if (mRSAKeyFactory == null) {
mRSAKeyFactory = KeyFactory.getInstance("RSA");
}
@ -422,13 +466,13 @@ public class DnsKeyConverter {
if (mECKeyFactory == null) {
mECKeyFactory = KeyFactory.getInstance("EC");
}
ECParameterSpec ecSpec = mAlgorithms.getEllipticCurveParams(algorithm);
if (ecSpec == null) {
ECParameterSpec ec_spec = mAlgorithms.getEllipticCurveParams(algorithm);
if (ec_spec == null) {
throw new NoSuchAlgorithmException("DNSSEC algorithm " + algorithm +
" is not a recognized Elliptic Curve algorithm");
}
KeySpec spec = new ECPrivateKeySpec(s, ecSpec);
KeySpec spec = new ECPrivateKeySpec(s, ec_spec);
try {
return mECKeyFactory.generatePrivate(spec);
@ -472,13 +516,13 @@ public class DnsKeyConverter {
if (mEdKeyFactory == null) {
mEdKeyFactory = KeyFactory.getInstance("EdDSA");
}
NamedParameterSpec namedSpec = mAlgorithms.getEdwardsCurveSpec(algorithm);
if (namedSpec == null) {
EdDSAParameterSpec ed_spec = mAlgorithms.getEdwardsCurveParams(algorithm);
if (ed_spec == null) {
throw new NoSuchAlgorithmException("DNSSEC algorithm " + algorithm +
" is not a recognized Edwards Curve algorithm");
}
EdECPrivateKeySpec spec = new EdECPrivateKeySpec(namedSpec, seed);
KeySpec spec = new EdDSAPrivateKeySpec(seed, ed_spec);
try {
return mEdKeyFactory.generatePrivate(spec);
@ -501,8 +545,8 @@ public class DnsKeyConverter {
return generatePrivateDH((DHPrivateKey) priv, (DHPublicKey) pub, alg);
} else if (priv instanceof ECPrivateKey && pub instanceof ECPublicKey) {
return generatePrivateEC((ECPrivateKey) priv, (ECPublicKey) pub, alg);
} else if (priv instanceof EdECPrivateKey && pub instanceof EdECPublicKey) {
return generatePrivateED((EdECPrivateKey) priv, (EdECPublicKey) pub, alg);
} else if (priv instanceof EdDSAPrivateKey && pub instanceof EdDSAPublicKey) {
return generatePrivateED((EdDSAPrivateKey) priv, (EdDSAPublicKey) pub, alg);
}
return null;
@ -512,16 +556,16 @@ public class DnsKeyConverter {
* Convert from 'unsigned' big integer to original 'signed format' in Base64
*/
private static String b64BigInt(BigInteger i) {
byte[] origBytes = i.toByteArray();
byte[] orig_bytes = i.toByteArray();
if (origBytes[0] != 0 || origBytes.length == 1) {
return base64.toString(origBytes);
if (orig_bytes[0] != 0 || orig_bytes.length == 1) {
return base64.toString(orig_bytes);
}
byte[] signedBytes = new byte[origBytes.length - 1];
System.arraycopy(origBytes, 1, signedBytes, 0, signedBytes.length);
byte[] signed_bytes = new byte[orig_bytes.length - 1];
System.arraycopy(orig_bytes, 1, signed_bytes, 0, signed_bytes.length);
return base64.toString(signedBytes);
return base64.toString(signed_bytes);
}
/**
@ -624,7 +668,7 @@ public class DnsKeyConverter {
* Given an edwards curve key pair, and the actual algorithm (which will
* describe the curve used), return the BIND9-style text encoding.
*/
private String generatePrivateED(EdECPrivateKey priv, EdECPublicKey pub, int alg) {
private String generatePrivateED(EdDSAPrivateKey priv, EdDSAPublicKey pub, int alg) {
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
@ -632,8 +676,7 @@ public class DnsKeyConverter {
out.println("Algorithm: " + alg + " (" + mAlgorithms.algToString(alg)
+ ")");
out.print("PrivateKey: ");
byte[] keyBytes = priv.getBytes().orElse("null".getBytes());
out.println(base64.toString(keyBytes));
out.println(base64.toString(priv.getSeed()));
return sw.toString();
}

View File

@ -264,23 +264,19 @@ public class DnsKeyPair {
* @throws NoSuchAlgorithmException
*/
public Signature getVerifier() {
if (mVerifier != null)
return mVerifier;
if (mVerifier == null) {
mVerifier = getSignature();
PublicKey pk = getPublic();
if (mVerifier == null || pk == null) {
log.warning("Could not get a Signature object for this key pair" + this);
return null;
}
if (mVerifier != null && pk != null) {
try {
mVerifier.initVerify(pk);
} catch (InvalidKeyException e) {
log.warning("Key pair cannot initialize with public key: " + this);
}
} else {
// do not return an uninitialized verifier
return null;
}
}
return mVerifier;
}
@ -334,7 +330,6 @@ public class DnsKeyPair {
// This is from a StackOverflow answer. There are number of bytes-to-hex
// converters in the ecosystem, but this avoid extra dependencies
private static final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
public static String toHex(byte[] bytes) {
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {

View File

@ -241,7 +241,7 @@ public class DnsSecVerifier {
byte[] sig = sigrec.getSignature();
if (algs.baseType(sigrec.getAlgorithm()) == DnsKeyAlgorithm.BaseAlgorithm.DSA) {
if (algs.baseType(sigrec.getAlgorithm()) == DnsKeyAlgorithm.DSA) {
sig = SignUtils.convertDSASignature(sig);
}

View File

@ -68,15 +68,21 @@ public class JCEDnsSecSigner {
/**
* Cryptographically generate a new DNSSEC key.
*
* @param owner the KEY RR's owner name.
* @param ttl the KEY RR's TTL.
* @param dclass the KEY RR's DNS class.
* @param algorithm the DNSSEC algorithm (RSASHA258, RSASHA512,
* ECDSAP256,
* etc.)
* @param flags any flags for the KEY RR.
* @param keysize the size of the key to generate.
* @param useLargeExponent if generating an RSA key, use the large exponent.
* @param owner
* the KEY RR's owner name.
* @param ttl
* the KEY RR's TTL.
* @param dclass
* the KEY RR's DNS class.
* @param algorithm
* the DNSSEC algorithm (RSASHA258, RSASHA512,
* ECDSAP256, etc.)
* @param flags
* any flags for the KEY RR.
* @param keysize
* the size of the key to generate.
* @param useLargeExponent
* if generating an RSA key, use the large exponent.
* @return a DnsKeyPair with the public and private keys populated.
*/
public DnsKeyPair generateKey(Name owner, long ttl, int dclass, int algorithm,
@ -107,25 +113,29 @@ public class JCEDnsSecSigner {
/**
* Sign an RRset.
*
* @param rrset the RRset to sign -- any existing signatures are ignored.
* @param keypars a list of DnsKeyPair objects containing private keys.
* @param start the inception time for the resulting RRSIG records.
* @param expire the expiration time for the resulting RRSIG records.
* @param rrset
* the RRset to sign -- any existing signatures are ignored.
* @param keypars
* a list of DnsKeyPair objects containing private keys.
* @param start
* the inception time for the resulting RRSIG records.
* @param expire
* the expiration time for the resulting RRSIG records.
* @return a list of RRSIGRecord objects.
*/
public List<RRSIGRecord> signRRset(RRset rrset, List<DnsKeyPair> keypairs, Instant start,
Instant expire) throws IOException,
GeneralSecurityException {
if (rrset == null || keypairs == null)
return new ArrayList<>();
return null;
// default start to now, expire to start + 1 second.
if (start == null)
start = Instant.now();
if (expire == null)
expire = start.plusSeconds(1);
if (keypairs.isEmpty())
return new ArrayList<>();
if (keypairs.size() == 0)
return null;
if (mVerboseSigning) {
log.info("Signing RRset:");
@ -133,9 +143,9 @@ public class JCEDnsSecSigner {
}
// first, pre-calculate the RRset bytes.
byte[] rrsetData = SignUtils.generateCanonicalRRsetData(rrset, 0, 0);
byte[] rrset_data = SignUtils.generateCanonicalRRsetData(rrset, 0, 0);
ArrayList<RRSIGRecord> sigs = new ArrayList<>(keypairs.size());
ArrayList<RRSIGRecord> sigs = new ArrayList<RRSIGRecord>(keypairs.size());
// for each keypair, sign the RRset.
for (DnsKeyPair pair : keypairs) {
@ -145,13 +155,13 @@ public class JCEDnsSecSigner {
RRSIGRecord presig = SignUtils.generatePreRRSIG(rrset, keyrec, start, expire,
rrset.getTTL());
byte[] signData = SignUtils.generateSigData(rrsetData, presig);
byte[] sign_data = SignUtils.generateSigData(rrset_data, presig);
if (mVerboseSigning) {
log.info("Canonical pre-signature data to sign with key "
+ keyrec.getName().toString() + "/" + keyrec.getAlgorithm() + "/"
+ keyrec.getFootprint() + ":");
log.info(hexdump.dump(null, signData));
log.info(hexdump.dump(null, sign_data));
}
Signature signer = pair.getSigner();
@ -164,7 +174,7 @@ public class JCEDnsSecSigner {
}
// sign the data.
signer.update(signData);
signer.update(sign_data);
byte[] sig = signer.sign();
if (mVerboseSigning) {
@ -174,7 +184,7 @@ public class JCEDnsSecSigner {
DnsKeyAlgorithm algs = DnsKeyAlgorithm.getInstance();
// Convert to RFC 2536 format, if necessary.
if (algs.baseType(pair.getDNSKEYAlgorithm()) == DnsKeyAlgorithm.BaseAlgorithm.DSA) {
if (algs.baseType(pair.getDNSKEYAlgorithm()) == DnsKeyAlgorithm.DSA) {
DSAPublicKey pk = (DSAPublicKey) pair.getPublic();
sig = SignUtils.convertDSASignature(pk.getParams(), sig);
}
@ -196,9 +206,12 @@ public class JCEDnsSecSigner {
/**
* Create a completely self-signed DNSKEY RRset.
*
* @param keypairs the public & private keypairs to use in the keyset.
* @param start the RRSIG inception time.
* @param expire the RRSIG expiration time.
* @param keypairs
* the public & private keypairs to use in the keyset.
* @param start
* the RRSIG inception time.
* @param expire
* the RRSIG expiration time.
* @return a signed RRset.
*/
public RRset makeKeySet(List<DnsKeyPair> keypairs, Instant start, Instant expire)
@ -223,55 +236,67 @@ public class JCEDnsSecSigner {
/**
* Conditionally sign an RRset and add it to the toList.
*
* @param toList the list to which we are adding the processed RRsets.
* @param zonename the zone apex name.
* @param rrset the RRset under consideration.
* @param kskpairs the List of KSKs..
* @param zskpairs the List of zone keys.
* @param start the RRSIG inception time.
* @param expire the RRSIG expiration time.
* @param fullySignKeyset if true, sign the zone apex keyset with both KSKs
* and ZSKs.
* @param lastCut the name of the last delegation point encountered.
* @param toList
* the list to which we are adding the processed RRsets.
* @param zonename
* the zone apex name.
* @param rrset
* the RRset under consideration.
* @param kskpairs
* the List of KSKs..
* @param zskpairs
* the List of zone keys.
* @param start
* the RRSIG inception time.
* @param expire
* the RRSIG expiration time.
* @param fullySignKeyset
* if true, sign the zone apex keyset with both KSKs and
* ZSKs.
* @param last_cut
* the name of the last delegation point encountered.
*
* @return the name of the new last_cut.
*/
private Name addRRset(List<Record> toList, Name zonename, RRset rrset,
List<DnsKeyPair> kskpairs, List<DnsKeyPair> zskpairs, Instant start,
Instant expire, boolean fullySignKeyset, Name lastCut,
Name lastDname) throws IOException, GeneralSecurityException {
Instant expire, boolean fullySignKeyset, Name last_cut,
Name last_dname) throws IOException, GeneralSecurityException {
// add the records themselves
rrset.rrs().forEach(toList::add);
rrset.rrs().forEach(record -> {
toList.add(record);
});
int type = SignUtils.recordSecType(zonename, rrset.getName(), rrset.getType(),
lastCut, lastDname);
last_cut, last_dname);
// we don't sign non-normal sets (delegations, glue, invalid).
if (type == SignUtils.RR_DELEGATION) {
return rrset.getName();
}
if (type == SignUtils.RR_GLUE || type == SignUtils.RR_INVALID) {
return lastCut;
return last_cut;
}
// check for the zone apex keyset.
if (rrset.getName().equals(zonename) && rrset.getType() == Type.DNSKEY && kskpairs != null && !kskpairs.isEmpty()) {
if (rrset.getName().equals(zonename) && rrset.getType() == Type.DNSKEY) {
// if we have ksks, sign the keyset with them, otherwise we will just sign
// them with the zsks.
if (kskpairs != null && kskpairs.size() > 0) {
List<RRSIGRecord> sigs = signRRset(rrset, kskpairs, start, expire);
toList.addAll(sigs);
// If we aren't going to sign with all the keys, bail out now.
if (!fullySignKeyset)
return lastCut;
return last_cut;
}
}
// otherwise, we are OK to sign this set.
List<RRSIGRecord> sigs = signRRset(rrset, zskpairs, start, expire);
toList.addAll(sigs);
return lastCut;
return last_cut;
}
// Various NSEC/NSEC3 generation modes
@ -286,31 +311,49 @@ public class JCEDnsSecSigner {
* Opt-Out, etc.) External users of this class are expected to use the
* appropriate public signZone* methods instead of this.
*
* @param zonename The name of the zone
* @param records The records comprising the zone. They do not have to
* be in any particular order, as this method will
* order them as necessary.
* @param kskpairs The key pairs designated as "key signing keys"
* @param zskpairs The key pairs designated as "zone signing keys"
* @param start The RRSIG inception time
* @param expire The RRSIG expiration time
* @param fullySignKeyset If true, all keys (ksk or zsk) will sign the DNSKEY
* RRset. If false, only the ksks will sign it.
* @param dsDigestAlg The hash algorithm to use for generating DS records
* @param zonename
* The name of the zone
* @param records
* The records comprising the zone. They do not have to
* be in any
* particular order, as this method will order them as
* necessary.
* @param kskpairs
* The key pairs designated as "key signing keys"
* @param zskpairs
* The key pairs designated as "zone signing keys"
* @param start
* The RRSIG inception time
* @param expire
* The RRSIG expiration time
* @param fullySignKeyset
* If true, all keys (ksk or zsk) will sign the DNSKEY
* RRset. If
* false, only the ksks will sign it.
* @param ds_digest_alg
* The hash algorithm to use for generating DS records
* (DSRecord.SHA1_DIGEST_ID, e.g.)
* @param mode The NSEC/NSEC3 generation mode: NSEC_MODE,
* NSEC3_MODE, NSEC3_OPTOUT_MODE, etc.
* @param includedNames When using an Opt-In/Opt-Out mode, the names listed
* here will be included in the NSEC/NSEC3 chain
* regardless
* @param salt When using an NSEC3 mode, use this salt.
* @param iterations When using an NSEC3 mode, use this number of
* @param mode
* The NSEC/NSEC3 generation mode: NSEC_MODE, NSEC3_MODE,
* NSEC3_OPTOUT_MODE, etc.
* @param includedNames
* When using an Opt-In/Opt-Out mode, the names listed
* here will be
* included in the NSEC/NSEC3 chain regardless
* @param salt
* When using an NSEC3 mode, use this salt.
* @param iterations
* When using an NSEC3 mode, use this number of
* iterations
* @param beConservative If true, then only turn on the Opt-In flag when
* there are insecure delegations in the span.
* Currently this only works for NSEC_EXP_OPT_IN mode.
* @param nsec3paramttl The TTL to use for the generated NSEC3PARAM record.
* Negative values will use the SOA TTL.
* @param beConservative
* If true, then only turn on the Opt-In flag when there
* are insecure
* delegations in the span. Currently this only works for
* NSEC_EXP_OPT_IN mode.
* @param nsec3paramttl
* The TTL to use for the generated NSEC3PARAM record.
* Negative
* values will use the SOA TTL.
* @return an ordered list of {@link org.xbill.DNS.Record} objects,
* representing the signed zone.
*
@ -320,7 +363,7 @@ public class JCEDnsSecSigner {
private List<Record> signZone(Name zonename, List<Record> records,
List<DnsKeyPair> kskpairs, List<DnsKeyPair> zskpairs,
Instant start, Instant expire, boolean fullySignKeyset,
int dsDigestAlg, int mode, List<Name> includedNames,
int ds_digest_alg, int mode, List<Name> includedNames,
byte[] salt, int iterations, long nsec3paramttl,
boolean beConservative) throws IOException,
GeneralSecurityException {
@ -337,7 +380,7 @@ public class JCEDnsSecSigner {
// Generate DS records. This replaces any non-zone-apex DNSKEY RRs with DS
// RRs.
SignUtils.generateDSRecords(zonename, records, dsDigestAlg);
SignUtils.generateDSRecords(zonename, records, ds_digest_alg);
// Generate the NSEC or NSEC3 records based on 'mode'
switch (mode) {
@ -355,8 +398,6 @@ public class JCEDnsSecSigner {
SignUtils.generateOptInNSECRecords(zonename, records, includedNames,
beConservative);
break;
default:
throw new NoSuchAlgorithmException("Unknown NSEC/NSEC3 mode: " + mode);
}
// Re-sort so we can assemble into rrsets.
@ -364,9 +405,9 @@ public class JCEDnsSecSigner {
// Assemble into RRsets and sign.
RRset rrset = new RRset();
ArrayList<Record> signedRecords = new ArrayList<>();
Name lastCut = null;
Name lastDname = null;
ArrayList<Record> signed_records = new ArrayList<Record>();
Name last_cut = null;
Name last_dname = null;
for (ListIterator<Record> i = records.listIterator(); i.hasNext();) {
Record r = i.next();
@ -389,38 +430,48 @@ public class JCEDnsSecSigner {
// add the RRset to the list of signed_records, regardless of
// whether or not we actually end up signing the set.
lastCut = addRRset(signedRecords, zonename, rrset, kskpairs, zskpairs, start,
expire, fullySignKeyset, lastCut, lastDname);
last_cut = addRRset(signed_records, zonename, rrset, kskpairs, zskpairs, start,
expire, fullySignKeyset, last_cut, last_dname);
if (rrset.getType() == Type.DNAME)
lastDname = rrset.getName();
last_dname = rrset.getName();
rrset.clear();
rrset.addRR(r);
}
// add the last RR set
addRRset(signedRecords, zonename, rrset, kskpairs, zskpairs, start, expire,
fullySignKeyset, lastCut, lastDname);
addRRset(signed_records, zonename, rrset, kskpairs, zskpairs, start, expire,
fullySignKeyset, last_cut, last_dname);
return signedRecords;
return signed_records;
}
/**
* Given a zone, sign it using standard NSEC records.
*
* @param zonename The name of the zone.
* @param records The records comprising the zone. They do not have to
* be in any particular order, as this method will
* order them as necessary.
* @param kskpairs The key pairs that are designated as "key signing
* @param zonename
* The name of the zone.
* @param records
* The records comprising the zone. They do not have to
* be in any
* particular order, as this method will order them as
* necessary.
* @param kskpairs
* The key pairs that are designated as "key signing
* keys".
* @param zskpairs This key pairs that are designated as "zone signing
* @param zskpairs
* This key pairs that are designated as "zone signing
* keys".
* @param start The RRSIG inception time.
* @param expire The RRSIG expiration time.
* @param fullySignKeyset Sign the zone apex keyset with all available keys
* (instead of just the key signing keys).
* @param dsDigestAlg The digest algorithm to use when generating DS
* @param start
* The RRSIG inception time.
* @param expire
* The RRSIG expiration time.
* @param fullySignKeyset
* Sign the zone apex keyset with all available keys
* (instead of just
* the key signing keys).
* @param ds_digest_alg
* The digest algorithm to use when generating DS
* records.
*
* @return an ordered list of {@link org.xbill.DNS.Record} objects,
@ -429,42 +480,58 @@ public class JCEDnsSecSigner {
public List<Record> signZone(Name zonename, List<Record> records,
List<DnsKeyPair> kskpairs, List<DnsKeyPair> zskpairs,
Instant start, Instant expire, boolean fullySignKeyset,
int dsDigestAlg) throws IOException,
int ds_digest_alg) throws IOException,
GeneralSecurityException {
return signZone(zonename, records, kskpairs, zskpairs, start, expire,
fullySignKeyset, dsDigestAlg, NSEC_MODE, null, null, 0, 0, false);
fullySignKeyset, ds_digest_alg, NSEC_MODE, null, null, 0, 0, false);
}
/**
* Given a zone, sign it using NSEC3 records.
*
* @param signer A signer (utility) object used to actually sign
* stuff.
* @param zonename The name of the zone being signed.
* @param records The records comprising the zone. They do not have to
* be in any particular order, as this method will
* order them as necessary.
* @param kskpairs The key pairs that are designated as "key signing
* @param signer
* A signer (utility) object used to actually sign stuff.
* @param zonename
* The name of the zone being signed.
* @param records
* The records comprising the zone. They do not have to
* be in any
* particular order, as this method will order them as
* necessary.
* @param kskpairs
* The key pairs that are designated as "key signing
* keys".
* @param zskpairs This key pairs that are designated as "zone signing
* @param zskpairs
* This key pairs that are designated as "zone signing
* keys".
* @param start The RRSIG inception time.
* @param expire The RRSIG expiration time.
* @param fullySignKeyset If true then the DNSKEY RRset will be signed by all
* available keys, if false, only the key signing keys.
* @param useOptOut If true, insecure delegations will be omitted from
* the NSEC3 chain, and all NSEC3 records will have the
* Opt-Out flag set.
* @param includedNames A list of names to include in the NSEC3 chain
* @param start
* The RRSIG inception time.
* @param expire
* The RRSIG expiration time.
* @param fullySignKeyset
* If true then the DNSKEY RRset will be signed by all
* available
* keys, if false, only the key signing keys.
* @param useOptOut
* If true, insecure delegations will be omitted from the
* NSEC3
* chain, and all NSEC3 records will have the Opt-Out
* flag set.
* @param includedNames
* A list of names to include in the NSEC3 chain
* regardless.
* @param salt The salt to use for the NSEC3 hashing. null means no
* @param salt
* The salt to use for the NSEC3 hashing. null means no
* salt.
* @param iterations The number of iterations to use for the NSEC3
* hashing.
* @param dsDigestAlg The digest algorithm to use when generating DS
* @param iterations
* The number of iterations to use for the NSEC3 hashing.
* @param ds_digest_alg
* The digest algorithm to use when generating DS
* records.
* @param nsec3paramttl The TTL to use for the generated NSEC3PARAM record.
* Negative values will use the SOA TTL.
* @param nsec3paramttl
* The TTL to use for the generated NSEC3PARAM record.
* Negative
* values will use the SOA TTL.
* @return an ordered list of {@link org.xbill.DNS.Record} objects,
* representing the signed zone.
*
@ -475,16 +542,16 @@ public class JCEDnsSecSigner {
List<DnsKeyPair> kskpairs, List<DnsKeyPair> zskpairs,
Instant start, Instant expire, boolean fullySignKeyset,
boolean useOptOut, List<Name> includedNames,
byte[] salt, int iterations, int dsDigestAlg,
byte[] salt, int iterations, int ds_digest_alg,
long nsec3paramttl) throws IOException,
GeneralSecurityException {
if (useOptOut) {
return signZone(zonename, records, kskpairs, zskpairs, start, expire,
fullySignKeyset, dsDigestAlg, NSEC3_OPTOUT_MODE, includedNames,
fullySignKeyset, ds_digest_alg, NSEC3_OPTOUT_MODE, includedNames,
salt, iterations, nsec3paramttl, false);
} else {
return signZone(zonename, records, kskpairs, zskpairs, start, expire,
fullySignKeyset, dsDigestAlg, NSEC3_MODE, null, salt, iterations,
fullySignKeyset, ds_digest_alg, NSEC3_MODE, null, salt, iterations,
nsec3paramttl, false);
}
}
@ -493,25 +560,37 @@ public class JCEDnsSecSigner {
* Given a zone, sign it using experimental Opt-In NSEC records (see RFC
* 4956).
*
* @param zonename the name of the zone.
* @param records the records comprising the zone. They do not
* have to be in any particular order, as this
* method will order them as necessary.
* @param kskpairs the key pairs that are designated as "key
* @param zonename
* the name of the zone.
* @param records
* the records comprising the zone. They do not have
* to be in any
* particular order, as this method will order them
* as necessary.
* @param kskpairs
* the key pairs that are designated as "key signing
* keys".
* @param zskpairs
* this key pairs that are designated as "zone
* signing keys".
* @param zskpairs this key pairs that are designated as "zone
* signing keys".
* @param start the RRSIG inception time.
* @param expire the RRSIG expiration time.
* @param useConservativeOptIn if true, Opt-In NSEC records will only be
* generated if there are insecure, unsigned
* delegations in the span.
* @param fullySignKeyset sign the zone apex keyset with all available
* @param start
* the RRSIG inception time.
* @param expire
* the RRSIG expiration time.
* @param useConservativeOptIn
* if true, Opt-In NSEC records will only be
* generated if there are
* insecure, unsigned delegations in the span.
* @param fullySignKeyset
* sign the zone apex keyset with all available
* keys.
* @param dsDigestAlg The digest algorithm to use when generating DS
* @param ds_digest_alg
* The digest algorithm to use when generating DS
* records.
* @param nsecIncludeNames names that are to be included in the NSEC chain
* regardless. This may be null.
* @param NSECIncludeNames
* names that are to be included in the NSEC chain
* regardless. This
* may be null.
* @return an ordered list of {@link org.xbill.DNS.Record} objects,
* representing the signed zone.
*/
@ -519,12 +598,12 @@ public class JCEDnsSecSigner {
List<DnsKeyPair> kskpairs, List<DnsKeyPair> zskpairs,
Instant start, Instant expire,
boolean useConservativeOptIn,
boolean fullySignKeyset, List<Name> nsecIncludeNames,
int dsDigestAlg) throws IOException,
boolean fullySignKeyset, List<Name> NSECIncludeNames,
int ds_digest_alg) throws IOException,
GeneralSecurityException {
return signZone(zonename, records, kskpairs, zskpairs, start, expire,
fullySignKeyset, dsDigestAlg, NSEC_EXP_OPT_IN, nsecIncludeNames,
fullySignKeyset, ds_digest_alg, NSEC_EXP_OPT_IN, NSECIncludeNames,
null, 0, 0, useConservativeOptIn);
}
}

View File

@ -33,7 +33,6 @@ import org.xbill.DNS.Type;
public class RecordComparator implements Comparator<Record> {
public RecordComparator() {
// nothing to initialize
}
/**
@ -66,15 +65,15 @@ public class RecordComparator implements Comparator<Record> {
}
private int compareRDATA(Record a, Record b) {
byte[] aRdata = a.rdataToWireCanonical();
byte[] bRdata = b.rdataToWireCanonical();
byte[] a_rdata = a.rdataToWireCanonical();
byte[] b_rdata = b.rdataToWireCanonical();
for (int i = 0; i < aRdata.length && i < bRdata.length; i++) {
int n = (aRdata[i] & 0xFF) - (bRdata[i] & 0xFF);
for (int i = 0; i < a_rdata.length && i < b_rdata.length; i++) {
int n = (a_rdata[i] & 0xFF) - (b_rdata[i] & 0xFF);
if (n != 0)
return n;
}
return (aRdata.length - bRdata.length);
return (a_rdata.length - b_rdata.length);
}
public int compare(Record a, Record b) {
@ -89,27 +88,27 @@ public class RecordComparator implements Comparator<Record> {
if (res != 0)
return res;
int aType = a.getType();
int bType = b.getType();
int sigType = 0;
int a_type = a.getType();
int b_type = b.getType();
int sig_type = 0;
if (aType == Type.RRSIG) {
aType = ((RRSIGRecord) a).getTypeCovered();
if (bType != Type.RRSIG)
sigType = 1;
if (a_type == Type.RRSIG) {
a_type = ((RRSIGRecord) a).getTypeCovered();
if (b_type != Type.RRSIG)
sig_type = 1;
}
if (bType == Type.RRSIG) {
bType = ((RRSIGRecord) b).getTypeCovered();
if (b_type == Type.RRSIG) {
b_type = ((RRSIGRecord) b).getTypeCovered();
if (a.getType() != Type.RRSIG)
sigType = -1;
sig_type = -1;
}
res = compareTypes(aType, bType);
res = compareTypes(a_type, b_type);
if (res != 0)
return res;
if (sigType != 0)
return sigType;
if (sig_type != 0)
return sig_type;
return compareRDATA(a, b);
}

File diff suppressed because it is too large Load Diff

View File

@ -37,7 +37,7 @@ public class TypeMap {
private Set<Integer> typeSet;
public TypeMap() {
this.typeSet = new HashSet<>();
this.typeSet = new HashSet<Integer>();
}
/** Add the given type to the typemap. */
@ -78,20 +78,20 @@ public class TypeMap {
TypeMap typemap = new TypeMap();
int page;
int byteLength;
int byte_length;
while (m < map.length) {
page = map[m++];
byteLength = map[m++];
byte_length = map[m++];
for (int i = 0; i < byteLength; i++) {
for (int i = 0; i < byte_length; i++) {
for (int j = 0; j < 8; j++) {
if (((map[m + i] & 0xFF) & (1 << (7 - j))) != 0) {
if ((map[m + i] & (1 << (7 - j))) != 0) {
typemap.set((page << 8) + (i * 8) + j);
}
}
}
m += byteLength;
m += byte_length;
}
return typemap;
@ -115,7 +115,7 @@ public class TypeMap {
int[] types = getTypes();
Arrays.sort(types);
StringBuilder sb = new StringBuilder();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < types.length; i++) {
if (i > 0)
@ -129,16 +129,16 @@ public class TypeMap {
protected static void mapToWire(DNSOutput out, int[] types, int base, int start, int end) {
// calculate the length of this map by looking at the largest
// typecode in this section.
int maxType = types[end - 1] & 0xFF;
int mapLength = (maxType / 8) + 1;
int max_type = types[end - 1] & 0xFF;
int map_length = (max_type / 8) + 1;
// write the map "header" -- the base and the length of the map.
out.writeU8(base & 0xFF);
out.writeU8(mapLength & 0xFF);
out.writeU8(map_length & 0xFF);
// allocate a temporary scratch space for caculating the actual
// bitmap.
byte[] map = new byte[mapLength];
byte[] map = new byte[map_length];
// for each type in our sub-array, set its corresponding bit in the map.
for (int i = start; i < end; i++) {
@ -179,7 +179,7 @@ public class TypeMap {
}
public int[] getTypes() {
Integer[] a = typeSet.toArray(integerArray);
Integer[] a = (Integer[]) typeSet.toArray(integerArray);
int[] res = new int[a.length];
for (int i = 0; i < res.length; i++) {
@ -189,8 +189,8 @@ public class TypeMap {
return res;
}
public static int[] fromWireToTypes(byte[] wireFmt) {
return TypeMap.fromBytes(wireFmt).getTypes();
public static int[] fromWireToTypes(byte[] wire_fmt) {
return TypeMap.fromBytes(wire_fmt).getTypes();
}
public static byte[] fromTypesToWire(int[] types) {

View File

@ -39,10 +39,6 @@ import org.xbill.DNS.Type;
*/
public class ZoneUtils {
private ZoneUtils() {
}
/**
* Load a zone file.
*
@ -57,10 +53,19 @@ public class ZoneUtils {
* if something goes wrong reading the zone file.
*/
public static List<Record> readZoneFile(String zonefile, Name origin) throws IOException {
ArrayList<Record> records = new ArrayList<>();
try (Master m = zonefile.equals("-") ? new Master(System.in) : new Master(zonefile, origin)) {
ArrayList<Record> records = new ArrayList<Record>();
Master m;
try {
if (zonefile.equals("-")) {
m = new Master(System.in);
} else {
m = new Master(zonefile, origin);
}
Record r = null;
while ((r = m.nextRecord()) != null) {
records.add(r);
}
} catch (IOException e) {
@ -115,7 +120,7 @@ public class ZoneUtils {
}
public static List<Record> findRRs(List<Record> records, Name name, int type) {
List<Record> res = new ArrayList<>();
List<Record> res = new ArrayList<Record>();
for (Record r : records) {
if (r.getName().equals(name) && r.getType() == type) {
res.add(r);

View File

@ -88,12 +88,10 @@ public class ZoneVerifier {
public boolean equals(Object o) {
return super.equals(o);
}
@Override
public int hashCode() {
return super.hashCode();
}
boolean getMark() {
return mIsMarked;
}
@ -150,8 +148,7 @@ public class ZoneVerifier {
/**
* Add a record to the various maps.
*
* @return true if the RR was added, false if it wasn't (because it was a
* duplicate)
* @return true if the RR was added, false if it wasn't (because it was a duplicate)
*/
private boolean addRR(Record r) {
Name n = r.getName();
@ -209,7 +206,7 @@ public class ZoneVerifier {
* Given an unsorted list of records, load the node and rrset maps, as well as
* determine the NSEC3 parameters and signing type.
*
* @param records an unsorted list of {@link org.xbill.DNS.Record} objects.
* @param records
* @return the number of errors encountered.
*/
private int calculateNodes(List<Record> records) {
@ -254,7 +251,7 @@ public class ZoneVerifier {
* Given a name, typeset, and name of the last zone cut, determine the node
* type.
*/
private NodeType determineNodeType(Name n, Set<Integer> typeset, Name lastCut) {
private NodeType determineNodeType(Name n, Set<Integer> typeset, Name last_cut) {
// All RRs at the zone apex are normal
if (n.equals(mZoneName))
return NodeType.NORMAL;
@ -266,7 +263,7 @@ public class ZoneVerifier {
}
// If the node is below a zone cut (either a delegation or DNAME), it is
// glue.
if (lastCut != null && n.subdomain(lastCut) && !n.equals(lastCut)) {
if (last_cut != null && n.subdomain(last_cut) && !n.equals(last_cut)) {
return NodeType.GLUE;
}
@ -297,13 +294,13 @@ public class ZoneVerifier {
*/
private int processNodes() throws NoSuchAlgorithmException, TextParseException {
int errors = 0;
Name lastCut = null;
Name last_cut = null;
for (Map.Entry<Name, Set<Integer>> entry : mNodeMap.entrySet()) {
Name n = entry.getKey();
Set<Integer> typeset = entry.getValue();
NodeType ntype = determineNodeType(n, typeset, lastCut);
NodeType ntype = determineNodeType(n, typeset, last_cut);
log.finest("Node " + n + " is type " + ntype);
// we can ignore glue/invalid RRs.
@ -312,7 +309,7 @@ public class ZoneVerifier {
// record the last zone cut if this node is a zone cut.
if (ntype == NodeType.DELEGATION || typeset.contains(Type.DNAME)) {
lastCut = n;
last_cut = n;
}
// check all of the RRsets that should be signed