Merge remote-tracking branch 'origin/pr/562' into baremetal
diff --git a/.pylint b/.pylint
deleted file mode 100644
index 934f30b..0000000
--- a/.pylint
+++ /dev/null
@@ -1,425 +0,0 @@
-[MASTER]
-
-# A comma-separated list of package or module names from where C extensions may
-# be loaded. Extensions are loading into the active Python interpreter and may
-# run arbitrary code
-extension-pkg-whitelist=
-
-# Add files or directories to the blacklist. They should be base names, not
-# paths.
-ignore=CVS
-
-# Add files or directories matching the regex patterns to the blacklist. The
-# regex matches against base names, not paths.
-ignore-patterns=
-
-# Python code to execute, usually for sys.path manipulation such as
-# pygtk.require().
-#init-hook=
-
-# Use multiple processes to speed up Pylint.
-jobs=1
-
-# List of plugins (as comma separated values of python modules names) to load,
-# usually to register additional checkers.
-load-plugins=
-
-# Pickle collected data for later comparisons.
-persistent=yes
-
-# Specify a configuration file.
-#rcfile=
-
-# Allow loading of arbitrary C extensions. Extensions are imported into the
-# active Python interpreter and may run arbitrary code.
-unsafe-load-any-extension=no
-
-
-[MESSAGES CONTROL]
-
-# Only show warnings with the listed confidence levels. Leave empty to show
-# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
-confidence=
-
-# Disable the message, report, category or checker with the given id(s). You
-# can either give multiple identifiers separated by comma (,) or put this
-# option multiple times (only on the command line, not in the configuration
-# file where it should appear only once).You can also use "--disable=all" to
-# disable everything first and then reenable specific checks. For example, if
-# you want to run only the similarities checker, you can use "--disable=all
-# --enable=similarities". If you want to run only the classes checker, but have
-# no Warning level messages displayed, use"--disable=all --enable=classes
-# --disable=W"
-disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call
-
-# Enable the message, report, category or checker with the given id(s). You can
-# either give multiple identifier separated by comma (,) or put this option
-# multiple time (only on the command line, not in the configuration file where
-# it should appear only once). See also the "--disable" option for examples.
-enable=
-
-
-[REPORTS]
-
-# Python expression which should return a note less than 10 (10 is the highest
-# note). You have access to the variables errors warning, statement which
-# respectively contain the number of errors / warnings messages and the total
-# number of statements analyzed. This is used by the global evaluation report
-# (RP0004).
-evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
-
-# Template used to display messages. This is a python new-style format string
-# used to format the message information. See doc for all details
-#msg-template=
-
-# Set the output format. Available formats are text, parseable, colorized, json
-# and msvs (visual studio).You can also give a reporter class, eg
-# mypackage.mymodule.MyReporterClass.
-output-format=text
-
-# Tells whether to display a full report or only the messages
-reports=no
-
-# Activate the evaluation score.
-score=yes
-
-
-[REFACTORING]
-
-# Maximum number of nested blocks for function / method body
-max-nested-blocks=5
-
-
-[SIMILARITIES]
-
-# Ignore comments when computing similarities.
-ignore-comments=yes
-
-# Ignore docstrings when computing similarities.
-ignore-docstrings=yes
-
-# Ignore imports when computing similarities.
-ignore-imports=no
-
-# Minimum lines number of a similarity.
-min-similarity-lines=4
-
-
-[FORMAT]
-
-# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
-expected-line-ending-format=
-
-# Regexp for a line that is allowed to be longer than the limit.
-ignore-long-lines=^\s*(# )?<?https?://\S+>?$
-
-# Number of spaces of indent required inside a hanging or continued line.
-indent-after-paren=4
-
-# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
-# tab).
-indent-string=' '
-
-# Maximum number of characters on a single line.
-max-line-length=79
-
-# Maximum number of lines in a module
-max-module-lines=2000
-
-# List of optional constructs for which whitespace checking is disabled. `dict-
-# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
-# `trailing-comma` allows a space between comma and closing bracket: (a, ).
-# `empty-line` allows space-only lines.
-no-space-check=trailing-comma,dict-separator
-
-# Allow the body of a class to be on the same line as the declaration if body
-# contains single statement.
-single-line-class-stmt=no
-
-# Allow the body of an if to be on the same line as the test if there is no
-# else.
-single-line-if-stmt=no
-
-
-[BASIC]
-
-# Naming hint for argument names
-argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Regular expression matching correct argument names
-argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Naming hint for attribute names
-attr-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Regular expression matching correct attribute names
-attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Bad variable names which should always be refused, separated by a comma
-bad-names=foo,bar,baz,toto,tutu,tata
-
-# Naming hint for class attribute names
-class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
-
-# Regular expression matching correct class attribute names
-class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
-
-# Naming hint for class names
-class-name-hint=[A-Z_][a-zA-Z0-9]+$
-
-# Regular expression matching correct class names
-class-rgx=[A-Z_][a-zA-Z0-9]+$
-
-# Naming hint for constant names
-const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
-
-# Regular expression matching correct constant names
-const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
-
-# Minimum line length for functions/classes that require docstrings, shorter
-# ones are exempt.
-docstring-min-length=-1
-
-# Naming hint for function names
-function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Regular expression matching correct function names
-function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Good variable names which should always be accepted, separated by a comma
-good-names=i,j,k,ex,Run,_
-
-# Include a hint for the correct naming format with invalid-name
-include-naming-hint=no
-
-# Naming hint for inline iteration names
-inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
-
-# Regular expression matching correct inline iteration names
-inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
-
-# Naming hint for method names
-method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Regular expression matching correct method names
-method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Naming hint for module names
-module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
-
-# Regular expression matching correct module names
-module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
-
-# Colon-delimited sets of names that determine each other's naming style when
-# the name regexes allow several styles.
-name-group=
-
-# Regular expression which should only match function or class names that do
-# not require a docstring.
-no-docstring-rgx=^_
-
-# List of decorators that produce properties, such as abc.abstractproperty. Add
-# to this list to register other decorators that produce valid properties.
-property-classes=abc.abstractproperty
-
-# Naming hint for variable names
-variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-# Regular expression matching correct variable names
-variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
-
-
-[TYPECHECK]
-
-# List of decorators that produce context managers, such as
-# contextlib.contextmanager. Add to this list to register other decorators that
-# produce valid context managers.
-contextmanager-decorators=contextlib.contextmanager
-
-# List of members which are set dynamically and missed by pylint inference
-# system, and so shouldn't trigger E1101 when accessed. Python regular
-# expressions are accepted.
-generated-members=
-
-# Tells whether missing members accessed in mixin class should be ignored. A
-# mixin class is detected if its name ends with "mixin" (case insensitive).
-ignore-mixin-members=yes
-
-# This flag controls whether pylint should warn about no-member and similar
-# checks whenever an opaque object is returned when inferring. The inference
-# can return multiple potential results while evaluating a Python object, but
-# some branches might not be evaluated, which results in partial inference. In
-# that case, it might be useful to still emit no-member and other checks for
-# the rest of the inferred objects.
-ignore-on-opaque-inference=yes
-
-# List of class names for which member attributes should not be checked (useful
-# for classes with dynamically set attributes). This supports the use of
-# qualified names.
-ignored-classes=optparse.Values,thread._local,_thread._local
-
-# List of module names for which member attributes should not be checked
-# (useful for modules/projects where namespaces are manipulated during runtime
-# and thus existing member attributes cannot be deduced by static analysis. It
-# supports qualified module names, as well as Unix pattern matching.
-ignored-modules=
-
-# Show a hint with possible names when a member name was not found. The aspect
-# of finding the hint is based on edit distance.
-missing-member-hint=yes
-
-# The minimum edit distance a name should have in order to be considered a
-# similar match for a missing member name.
-missing-member-hint-distance=1
-
-# The total number of similar names that should be taken in consideration when
-# showing a hint for a missing member.
-missing-member-max-choices=1
-
-
-[VARIABLES]
-
-# List of additional names supposed to be defined in builtins. Remember that
-# you should avoid to define new builtins when possible.
-additional-builtins=
-
-# Tells whether unused global variables should be treated as a violation.
-allow-global-unused-variables=yes
-
-# List of strings which can identify a callback function by name. A callback
-# name must start or end with one of those strings.
-callbacks=cb_,_cb
-
-# A regular expression matching the name of dummy variables (i.e. expectedly
-# not used).
-dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
-
-# Argument names that match this expression will be ignored. Default to name
-# with leading underscore
-ignored-argument-names=_.*|^ignored_|^unused_
-
-# Tells whether we should check for unused import in __init__ files.
-init-import=no
-
-# List of qualified module names which can have objects that can redefine
-# builtins.
-redefining-builtins-modules=six.moves,future.builtins
-
-
-[SPELLING]
-
-# Spelling dictionary name. Available dictionaries: none. To make it working
-# install python-enchant package.
-spelling-dict=
-
-# List of comma separated words that should not be checked.
-spelling-ignore-words=
-
-# A path to a file that contains private dictionary; one word per line.
-spelling-private-dict-file=
-
-# Tells whether to store unknown words to indicated private dictionary in
-# --spelling-private-dict-file option instead of raising a message.
-spelling-store-unknown-words=no
-
-
-[MISCELLANEOUS]
-
-# List of note tags to take in consideration, separated by a comma.
-notes=FIXME,XXX,TODO
-
-
-[LOGGING]
-
-# Logging modules to check that the string format arguments are in logging
-# function parameter format
-logging-modules=logging
-
-
-[CLASSES]
-
-# List of method names used to declare (i.e. assign) instance attributes.
-defining-attr-methods=__init__,__new__,setUp
-
-# List of member names, which should be excluded from the protected access
-# warning.
-exclude-protected=_asdict,_fields,_replace,_source,_make
-
-# List of valid names for the first argument in a class method.
-valid-classmethod-first-arg=cls
-
-# List of valid names for the first argument in a metaclass class method.
-valid-metaclass-classmethod-first-arg=mcs
-
-
-[DESIGN]
-
-# Maximum number of arguments for function / method
-max-args=5
-
-# Maximum number of attributes for a class (see R0902).
-max-attributes=7
-
-# Maximum number of boolean expressions in a if statement
-max-bool-expr=5
-
-# Maximum number of branch for function / method body
-max-branches=12
-
-# Maximum number of locals for function / method body
-max-locals=15
-
-# Maximum number of parents for a class (see R0901).
-max-parents=7
-
-# Maximum number of public methods for a class (see R0904).
-max-public-methods=20
-
-# Maximum number of return / yield for function / method body
-max-returns=6
-
-# Maximum number of statements in function / method body
-max-statements=50
-
-# Minimum number of public methods for a class (see R0903).
-min-public-methods=2
-
-
-[IMPORTS]
-
-# Allow wildcard imports from modules that define __all__.
-allow-wildcard-with-all=no
-
-# Analyse import fallback blocks. This can be used to support both Python 2 and
-# 3 compatible code, which means that the block might have code that exists
-# only in one or another interpreter, leading to false positives when analysed.
-analyse-fallback-blocks=no
-
-# Deprecated modules which should not be used, separated by a comma
-deprecated-modules=regsub,TERMIOS,Bastion,rexec
-
-# Create a graph of external dependencies in the given file (report RP0402 must
-# not be disabled)
-ext-import-graph=
-
-# Create a graph of every (i.e. internal and external) dependencies in the
-# given file (report RP0402 must not be disabled)
-import-graph=
-
-# Create a graph of internal dependencies in the given file (report RP0402 must
-# not be disabled)
-int-import-graph=
-
-# Force import order to recognize a module as part of the standard
-# compatibility libraries.
-known-standard-library=
-
-# Force import order to recognize a module as part of a third party library.
-known-third-party=enchant
-
-
-[EXCEPTIONS]
-
-# Exceptions that will emit a warning when being caught. Defaults to
-# "Exception"
-overgeneral-exceptions=Exception
diff --git a/.pylintrc b/.pylintrc
new file mode 100644
index 0000000..168e0b7
--- /dev/null
+++ b/.pylintrc
@@ -0,0 +1,52 @@
+[BASIC]
+# We're ok with short funtion argument names.
+# [invalid-name]
+argument-rgx=[a-z_][a-z0-9_]*$
+
+# Allow filter and map.
+# [bad-builtin]
+bad-functions=input
+
+# We prefer docstrings, but we don't require them on all functions.
+# Require them only on long functions (for some value of long).
+# [missing-docstring]
+docstring-min-length=10
+
+# Allow longer methods than the default.
+# [invalid-name]
+method-rgx=[a-z_][a-z0-9_]{2,35}$
+
+# Allow module names containing a dash (but no underscore or uppercase letter).
+# They are whole programs, not meant to be included by another module.
+# [invalid-name]
+module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+)|[a-z][-0-9a-z]+)$
+
+# Some functions don't need docstrings.
+# [missing-docstring]
+no-docstring-rgx=(run_)main$
+
+# We're ok with short local or global variable names.
+# [invalid-name]
+variable-rgx=[a-z_][a-z0-9_]*$
+
+[DESIGN]
+# Allow more than the default 7 attributes.
+# [too-many-instance-attributes]
+max-attributes=15
+
+[FORMAT]
+# Allow longer modules than the default recommended maximum.
+# [too-many-lines]
+max-module-lines=2000
+
+[MESSAGES CONTROL]
+disable=
+
+[REPORTS]
+# Don't diplay statistics. Just the facts.
+reports=no
+
+[VARIABLES]
+# Allow unused variables if their name starts with an underscore.
+# [unused-argument]
+dummy-variables-rgx=_.*
diff --git a/.travis.yml b/.travis.yml
index 4fc31c9..c45d408 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -31,7 +31,8 @@
- tests/scripts/travis-log-failure.sh
env:
global:
- secure: "barHldniAfXyoWOD/vcO+E6/Xm4fmcaUoC9BeKW+LwsHqlDMLvugaJnmLXkSpkbYhVL61Hzf3bo0KPJn88AFc5Rkf8oYHPjH4adMnVXkf3B9ghHCgznqHsAH3choo6tnPxaFgOwOYmLGb382nQxfE5lUdvnM/W/psQjWt66A1+k="
+ - SEED=1
+ - secure: "barHldniAfXyoWOD/vcO+E6/Xm4fmcaUoC9BeKW+LwsHqlDMLvugaJnmLXkSpkbYhVL61Hzf3bo0KPJn88AFc5Rkf8oYHPjH4adMnVXkf3B9ghHCgznqHsAH3choo6tnPxaFgOwOYmLGb382nQxfE5lUdvnM/W/psQjWt66A1+k="
addons:
apt:
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 99bf31f..d4a236f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -179,6 +179,7 @@
add_subdirectory(library)
add_subdirectory(include)
+add_subdirectory(tinycrypt)
if(ENABLE_PROGRAMS)
add_subdirectory(programs)
diff --git a/ChangeLog b/ChangeLog
index 66ecf97..978b8b5 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -2,6 +2,47 @@
= mbed TLS 2.x.x branch released xxxx-xx-xx
+Security
+ * Make mbedtls_ecdh_get_params return an error if the second key
+ belongs to a different group from the first. Before, if an application
+ passed keys that belonged to different group, the first key's data was
+ interpreted according to the second group, which could lead to either
+ an error or a meaningless output from mbedtls_ecdh_get_params. In the
+ latter case, this could expose at most 5 bits of the private key.
+
+Bugfix
+ * Server's RSA certificate in certs.c was SHA-1 signed. In the default
+ mbedTLS configuration only SHA-2 signed certificates are accepted.
+ This certificate is used in the demo server programs, which lead the
+ client programs to fail at the peer's certificate verification
+ due to an unacceptable hash signature. The certificate has been
+ updated to one that is SHA-256 signed. Fix contributed by
+ Illya Gerasymchuk.
+ * Fix private key DER output in the key_app_writer example. File contents
+ were shifted by one byte, creating an invalid ASN.1 tag. Fixed by
+ Christian Walther in #2239.
+ * Fix potential memory leak in X.509 self test. Found and fixed by
+ Junhwan Park, #2106.
+ * Reduce stack usage of hkdf tests. Fixes #2195.
+ * Fix 1-byte buffer overflow in mbedtls_mpi_write_string() when
+ used with negative inputs. Found by Guido Vranken in #2404. Credit to
+ OSS-Fuzz.
+ * Fix bugs in the AEAD test suite which would be exposed by ciphers which
+ either used both encrypt and decrypt key schedules, or which perform padding.
+ GCM and CCM were not affected. Fixed by Jack Lloyd.
+ * Fix incorrect default port number in ssl_mail_client example's usage.
+ Found and fixed by irwir. #2337
+
+Changes
+ * Return from various debugging routines immediately if the
+ provided SSL context is unset.
+ * Remove dead code from bignum.c in the default configuration.
+ Found by Coverity, reported and fixed by Peter Kolbus (Garmin). Fixes #2309.
+ * Add test for minimal value of MBEDTLS_MPI_WINDOW_SIZE to all.sh.
+ Contributed by Peter Kolbus (Garmin).
+
+= mbed TLS 2.16.1 branch released 2019-03-19
+
Features
* Add MBEDTLS_REMOVE_3DES_CIPHERSUITES to allow removing 3DES ciphersuites
from the default list (enabled by default). See
@@ -37,16 +78,6 @@
extensions in CSRs and CRTs that caused these bitstrings to not be encoded
correctly as trailing zeroes were not accounted for as unused bits in the
leading content octet. Fixes #1610.
- * Server's RSA certificate in certs.c was SHA-1 signed. In the default
- mbedTLS configuration only SHA-2 signed certificates are accepted.
- This certificate is used in the demo server programs, which lead the
- client programs to fail at the peer's certificate verification
- due to an unacceptable hash signature. The certificate has been
- updated to one that is SHA-256 signed. Fix contributed by
- Illya Gerasymchuk.
- * Fix private key DER output in the key_app_writer example. File contents
- were shifted by one byte, creating an invalid ASN.1 tag. Fixed by
- Christian Walther in #2239.
Changes
* Include configuration file in all header files that use configuration,
@@ -62,12 +93,6 @@
been disabled for lack of a sufficiently recent version of GnuTLS on the CI.
* Ciphersuites based on 3DES now have the lowest priority by default when
they are enabled.
- * Return from various debugging routines immediately if the
- provided SSL context is unset.
- * Remove dead code from bignum.c in the default configuration.
- Found by Coverity, reported and fixed by Peter Kolbus (Garmin). Fixes #2309.
- * Add test for minimal value of MBEDTLS_MPI_WINDOW_SIZE to all.sh.
- Contributed by Peter Kolbus (Garmin).
= mbed TLS 2.16.0 branch released 2018-12-21
diff --git a/README.md b/README.md
index d7a0e9d..94ea84b 100644
--- a/README.md
+++ b/README.md
@@ -35,7 +35,7 @@
make check
-The tests need Perl to be built and run. If you don't have Perl installed, you can skip building the tests with:
+The tests need Python to be built and Perl to be run. If you don't have one of them installed, you can skip building the tests with:
make no_test
@@ -65,7 +65,7 @@
make test
-The test suites need Perl to be built. If you don't have Perl installed, you'll want to disable the test suites with:
+The test suites need Python to be built and Perl to be executed. If you don't have one of these installed, you'll want to disable the test suites with:
cmake -DENABLE_TESTING=Off /path/to/mbedtls_source
@@ -133,7 +133,7 @@
The build files for Microsoft Visual Studio are generated for Visual Studio 2010.
-The solution file `mbedTLS.sln` contains all the basic projects needed to build the library and all the programs. The files in tests are not generated and compiled, as these need a perl environment as well. However, the selftest program in `programs/test/` is still available.
+The solution file `mbedTLS.sln` contains all the basic projects needed to build the library and all the programs. The files in tests are not generated and compiled, as these need Python and perl environments as well. However, the selftest program in `programs/test/` is still available.
Example programs
----------------
@@ -143,7 +143,7 @@
Tests
-----
-Mbed TLS includes an elaborate test suite in `tests/` that initially requires Perl to generate the tests files (e.g. `test\_suite\_mpi.c`). These files are generated from a `function file` (e.g. `suites/test\_suite\_mpi.function`) and a `data file` (e.g. `suites/test\_suite\_mpi.data`). The `function file` contains the test functions. The `data file` contains the test cases, specified as parameters that will be passed to the test function.
+Mbed TLS includes an elaborate test suite in `tests/` that initially requires Python to generate the tests files (e.g. `test\_suite\_mpi.c`). These files are generated from a `function file` (e.g. `suites/test\_suite\_mpi.function`) and a `data file` (e.g. `suites/test\_suite\_mpi.data`). The `function file` contains the test functions. The `data file` contains the test cases, specified as parameters that will be passed to the test function.
For machines with a Unix shell and OpenSSL (and optionally GnuTLS) installed, additional test scripts are available:
diff --git a/circle.yml b/circle.yml
deleted file mode 100644
index eaed02a..0000000
--- a/circle.yml
+++ /dev/null
@@ -1,44 +0,0 @@
-# Purpose:
-# - To test and prove that a new commit in the mbed TLS repository builds
-# and integrates with mbed-os properly.
-# AND
-# - To test and prove that the current development head of mbed TLS builds
-# and integrates with the current mbed-os master branch.
-#
-# The script fetches all the prerequisites and builds the mbed TLS 'tls-client'
-# example. This script is triggered by every commit and once each night and the
-# exact behaviour depends on how it was triggered:
-# - If it is a nightly build then it builds the mbed TLS development head with
-# mbed-os master.
-# - If it was triggered by the commit, then it builds the example with mbed TLS
-# at that commit and mbed-os at the commit pointed by mbed-os.lib in the
-# example repository.
-
-test:
- override:
- - cd ../mbed-os-example-tls/tls-client/ && mbed compile -m K64F -t GCC_ARM -c
-
-dependencies:
- pre:
- # Install gcc-arm
- - cd .. && wget "https://launchpad.net/gcc-arm-embedded/4.9/4.9-2015-q3-update/+download/gcc-arm-none-eabi-4_9-2015q3-20150921-linux.tar.bz2"
- - cd .. && tar -xvjf gcc-arm-none-eabi-4_9-2015q3-20150921-linux.tar.bz2
- - ln -s ../gcc-arm-none-eabi-4_9-2015q3/bin/* ../bin/
- # Install mbed-cli
- - cd ../ && git clone https://github.com/ARMmbed/mbed-cli.git
- - cd ../mbed-cli && sudo -H pip install -e .
- # Get the sample application
- - cd ../ && git clone git@github.com:ARMmbed/mbed-os-example-tls.git
- # Get mbed-os
- - cd ../mbed-os-example-tls/tls-client && mbed deploy
- # Update mbed-os to master only if it is a nightly build
- - >
- if [ -n "${RUN_NIGHTLY_BUILD}" ]; then
- cd ../mbed-os-example-tls/tls-client/mbed-os/ && mbed update master;
- fi
- # Import mbedtls current revision
- - ln -s ../../../../../../../mbedtls/ ../mbed-os-example-tls/tls-client/mbed-os/features/mbedtls/importer/TARGET_IGNORE/mbedtls
- - cd ../mbed-os-example-tls/tls-client/mbed-os/features/mbedtls/importer/ && make
- override:
- # Install the missing python packages
- - cd ../mbed-os-example-tls/tls-client/mbed-os/ && sudo -H pip install -r requirements.txt
diff --git a/doxygen/input/doc_mainpage.h b/doxygen/input/doc_mainpage.h
index ffc3cec..6345ddc 100644
--- a/doxygen/input/doc_mainpage.h
+++ b/doxygen/input/doc_mainpage.h
@@ -24,7 +24,7 @@
*/
/**
- * @mainpage mbed TLS v2.16.0 source code documentation
+ * @mainpage mbed TLS v2.16.1 source code documentation
*
* This documentation describes the internal structure of mbed TLS. It was
* automatically generated from specially formatted comment blocks in
diff --git a/doxygen/mbedtls.doxyfile b/doxygen/mbedtls.doxyfile
index 574db8d..e5d2dda 100644
--- a/doxygen/mbedtls.doxyfile
+++ b/doxygen/mbedtls.doxyfile
@@ -28,7 +28,7 @@
# identify the project. Note that if you do not use Doxywizard you need
# to put quotes around the project name if it contains spaces.
-PROJECT_NAME = "mbed TLS v2.16.0"
+PROJECT_NAME = "mbed TLS v2.16.1"
# The PROJECT_NUMBER tag can be used to enter a project or revision number.
# This could be handy for archiving the generated documentation or
@@ -696,7 +696,9 @@
# Note that relative paths are relative to the directory from which doxygen is
# run.
-EXCLUDE =
+EXCLUDE = ./../include/tinycrypt/ecc.h \
+ ./../include/tinycrypt/ecc_dh.h \
+ ./../include/tinycrypt/ecc_dsa.h
# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded
diff --git a/include/CMakeLists.txt b/include/CMakeLists.txt
index 1b581a5..862fa92 100644
--- a/include/CMakeLists.txt
+++ b/include/CMakeLists.txt
@@ -3,6 +3,7 @@
if(INSTALL_MBEDTLS_HEADERS)
file(GLOB headers "mbedtls/*.h")
+ file(GLOB headers "tinycrypt/*.h")
install(FILES ${headers}
DESTINATION include/mbedtls
diff --git a/include/mbedtls/check_config.h b/include/mbedtls/check_config.h
index b86e580..bc94b77 100644
--- a/include/mbedtls/check_config.h
+++ b/include/mbedtls/check_config.h
@@ -87,6 +87,10 @@
#error "MBEDTLS_CMAC_C defined, but not all prerequisites"
#endif
+#if defined(MBEDTLS_USE_UECC) && defined(MBEDTLS_NO_64BIT_MULTIPLICATION)
+#error "MBEDTLS_USE_UECC defined, but it cannot be defined with MBEDTLS_NO_64BIT_MULTIPLICATION"
+#endif
+
#if defined(MBEDTLS_NIST_KW_C) && \
( !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CIPHER_C) )
#error "MBEDTLS_NIST_KW_C defined, but not all prerequisites"
@@ -591,6 +595,11 @@
#error "MBEDTLS_SSL_DTLS_ANTI_REPLAY defined, but not all prerequisites"
#endif
+#if defined(MBEDTLS_SSL_CID) && \
+ ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) )
+#error "MBEDTLS_SSL_CID defined, but not all prerequisites"
+#endif
+
#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) && \
( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) )
#error "MBEDTLS_SSL_DTLS_BADMAC_LIMIT defined, but not all prerequisites"
diff --git a/include/mbedtls/config.h b/include/mbedtls/config.h
index 654f972..24501ab 100644
--- a/include/mbedtls/config.h
+++ b/include/mbedtls/config.h
@@ -1270,6 +1270,30 @@
#define MBEDTLS_SSL_ALL_ALERT_MESSAGES
/**
+ * \def MBEDTLS_SSL_CID
+ *
+ * Enable support for the DTLS Connection ID extension
+ * (version draft-ietf-tls-dtls-connection-id-04)
+ * which allows to identify DTLS connections across changes
+ * in the underlying transport.
+ *
+ * Setting this option enables the SSL APIs `mbedtls_ssl_set_cid()`
+ * and `mbedtls_ssl_get_peer_cid()`. See their documentation for more
+ * information.
+ *
+ * \warning The Connection ID extension is still in draft state.
+ * We make no stability promises for the availability
+ * or the shape of the API controlled by this option.
+ *
+ * See also MBEDTLS_SSL_CID_OUT_LEN_MAX and MBEDTLS_SSL_CID_IN_LEN_MAX.
+ *
+ * Requires: MBEDTLS_SSL_PROTO_DTLS
+ *
+ * Uncomment to enable the Connection ID extension.
+ */
+#define MBEDTLS_SSL_CID
+
+/**
* \def MBEDTLS_SSL_ASYNC_PRIVATE
*
* Enable asynchronous external private key operations in SSL. This allows
@@ -2255,6 +2279,20 @@
#define MBEDTLS_ECP_C
/**
+ * \def MBEDTLS_USE_UECC
+ *
+ * Enable the tinycrypt ECC library.
+ *
+ * Module: tinycrypt/ecc.c
+ * tinycrypt/ecc_dh.c
+ * tinycrypt/ecc_dsa.c
+ *
+ * This module provides alternative ECC handling functions replacing
+ * native MBEDTLS ECP module.
+ */
+//#define MBEDTLS_USE_UECC
+
+/**
* \def MBEDTLS_ENTROPY_C
*
* Enable the platform-specific entropy code.
@@ -3145,6 +3183,20 @@
*/
//#define MBEDTLS_SSL_IN_CONTENT_LEN 16384
+/** \def MBEDTLS_SSL_CID_IN_LEN_MAX
+ *
+ * The maximum length of CIDs used for incoming DTLS messages.
+ *
+ */
+//#define MBEDTLS_SSL_CID_IN_LEN_MAX 32
+
+/** \def MBEDTLS_SSL_CID_OUT_LEN_MAX
+ *
+ * The maximum length of CIDs used for outgoing DTLS messages.
+ *
+ */
+//#define MBEDTLS_SSL_CID_OUT_LEN_MAX 32
+
/** \def MBEDTLS_SSL_OUT_CONTENT_LEN
*
* Maximum length (in bytes) of outgoing plaintext fragments.
diff --git a/include/mbedtls/ecp.h b/include/mbedtls/ecp.h
index 2401778..065a4cc 100644
--- a/include/mbedtls/ecp.h
+++ b/include/mbedtls/ecp.h
@@ -482,7 +482,7 @@
*
* \note After this function is called, domain parameters
* for various ECP groups can be loaded through the
- * mbedtls_ecp_load() or mbedtls_ecp_tls_read_group()
+ * mbedtls_ecp_group_load() or mbedtls_ecp_tls_read_group()
* functions.
*/
void mbedtls_ecp_group_init( mbedtls_ecp_group *grp );
diff --git a/include/mbedtls/ssl.h b/include/mbedtls/ssl.h
index 8106bb4..dae4558 100644
--- a/include/mbedtls/ssl.h
+++ b/include/mbedtls/ssl.h
@@ -156,6 +156,9 @@
#define MBEDTLS_SSL_EXTENDED_MS_DISABLED 0
#define MBEDTLS_SSL_EXTENDED_MS_ENABLED 1
+#define MBEDTLS_SSL_CID_DISABLED 0
+#define MBEDTLS_SSL_CID_ENABLED 1
+
#define MBEDTLS_SSL_ETM_DISABLED 0
#define MBEDTLS_SSL_ETM_ENABLED 1
@@ -252,6 +255,17 @@
#define MBEDTLS_SSL_DTLS_MAX_BUFFERING 32768
#endif
+/*
+ * Maximum length of CIDs for incoming and outgoing messages.
+ */
+#if !defined(MBEDTLS_SSL_CID_IN_LEN_MAX)
+#define MBEDTLS_SSL_CID_IN_LEN_MAX 32
+#endif
+
+#if !defined(MBEDTLS_SSL_CID_OUT_LEN_MAX)
+#define MBEDTLS_SSL_CID_OUT_LEN_MAX 32
+#endif
+
/* \} name SECTION: Module settings */
/*
@@ -1396,6 +1410,135 @@
mbedtls_ssl_recv_timeout_t *f_recv_timeout );
#if defined(MBEDTLS_SSL_PROTO_DTLS)
+
+#if defined(MBEDTLS_SSL_CID)
+
+
+/**
+ * \brief (STUB) Configure the use of the Connection ID (CID)
+ * extension in the next handshake.
+ *
+ * Reference:
+ * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-04
+ *
+ * The DTLS CID extension allows to reliably associate
+ * DTLS records to DTLS connections across changes in the
+ * underlying transport (changed IP+Port metadata) by adding
+ * explicit connection identifiers (CIDs) to the headers of
+ * encrypted DTLS records. The desired CIDs are configured
+ * by the application layer and are exchanged in new
+ * `ClientHello` / `ServerHello` extensions during the
+ * handshake, where each side indicates the CID it wants the
+ * peer to use when writing encrypted messages. The CIDs are
+ * put to use once records get encrypted: the stack discards
+ * any incoming records that don't include the configured CID
+ * in their header, and adds the peer's requested CID to the
+ * headers of outgoing messages.
+ *
+ * This API allows to enable/disable the use of the CID
+ * extension in the next handshake and to set the value of
+ * the CID to be used for incoming messages.
+ *
+ * \warning The current implementation of this API does nothing!
+ * It is included solely to allow review and coding against
+ * the new Connection CID API.
+ * The actual implementation will be added in the future.
+ *
+ * \param ssl The SSL context to configure. This must be initialized.
+ * \param enable This value determines whether the CID extension should
+ * be used or not. Possible values are:
+ * - MBEDTLS_SSL_CID_ENABLED to enable the use of the CID.
+ * - MBEDTLS_SSL_CID_DISABLED (default) to disable the use
+ * of the CID.
+ * \param own_cid The address of the readable buffer holding the CID we want
+ * the peer to use when sending encrypted messages to us.
+ * This may be \c NULL if \p own_cid_len is \c 0.
+ * This parameter is unused if \p enabled is set to
+ * MBEDTLS_SSL_CID_DISABLED.
+ * \param own_cid_len The length of \p own_cid.
+ * This parameter is unused if \p enabled is set to
+ * MBEDTLS_SSL_CID_DISABLED.
+ *
+ * \note This CID configuration applies to subsequent handshakes
+ * performed on the SSL context \p ssl, but does not trigger
+ * one. You still have to call `mbedtls_ssl_handshake()`
+ * (for the initial handshake) or `mbedtls_ssl_renegotiate()`
+ * (for a renegotiation handshake) explicitly after a
+ * successful call to this function to run the handshake.
+ *
+ * \note This call cannot guarantee that the use of the CID
+ * will be successfully negotiated in the next handshake,
+ * because the peer might not support it. Specifically:
+ * - On the Client, enabling the use of the CID through
+ * this call implies that the `ClientHello` in the next
+ * handshake will include the CID extension, thereby
+ * offering the use of the CID to the server. Only if
+ * the `ServerHello` contains the CID extension, too,
+ * the CID extension will actually be put to use.
+ * - On the Server, enabling the use of the CID through
+ * this call implies that that the server will look for
+ * the CID extension in a `ClientHello` from the client,
+ * and, if present, reply with a CID extension in its
+ * `ServerHello`.
+ *
+ * \note To check whether the use of the CID was negotiated
+ * after the subsequent handshake has completed, please
+ * use the API mbedtls_ssl_get_peer_cid().
+ *
+ * \warning If the use of the CID extension is enabled in this call
+ * and the subsequent handshake negotiates its use, Mbed TLS
+ * will silently drop every packet whose CID does not match
+ * the CID configured in \p own_cid. It is the responsibility
+ * of the user to adapt the underlying transport to take care
+ * of CID-based demultiplexing before handing datagrams to
+ * Mbed TLS.
+ *
+ * \return \c 0 on success. In this case, the CID configuration
+ * applies to the next handshake.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ssl_set_cid( mbedtls_ssl_context *ssl,
+ int enable,
+ unsigned char const *own_cid,
+ size_t own_cid_len );
+
+/**
+ * \brief (STUB) Get information about the current use of the
+ * CID extension.
+ *
+ * \warning The current implementation of this API does nothing
+ * except setting `*enabled` to MBEDTLS_SSL_CID_DISABLED!
+ * It is included solely to allow review and coding against
+ * the new Connection CID API.
+ * The actual implementation will be added in the future.
+ *
+ * \param ssl The SSL context to query.
+ * \param enabled The address at which to store whether the CID extension
+ * is currently in use or not. If the CID is in use,
+ * `*enabled` is set to MBEDTLS_SSL_CID_ENABLED;
+ * otherwise, it is set to MBEDTLS_SSL_CID_DISABLED.
+ * \param peer_cid The address of the buffer in which to store the CID
+ * chosen by the peer (if the CID extension is used).
+ * \param peer_cid_len The address at which to store the size of the CID
+ * chosen by the peer (if the CID extension is used).
+ * This is also the number of Bytes in \p peer_cid that
+ * have been written.
+ *
+ * \note This applies to the state of the CID negotiated in
+ * the last complete handshake. If a handshake is in
+ * progress, this function will attempt to complete
+ * the handshake first.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ssl_get_peer_cid( mbedtls_ssl_context *ssl,
+ int *enabled,
+ unsigned char peer_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ],
+ size_t *peer_cid_len );
+
+#endif /* MBEDTLS_SSL_CID */
+
/**
* \brief Set the Maximum Tranport Unit (MTU).
* Special value: 0 means unset (no limit).
diff --git a/include/mbedtls/version.h b/include/mbedtls/version.h
index 56e7398..cc736e1 100644
--- a/include/mbedtls/version.h
+++ b/include/mbedtls/version.h
@@ -40,16 +40,16 @@
*/
#define MBEDTLS_VERSION_MAJOR 2
#define MBEDTLS_VERSION_MINOR 16
-#define MBEDTLS_VERSION_PATCH 0
+#define MBEDTLS_VERSION_PATCH 1
/**
* The single version number has the following structure:
* MMNNPP00
* Major version | Minor version | Patch version
*/
-#define MBEDTLS_VERSION_NUMBER 0x02100000
-#define MBEDTLS_VERSION_STRING "2.16.0"
-#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.16.0"
+#define MBEDTLS_VERSION_NUMBER 0x02100100
+#define MBEDTLS_VERSION_STRING "2.16.1"
+#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.16.1"
#if defined(MBEDTLS_VERSION_C)
diff --git a/include/tinycrypt/ecc.h b/include/tinycrypt/ecc.h
new file mode 100644
index 0000000..ede7544
--- /dev/null
+++ b/include/tinycrypt/ecc.h
@@ -0,0 +1,547 @@
+/* ecc.h - TinyCrypt interface to common ECC functions */
+
+/* Copyright (c) 2014, Kenneth MacKay
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (C) 2017 by Intel Corporation, All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @file
+ * @brief -- Interface to common ECC functions.
+ *
+ * Overview: This software is an implementation of common functions
+ * necessary to elliptic curve cryptography. This implementation uses
+ * curve NIST p-256.
+ *
+ * Security: The curve NIST p-256 provides approximately 128 bits of security.
+ *
+ */
+
+#if defined(MBEDTLS_USE_UECC)
+#ifndef __TC_UECC_H__
+#define __TC_UECC_H__
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Word size (4 bytes considering 32-bits architectures) */
+#define uECC_WORD_SIZE 4
+
+/* setting max number of calls to prng: */
+#ifndef uECC_RNG_MAX_TRIES
+#define uECC_RNG_MAX_TRIES 64
+#endif
+
+/* defining data types to store word and bit counts: */
+typedef int8_t wordcount_t;
+typedef int16_t bitcount_t;
+/* defining data type for comparison result: */
+typedef int8_t cmpresult_t;
+/* defining data type to store ECC coordinate/point in 32bits words: */
+typedef unsigned int uECC_word_t;
+/* defining data type to store an ECC coordinate/point in 64bits words: */
+typedef uint64_t uECC_dword_t;
+
+/* defining masks useful for ecc computations: */
+#define HIGH_BIT_SET 0x80000000
+#define uECC_WORD_BITS 32
+#define uECC_WORD_BITS_SHIFT 5
+#define uECC_WORD_BITS_MASK 0x01F
+
+/* Number of words of 32 bits to represent an element of the the curve p-256: */
+#define NUM_ECC_WORDS 8
+/* Number of bytes to represent an element of the the curve p-256: */
+#define NUM_ECC_BYTES (uECC_WORD_SIZE*NUM_ECC_WORDS)
+
+/* structure that represents an elliptic curve (e.g. p256):*/
+struct uECC_Curve_t;
+typedef const struct uECC_Curve_t * uECC_Curve;
+struct uECC_Curve_t {
+ wordcount_t num_words;
+ wordcount_t num_bytes;
+ bitcount_t num_n_bits;
+ uECC_word_t p[NUM_ECC_WORDS];
+ uECC_word_t n[NUM_ECC_WORDS];
+ uECC_word_t G[NUM_ECC_WORDS * 2];
+ uECC_word_t b[NUM_ECC_WORDS];
+ void (*double_jacobian)(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * Z1,
+ uECC_Curve curve);
+ void (*x_side)(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve);
+ void (*mmod_fast)(uECC_word_t *result, uECC_word_t *product);
+};
+
+/*
+ * @brief computes doubling of point ion jacobian coordinates, in place.
+ * @param X1 IN/OUT -- x coordinate
+ * @param Y1 IN/OUT -- y coordinate
+ * @param Z1 IN/OUT -- z coordinate
+ * @param curve IN -- elliptic curve
+ */
+void double_jacobian_default(uECC_word_t * X1, uECC_word_t * Y1,
+ uECC_word_t * Z1, uECC_Curve curve);
+
+/*
+ * @brief Computes x^3 + ax + b. result must not overlap x.
+ * @param result OUT -- x^3 + ax + b
+ * @param x IN -- value of x
+ * @param curve IN -- elliptic curve
+ */
+void x_side_default(uECC_word_t *result, const uECC_word_t *x,
+ uECC_Curve curve);
+
+/*
+ * @brief Computes result = product % curve_p
+ * from http://www.nsa.gov/ia/_files/nist-routines.pdf
+ * @param result OUT -- product % curve_p
+ * @param product IN -- value to be reduced mod curve_p
+ */
+void vli_mmod_fast_secp256r1(unsigned int *result, unsigned int *product);
+
+/* Bytes to words ordering: */
+#define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e
+#define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a
+#define BITS_TO_WORDS(num_bits) \
+ ((num_bits + ((uECC_WORD_SIZE * 8) - 1)) / (uECC_WORD_SIZE * 8))
+#define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8)
+
+/* definition of curve NIST p-256: */
+static const struct uECC_Curve_t curve_secp256r1 = {
+ NUM_ECC_WORDS,
+ NUM_ECC_BYTES,
+ 256, /* num_n_bits */ {
+ BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
+ BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00),
+ BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
+ BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF)
+ }, {
+ BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3),
+ BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC),
+ BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
+ BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF)
+ }, {
+ BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4),
+ BYTES_TO_WORDS_8(A0, 33, EB, 2D, 81, 7D, 03, 77),
+ BYTES_TO_WORDS_8(F2, 40, A4, 63, E5, E6, BC, F8),
+ BYTES_TO_WORDS_8(47, 42, 2C, E1, F2, D1, 17, 6B),
+
+ BYTES_TO_WORDS_8(F5, 51, BF, 37, 68, 40, B6, CB),
+ BYTES_TO_WORDS_8(CE, 5E, 31, 6B, 57, 33, CE, 2B),
+ BYTES_TO_WORDS_8(16, 9E, 0F, 7C, 4A, EB, E7, 8E),
+ BYTES_TO_WORDS_8(9B, 7F, 1A, FE, E2, 42, E3, 4F)
+ }, {
+ BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B),
+ BYTES_TO_WORDS_8(F6, B0, 53, CC, B0, 06, 1D, 65),
+ BYTES_TO_WORDS_8(BC, 86, 98, 76, 55, BD, EB, B3),
+ BYTES_TO_WORDS_8(E7, 93, 3A, AA, D8, 35, C6, 5A)
+ },
+ &double_jacobian_default,
+ &x_side_default,
+ &vli_mmod_fast_secp256r1
+};
+
+uECC_Curve uECC_secp256r1(void);
+
+/*
+ * @brief Generates a random integer in the range 0 < random < top.
+ * Both random and top have num_words words.
+ * @param random OUT -- random integer in the range 0 < random < top
+ * @param top IN -- upper limit
+ * @param num_words IN -- number of words
+ * @return a random integer in the range 0 < random < top
+ */
+int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top,
+ wordcount_t num_words);
+
+
+/* uECC_RNG_Function type
+ * The RNG function should fill 'size' random bytes into 'dest'. It should
+ * return 1 if 'dest' was filled with random data, or 0 if the random data could
+ * not be generated. The filled-in values should be either truly random, or from
+ * a cryptographically-secure PRNG.
+ *
+ * A correctly functioning RNG function must be set (using uECC_set_rng())
+ * before calling uECC_make_key() or uECC_sign().
+ *
+ * Setting a correctly functioning RNG function improves the resistance to
+ * side-channel attacks for uECC_shared_secret().
+ *
+ * A correct RNG function is set by default. If you are building on another
+ * POSIX-compliant system that supports /dev/random or /dev/urandom, you can
+ * define uECC_POSIX to use the predefined RNG.
+ */
+typedef int(*uECC_RNG_Function)(uint8_t *dest, unsigned int size);
+
+/*
+ * @brief Set the function that will be used to generate random bytes. The RNG
+ * function should return 1 if the random data was generated, or 0 if the random
+ * data could not be generated.
+ *
+ * @note On platforms where there is no predefined RNG function, this must be
+ * called before uECC_make_key() or uECC_sign() are used.
+ *
+ * @param rng_function IN -- function that will be used to generate random bytes
+ */
+void uECC_set_rng(uECC_RNG_Function rng_function);
+
+/*
+ * @brief provides current uECC_RNG_Function.
+ * @return Returns the function that will be used to generate random bytes.
+ */
+uECC_RNG_Function uECC_get_rng(void);
+
+/*
+ * @brief computes the size of a private key for the curve in bytes.
+ * @param curve IN -- elliptic curve
+ * @return size of a private key for the curve in bytes.
+ */
+int uECC_curve_private_key_size(uECC_Curve curve);
+
+/*
+ * @brief computes the size of a public key for the curve in bytes.
+ * @param curve IN -- elliptic curve
+ * @return the size of a public key for the curve in bytes.
+ */
+int uECC_curve_public_key_size(uECC_Curve curve);
+
+/*
+ * @brief Compute the corresponding public key for a private key.
+ * @param private_key IN -- The private key to compute the public key for
+ * @param public_key OUT -- Will be filled in with the corresponding public key
+ * @param curve
+ * @return Returns 1 if key was computed successfully, 0 if an error occurred.
+ */
+int uECC_compute_public_key(const uint8_t *private_key,
+ uint8_t *public_key, uECC_Curve curve);
+
+/*
+ * @brief Compute public-key.
+ * @return corresponding public-key.
+ * @param result OUT -- public-key
+ * @param private_key IN -- private-key
+ * @param curve IN -- elliptic curve
+ */
+uECC_word_t EccPoint_compute_public_key(uECC_word_t *result,
+ uECC_word_t *private_key, uECC_Curve curve);
+
+/*
+ * @brief Regularize the bitcount for the private key so that attackers cannot
+ * use a side channel attack to learn the number of leading zeros.
+ * @return Regularized k
+ * @param k IN -- private-key
+ * @param k0 IN/OUT -- regularized k
+ * @param k1 IN/OUT -- regularized k
+ * @param curve IN -- elliptic curve
+ */
+uECC_word_t regularize_k(const uECC_word_t * const k, uECC_word_t *k0,
+ uECC_word_t *k1, uECC_Curve curve);
+
+/*
+ * @brief Point multiplication algorithm using Montgomery's ladder with co-Z
+ * coordinates. See http://eprint.iacr.org/2011/338.pdf.
+ * @note Result may overlap point.
+ * @param result OUT -- returns scalar*point
+ * @param point IN -- elliptic curve point
+ * @param scalar IN -- scalar
+ * @param initial_Z IN -- initial value for z
+ * @param num_bits IN -- number of bits in scalar
+ * @param curve IN -- elliptic curve
+ */
+void EccPoint_mult(uECC_word_t * result, const uECC_word_t * point,
+ const uECC_word_t * scalar, const uECC_word_t * initial_Z,
+ bitcount_t num_bits, uECC_Curve curve);
+
+/*
+ * @brief Constant-time comparison to zero - secure way to compare long integers
+ * @param vli IN -- very long integer
+ * @param num_words IN -- number of words in the vli
+ * @return 1 if vli == 0, 0 otherwise.
+ */
+uECC_word_t uECC_vli_isZero(const uECC_word_t *vli, wordcount_t num_words);
+
+/*
+ * @brief Check if 'point' is the point at infinity
+ * @param point IN -- elliptic curve point
+ * @param curve IN -- elliptic curve
+ * @return if 'point' is the point at infinity, 0 otherwise.
+ */
+uECC_word_t EccPoint_isZero(const uECC_word_t *point, uECC_Curve curve);
+
+/*
+ * @brief computes the sign of left - right, in constant time.
+ * @param left IN -- left term to be compared
+ * @param right IN -- right term to be compared
+ * @param num_words IN -- number of words
+ * @return the sign of left - right
+ */
+cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right,
+ wordcount_t num_words);
+
+/*
+ * @brief computes sign of left - right, not in constant time.
+ * @note should not be used if inputs are part of a secret
+ * @param left IN -- left term to be compared
+ * @param right IN -- right term to be compared
+ * @param num_words IN -- number of words
+ * @return the sign of left - right
+ */
+cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left, const uECC_word_t *right,
+ wordcount_t num_words);
+
+/*
+ * @brief Computes result = (left - right) % mod.
+ * @note Assumes that (left < mod) and (right < mod), and that result does not
+ * overlap mod.
+ * @param result OUT -- (left - right) % mod
+ * @param left IN -- leftright term in modular subtraction
+ * @param right IN -- right term in modular subtraction
+ * @param mod IN -- mod
+ * @param num_words IN -- number of words
+ */
+void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, const uECC_word_t *mod,
+ wordcount_t num_words);
+
+/*
+ * @brief Computes P' = (x1', y1', Z3), P + Q = (x3, y3, Z3) or
+ * P => P', Q => P + Q
+ * @note assumes Input P = (x1, y1, Z), Q = (x2, y2, Z)
+ * @param X1 IN -- x coordinate of P
+ * @param Y1 IN -- y coordinate of P
+ * @param X2 IN -- x coordinate of Q
+ * @param Y2 IN -- y coordinate of Q
+ * @param curve IN -- elliptic curve
+ */
+void XYcZ_add(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * X2,
+ uECC_word_t * Y2, uECC_Curve curve);
+
+/*
+ * @brief Computes (x1 * z^2, y1 * z^3)
+ * @param X1 IN -- previous x1 coordinate
+ * @param Y1 IN -- previous y1 coordinate
+ * @param Z IN -- z value
+ * @param curve IN -- elliptic curve
+ */
+void apply_z(uECC_word_t * X1, uECC_word_t * Y1, const uECC_word_t * const Z,
+ uECC_Curve curve);
+
+/*
+ * @brief Check if bit is set.
+ * @return Returns nonzero if bit 'bit' of vli is set.
+ * @warning It is assumed that the value provided in 'bit' is within the
+ * boundaries of the word-array 'vli'.
+ * @note The bit ordering layout assumed for vli is: {31, 30, ..., 0},
+ * {63, 62, ..., 32}, {95, 94, ..., 64}, {127, 126,..., 96} for a vli consisting
+ * of 4 uECC_word_t elements.
+ */
+uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit);
+
+/*
+ * @brief Computes result = product % mod, where product is 2N words long.
+ * @param result OUT -- product % mod
+ * @param mod IN -- module
+ * @param num_words IN -- number of words
+ * @warning Currently only designed to work for curve_p or curve_n.
+ */
+void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product,
+ const uECC_word_t *mod, wordcount_t num_words);
+
+/*
+ * @brief Computes modular product (using curve->mmod_fast)
+ * @param result OUT -- (left * right) mod % curve_p
+ * @param left IN -- left term in product
+ * @param right IN -- right term in product
+ * @param curve IN -- elliptic curve
+ */
+void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, uECC_Curve curve);
+
+/*
+ * @brief Computes result = left - right.
+ * @note Can modify in place.
+ * @param result OUT -- left - right
+ * @param left IN -- left term in subtraction
+ * @param right IN -- right term in subtraction
+ * @param num_words IN -- number of words
+ * @return borrow
+ */
+uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, wordcount_t num_words);
+
+/*
+ * @brief Constant-time comparison function(secure way to compare long ints)
+ * @param left IN -- left term in comparison
+ * @param right IN -- right term in comparison
+ * @param num_words IN -- number of words
+ * @return Returns 0 if left == right, 1 otherwise.
+ */
+uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right,
+ wordcount_t num_words);
+
+/*
+ * @brief Computes (left * right) % mod
+ * @param result OUT -- (left * right) % mod
+ * @param left IN -- left term in product
+ * @param right IN -- right term in product
+ * @param mod IN -- mod
+ * @param num_words IN -- number of words
+ */
+void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, const uECC_word_t *mod,
+ wordcount_t num_words);
+
+/*
+ * @brief Computes (1 / input) % mod
+ * @note All VLIs are the same size.
+ * @note See "Euclid's GCD to Montgomery Multiplication to the Great Divide"
+ * @param result OUT -- (1 / input) % mod
+ * @param input IN -- value to be modular inverted
+ * @param mod IN -- mod
+ * @param num_words -- number of words
+ */
+void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input,
+ const uECC_word_t *mod, wordcount_t num_words);
+
+/*
+ * @brief Sets dest = src.
+ * @param dest OUT -- destination buffer
+ * @param src IN -- origin buffer
+ * @param num_words IN -- number of words
+ */
+void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src,
+ wordcount_t num_words);
+
+/*
+ * @brief Computes (left + right) % mod.
+ * @note Assumes that (left < mod) and right < mod), and that result does not
+ * overlap mod.
+ * @param result OUT -- (left + right) % mod.
+ * @param left IN -- left term in addition
+ * @param right IN -- right term in addition
+ * @param mod IN -- mod
+ * @param num_words IN -- number of words
+ */
+void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, const uECC_word_t *mod,
+ wordcount_t num_words);
+
+/*
+ * @brief Counts the number of bits required to represent vli.
+ * @param vli IN -- very long integer
+ * @param max_words IN -- number of words
+ * @return number of bits in given vli
+ */
+bitcount_t uECC_vli_numBits(const uECC_word_t *vli,
+ const wordcount_t max_words);
+
+/*
+ * @brief Erases (set to 0) vli
+ * @param vli IN -- very long integer
+ * @param num_words IN -- number of words
+ */
+void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words);
+
+/*
+ * @brief check if it is a valid point in the curve
+ * @param point IN -- point to be checked
+ * @param curve IN -- elliptic curve
+ * @return 0 if point is valid
+ * @exception returns -1 if it is a point at infinity
+ * @exception returns -2 if x or y is smaller than p,
+ * @exception returns -3 if y^2 != x^3 + ax + b.
+ */
+int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve);
+
+/*
+ * @brief Check if a public key is valid.
+ * @param public_key IN -- The public key to be checked.
+ * @return returns 0 if the public key is valid
+ * @exception returns -1 if it is a point at infinity
+ * @exception returns -2 if x or y is smaller than p,
+ * @exception returns -3 if y^2 != x^3 + ax + b.
+ * @exception returns -4 if public key is the group generator.
+ *
+ * @note Note that you are not required to check for a valid public key before
+ * using any other uECC functions. However, you may wish to avoid spending CPU
+ * time computing a shared secret or verifying a signature using an invalid
+ * public key.
+ */
+int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve);
+
+ /*
+ * @brief Converts an integer in uECC native format to big-endian bytes.
+ * @param bytes OUT -- bytes representation
+ * @param num_bytes IN -- number of bytes
+ * @param native IN -- uECC native representation
+ */
+void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
+ const unsigned int *native);
+
+/*
+ * @brief Converts big-endian bytes to an integer in uECC native format.
+ * @param native OUT -- uECC native representation
+ * @param bytes IN -- bytes representation
+ * @param num_bytes IN -- number of bytes
+ */
+void uECC_vli_bytesToNative(unsigned int *native, const uint8_t *bytes,
+ int num_bytes);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __TC_UECC_H__ */
+#endif /* MBEDTLS_USE_UECC */
diff --git a/include/tinycrypt/ecc_dh.h b/include/tinycrypt/ecc_dh.h
new file mode 100644
index 0000000..18a4fd2
--- /dev/null
+++ b/include/tinycrypt/ecc_dh.h
@@ -0,0 +1,133 @@
+/* ecc_dh.h - TinyCrypt interface to EC-DH implementation */
+
+/*
+ * Copyright (c) 2014, Kenneth MacKay
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* Copyright (C) 2017 by Intel Corporation, All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @file
+ * @brief -- Interface to EC-DH implementation.
+ *
+ * Overview: This software is an implementation of EC-DH. This implementation
+ * uses curve NIST p-256.
+ *
+ * Security: The curve NIST p-256 provides approximately 128 bits of security.
+ */
+
+#if defined(MBEDTLS_USE_UECC)
+#ifndef __TC_ECC_DH_H__
+#define __TC_ECC_DH_H__
+
+#include <tinycrypt/ecc.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief Create a public/private key pair.
+ * @return returns TC_CRYPTO_SUCCESS (1) if the key pair was generated successfully
+ * returns TC_CRYPTO_FAIL (0) if error while generating key pair
+ *
+ * @param p_public_key OUT -- Will be filled in with the public key. Must be at
+ * least 2 * the curve size (in bytes) long. For curve secp256r1, p_public_key
+ * must be 64 bytes long.
+ * @param p_private_key OUT -- Will be filled in with the private key. Must be as
+ * long as the curve order (for secp256r1, p_private_key must be 32 bytes long).
+ *
+ * @note side-channel countermeasure: algorithm strengthened against timing
+ * attack.
+ * @warning A cryptographically-secure PRNG function must be set (using
+ * uECC_set_rng()) before calling uECC_make_key().
+ */
+int uECC_make_key(uint8_t *p_public_key, uint8_t *p_private_key, uECC_Curve curve);
+
+#ifdef ENABLE_TESTS
+
+/**
+ * @brief Create a public/private key pair given a specific d.
+ *
+ * @note THIS FUNCTION SHOULD BE CALLED ONLY FOR TEST PURPOSES. Refer to
+ * uECC_make_key() function for real applications.
+ */
+int uECC_make_key_with_d(uint8_t *p_public_key, uint8_t *p_private_key,
+ unsigned int *d, uECC_Curve curve);
+#endif
+
+/**
+ * @brief Compute a shared secret given your secret key and someone else's
+ * public key.
+ * @return returns TC_CRYPTO_SUCCESS (1) if the shared secret was computed successfully
+ * returns TC_CRYPTO_FAIL (0) otherwise
+ *
+ * @param p_secret OUT -- Will be filled in with the shared secret value. Must be
+ * the same size as the curve size (for curve secp256r1, secret must be 32 bytes
+ * long.
+ * @param p_public_key IN -- The public key of the remote party.
+ * @param p_private_key IN -- Your private key.
+ *
+ * @warning It is recommended to use the output of uECC_shared_secret() as the
+ * input of a recommended Key Derivation Function (see NIST SP 800-108) in
+ * order to produce a cryptographically secure symmetric key.
+ */
+int uECC_shared_secret(const uint8_t *p_public_key, const uint8_t *p_private_key,
+ uint8_t *p_secret, uECC_Curve curve);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __TC_ECC_DH_H__ */
+#endif /* MBEDTLS_USE_UECC */
diff --git a/include/tinycrypt/ecc_dsa.h b/include/tinycrypt/ecc_dsa.h
new file mode 100644
index 0000000..8065340
--- /dev/null
+++ b/include/tinycrypt/ecc_dsa.h
@@ -0,0 +1,141 @@
+/* ecc_dh.h - TinyCrypt interface to EC-DSA implementation */
+
+/*
+ * Copyright (c) 2014, Kenneth MacKay
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (C) 2017 by Intel Corporation, All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @file
+ * @brief -- Interface to EC-DSA implementation.
+ *
+ * Overview: This software is an implementation of EC-DSA. This implementation
+ * uses curve NIST p-256.
+ *
+ * Security: The curve NIST p-256 provides approximately 128 bits of security.
+ *
+ * Usage: - To sign: Compute a hash of the data you wish to sign (SHA-2 is
+ * recommended) and pass it in to ecdsa_sign function along with your
+ * private key and a random number. You must use a new non-predictable
+ * random number to generate each new signature.
+ * - To verify a signature: Compute the hash of the signed data using
+ * the same hash as the signer and pass it to this function along with
+ * the signer's public key and the signature values (r and s).
+ */
+
+#if defined(MBEDTLS_USE_UECC)
+#ifndef __TC_ECC_DSA_H__
+#define __TC_ECC_DSA_H__
+
+#include <tinycrypt/ecc.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief Generate an ECDSA signature for a given hash value.
+ * @return returns TC_CRYPTO_SUCCESS (1) if the signature generated successfully
+ * returns TC_CRYPTO_FAIL (0) if an error occurred.
+ *
+ * @param p_private_key IN -- Your private key.
+ * @param p_message_hash IN -- The hash of the message to sign.
+ * @param p_hash_size IN -- The size of p_message_hash in bytes.
+ * @param p_signature OUT -- Will be filled in with the signature value. Must be
+ * at least 2 * curve size long (for secp256r1, signature must be 64 bytes long).
+ *
+ * @warning A cryptographically-secure PRNG function must be set (using
+ * uECC_set_rng()) before calling uECC_sign().
+ * @note Usage: Compute a hash of the data you wish to sign (SHA-2 is
+ * recommended) and pass it in to this function along with your private key.
+ * @note side-channel countermeasure: algorithm strengthened against timing
+ * attack.
+ */
+int uECC_sign(const uint8_t *p_private_key, const uint8_t *p_message_hash,
+ unsigned p_hash_size, uint8_t *p_signature, uECC_Curve curve);
+
+#ifdef ENABLE_TESTS
+/*
+ * THIS FUNCTION SHOULD BE CALLED FOR TEST PURPOSES ONLY.
+ * Refer to uECC_sign() function for real applications.
+ */
+int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
+ unsigned int hash_size, uECC_word_t *k, uint8_t *signature,
+ uECC_Curve curve);
+#endif
+
+/**
+ * @brief Verify an ECDSA signature.
+ * @return returns TC_SUCCESS (1) if the signature is valid
+ * returns TC_FAIL (0) if the signature is invalid.
+ *
+ * @param p_public_key IN -- The signer's public key.
+ * @param p_message_hash IN -- The hash of the signed data.
+ * @param p_hash_size IN -- The size of p_message_hash in bytes.
+ * @param p_signature IN -- The signature values.
+ *
+ * @note Usage: Compute the hash of the signed data using the same hash as the
+ * signer and pass it to this function along with the signer's public key and
+ * the signature values (hash_size and signature).
+ */
+int uECC_verify(const uint8_t *p_public_key, const uint8_t *p_message_hash,
+ unsigned int p_hash_size, const uint8_t *p_signature, uECC_Curve curve);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __TC_ECC_DSA_H__ */
+#endif /* MBEDTLS_USE_UECC */
diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt
index f3c8044..a9a5b7b 100644
--- a/library/CMakeLists.txt
+++ b/library/CMakeLists.txt
@@ -131,6 +131,8 @@
set(libs ${libs} pthread)
endif()
+set(libs ${libs} tinycrypt)
+
if (NOT USE_STATIC_MBEDTLS_LIBRARY AND NOT USE_SHARED_MBEDTLS_LIBRARY)
message(FATAL_ERROR "Need to choose static or shared mbedtls build!")
endif(NOT USE_STATIC_MBEDTLS_LIBRARY AND NOT USE_SHARED_MBEDTLS_LIBRARY)
@@ -165,15 +167,15 @@
if(USE_SHARED_MBEDTLS_LIBRARY)
add_library(mbedcrypto SHARED ${src_crypto})
- set_target_properties(mbedcrypto PROPERTIES VERSION 2.16.0 SOVERSION 3)
+ set_target_properties(mbedcrypto PROPERTIES VERSION 2.16.1 SOVERSION 3)
target_link_libraries(mbedcrypto ${libs})
add_library(mbedx509 SHARED ${src_x509})
- set_target_properties(mbedx509 PROPERTIES VERSION 2.16.0 SOVERSION 0)
+ set_target_properties(mbedx509 PROPERTIES VERSION 2.16.1 SOVERSION 0)
target_link_libraries(mbedx509 ${libs} mbedcrypto)
add_library(mbedtls SHARED ${src_tls})
- set_target_properties(mbedtls PROPERTIES VERSION 2.16.0 SOVERSION 12)
+ set_target_properties(mbedtls PROPERTIES VERSION 2.16.1 SOVERSION 12)
target_link_libraries(mbedtls ${libs} mbedx509)
install(TARGETS mbedtls mbedx509 mbedcrypto
diff --git a/library/Makefile b/library/Makefile
index 430c598..d653aa0 100644
--- a/library/Makefile
+++ b/library/Makefile
@@ -63,6 +63,8 @@
endif
endif
+VPATH = ../tinycrypt
+
OBJS_CRYPTO= aes.o aesni.o arc4.o \
aria.o asn1parse.o asn1write.o \
base64.o bignum.o blowfish.o \
@@ -84,7 +86,8 @@
ripemd160.o rsa_internal.o rsa.o \
sha1.o sha256.o sha512.o \
threading.o timing.o version.o \
- version_features.o xtea.o
+ version_features.o xtea.o \
+ ecc.o ecc_dh.o ecc_dsa.o
OBJS_X509= certs.o pkcs11.o x509.o \
x509_create.o x509_crl.o x509_crt.o \
diff --git a/library/bignum.c b/library/bignum.c
index 47e4529..4194618 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -582,15 +582,20 @@
if( radix < 2 || radix > 16 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
- n = mbedtls_mpi_bitlen( X );
- if( radix >= 4 ) n >>= 1;
- if( radix >= 16 ) n >>= 1;
- /*
- * Round up the buffer length to an even value to ensure that there is
- * enough room for hexadecimal values that can be represented in an odd
- * number of digits.
- */
- n += 3 + ( ( n + 1 ) & 1 );
+ n = mbedtls_mpi_bitlen( X ); /* Number of bits necessary to present `n`. */
+ if( radix >= 4 ) n >>= 1; /* Number of 4-adic digits necessary to present
+ * `n`. If radix > 4, this might be a strict
+ * overapproximation of the number of
+ * radix-adic digits needed to present `n`. */
+ if( radix >= 16 ) n >>= 1; /* Number of hexadecimal digits necessary to
+ * present `n`. */
+
+ n += 1; /* Terminating null byte */
+ n += 1; /* Compensate for the divisions above, which round down `n`
+ * in case it's not even. */
+ n += 1; /* Potential '-'-sign. */
+ n += ( n & 1 ); /* Make n even to have enough space for hexadecimal writing,
+ * which always uses an even number of hex-digits. */
if( buflen < n )
{
@@ -602,7 +607,10 @@
mbedtls_mpi_init( &T );
if( X->s == -1 )
+ {
*p++ = '-';
+ buflen--;
+ }
if( radix == 16 )
{
diff --git a/library/ecdh.c b/library/ecdh.c
index da95c60..c572687 100644
--- a/library/ecdh.c
+++ b/library/ecdh.c
@@ -49,6 +49,16 @@
typedef mbedtls_ecdh_context mbedtls_ecdh_context_mbed;
#endif
+static mbedtls_ecp_group_id mbedtls_ecdh_grp_id(
+ const mbedtls_ecdh_context *ctx )
+{
+#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
+ return( ctx->grp.id );
+#else
+ return( ctx->grp_id );
+#endif
+}
+
#if !defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT)
/*
* Generate public key (restartable version)
@@ -442,8 +452,21 @@
ECDH_VALIDATE_RET( side == MBEDTLS_ECDH_OURS ||
side == MBEDTLS_ECDH_THEIRS );
- if( ( ret = mbedtls_ecdh_setup( ctx, key->grp.id ) ) != 0 )
- return( ret );
+ if( mbedtls_ecdh_grp_id( ctx ) == MBEDTLS_ECP_DP_NONE )
+ {
+ /* This is the first call to get_params(). Set up the context
+ * for use with the group. */
+ if( ( ret = mbedtls_ecdh_setup( ctx, key->grp.id ) ) != 0 )
+ return( ret );
+ }
+ else
+ {
+ /* This is not the first call to get_params(). Check that the
+ * current key's group is the same as the context's, which was set
+ * from the first key's group. */
+ if( mbedtls_ecdh_grp_id( ctx ) != key->grp.id )
+ return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
+ }
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_get_params_internal( ctx, key, side ) );
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 1ae28f7..62f6027 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -109,6 +109,41 @@
#if defined(MBEDTLS_SSL_PROTO_DTLS)
+#if defined(MBEDTLS_SSL_CID)
+/* Top-level Connection ID API */
+
+/* WARNING: This implementation is a stub and doesn't do anything!
+ * It is included solely to allow review and coding against
+ * the new Connection CID API. */
+int mbedtls_ssl_set_cid( mbedtls_ssl_context *ssl,
+ int enable,
+ unsigned char const *own_cid,
+ size_t own_cid_len )
+{
+ ((void) ssl);
+ ((void) enable);
+ ((void) own_cid);
+ ((void) own_cid_len);
+ return( 0 );
+}
+
+/* WARNING: This implementation is a stub and doesn't do anything!
+ * It is included solely to allow review and coding against
+ * the new Connection CID API. */
+int mbedtls_ssl_get_peer_cid( mbedtls_ssl_context *ssl,
+ int *enabled,
+ unsigned char peer_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ],
+ size_t *peer_cid_len )
+{
+ ((void) ssl);
+ ((void) peer_cid);
+ ((void) peer_cid_len);
+
+ *enabled = MBEDTLS_SSL_CID_DISABLED;
+ return( 0 );
+}
+#endif /* MBEDTLS_SSL_CID */
+
/* Forward declarations for functions related to message buffering. */
static void ssl_buffering_free( mbedtls_ssl_context *ssl );
static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
diff --git a/library/version_features.c b/library/version_features.c
index 24143d0..74a0a0e 100644
--- a/library/version_features.c
+++ b/library/version_features.c
@@ -435,6 +435,9 @@
#if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
"MBEDTLS_SSL_ALL_ALERT_MESSAGES",
#endif /* MBEDTLS_SSL_ALL_ALERT_MESSAGES */
+#if defined(MBEDTLS_SSL_CID)
+ "MBEDTLS_SSL_CID",
+#endif /* MBEDTLS_SSL_CID */
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
"MBEDTLS_SSL_ASYNC_PRIVATE",
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
@@ -612,6 +615,9 @@
#if defined(MBEDTLS_ECP_C)
"MBEDTLS_ECP_C",
#endif /* MBEDTLS_ECP_C */
+#if defined(MBEDTLS_USE_UECC)
+ "MBEDTLS_USE_UECC",
+#endif /* MBEDTLS_USE_UECC */
#if defined(MBEDTLS_ENTROPY_C)
"MBEDTLS_ENTROPY_C",
#endif /* MBEDTLS_ENTROPY_C */
diff --git a/library/x509.c b/library/x509.c
index 52b5b64..7cc813e 100644
--- a/library/x509.c
+++ b/library/x509.c
@@ -1001,8 +1001,8 @@
*/
int mbedtls_x509_self_test( int verbose )
{
+ int ret = 0;
#if defined(MBEDTLS_CERTS_C) && defined(MBEDTLS_SHA256_C)
- int ret;
uint32_t flags;
mbedtls_x509_crt cacert;
mbedtls_x509_crt clicert;
@@ -1010,6 +1010,7 @@
if( verbose != 0 )
mbedtls_printf( " X.509 certificate load: " );
+ mbedtls_x509_crt_init( &cacert );
mbedtls_x509_crt_init( &clicert );
ret = mbedtls_x509_crt_parse( &clicert, (const unsigned char *) mbedtls_test_cli_crt,
@@ -1019,11 +1020,9 @@
if( verbose != 0 )
mbedtls_printf( "failed\n" );
- return( ret );
+ goto cleanup;
}
- mbedtls_x509_crt_init( &cacert );
-
ret = mbedtls_x509_crt_parse( &cacert, (const unsigned char *) mbedtls_test_ca_crt,
mbedtls_test_ca_crt_len );
if( ret != 0 )
@@ -1031,7 +1030,7 @@
if( verbose != 0 )
mbedtls_printf( "failed\n" );
- return( ret );
+ goto cleanup;
}
if( verbose != 0 )
@@ -1043,20 +1042,19 @@
if( verbose != 0 )
mbedtls_printf( "failed\n" );
- return( ret );
+ goto cleanup;
}
if( verbose != 0 )
mbedtls_printf( "passed\n\n");
+cleanup:
mbedtls_x509_crt_free( &cacert );
mbedtls_x509_crt_free( &clicert );
-
- return( 0 );
#else
((void) verbose);
- return( 0 );
#endif /* MBEDTLS_CERTS_C && MBEDTLS_SHA1_C */
+ return( ret );
}
#endif /* MBEDTLS_SELF_TEST */
diff --git a/programs/Makefile b/programs/Makefile
index 7d9affc..28c747b 100644
--- a/programs/Makefile
+++ b/programs/Makefile
@@ -67,7 +67,7 @@
ssl/ssl_mail_client$(EXEXT) random/gen_entropy$(EXEXT) \
random/gen_random_havege$(EXEXT) \
random/gen_random_ctr_drbg$(EXEXT) \
- test/ssl_cert_test$(EXEXT) test/benchmark$(EXEXT) \
+ test/benchmark$(EXEXT) \
test/selftest$(EXEXT) test/udp_proxy$(EXEXT) \
test/zeroize$(EXEXT) \
test/query_compile_time_config$(EXEXT) \
@@ -241,10 +241,6 @@
echo " CC ssl/mini_client.c"
$(CC) $(LOCAL_CFLAGS) $(CFLAGS) ssl/mini_client.c $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@
-test/ssl_cert_test$(EXEXT): test/ssl_cert_test.c $(DEP)
- echo " CC test/ssl_cert_test.c"
- $(CC) $(LOCAL_CFLAGS) $(CFLAGS) test/ssl_cert_test.c $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@
-
test/benchmark$(EXEXT): test/benchmark.c $(DEP)
echo " CC test/benchmark.c"
$(CC) $(LOCAL_CFLAGS) $(CFLAGS) test/benchmark.c $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@
diff --git a/programs/README.md b/programs/README.md
index eb25a7f..d26349d 100644
--- a/programs/README.md
+++ b/programs/README.md
@@ -99,8 +99,6 @@
* [`test/selftest.c`](test/selftest.c): runs the self-test function in each library module.
-* [`test/ssl_cert_test.c`](test/ssl_cert_test.c): demonstrates how to verify X.509 certificates, and (for RSA keys only) how to check that each certificate matches the corresponding private key. This program requires some test data which is not provided.
-
* [`test/udp_proxy.c`](test/udp_proxy.c): a UDP proxy that can inject certain failures (delay, duplicate, drop). Useful for testing DTLS.
* [`test/zeroize.c`](test/zeroize.c): a test program for `mbedtls_platform_zeroize`, used by [`tests/scripts/test_zeroize.gdb`](tests/scripts/test_zeroize.gdb).
diff --git a/programs/ssl/query_config.c b/programs/ssl/query_config.c
index 6e28197..6c76f47 100644
--- a/programs/ssl/query_config.c
+++ b/programs/ssl/query_config.c
@@ -1202,6 +1202,14 @@
}
#endif /* MBEDTLS_SSL_ALL_ALERT_MESSAGES */
+#if defined(MBEDTLS_SSL_CID)
+ if( strcmp( "MBEDTLS_SSL_CID", config ) == 0 )
+ {
+ MACRO_EXPANSION_TO_STR( MBEDTLS_SSL_CID );
+ return( 0 );
+ }
+#endif /* MBEDTLS_SSL_CID */
+
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
if( strcmp( "MBEDTLS_SSL_ASYNC_PRIVATE", config ) == 0 )
{
@@ -1674,6 +1682,14 @@
}
#endif /* MBEDTLS_ECP_C */
+#if defined(MBEDTLS_USE_UECC)
+ if( strcmp( "MBEDTLS_USE_UECC", config ) == 0 )
+ {
+ MACRO_EXPANSION_TO_STR( MBEDTLS_USE_UECC );
+ return( 0 );
+ }
+#endif /* MBEDTLS_USE_UECC */
+
#if defined(MBEDTLS_ENTROPY_C)
if( strcmp( "MBEDTLS_ENTROPY_C", config ) == 0 )
{
@@ -2418,6 +2434,22 @@
}
#endif /* MBEDTLS_SSL_IN_CONTENT_LEN */
+#if defined(MBEDTLS_SSL_CID_IN_LEN_MAX)
+ if( strcmp( "MBEDTLS_SSL_CID_IN_LEN_MAX", config ) == 0 )
+ {
+ MACRO_EXPANSION_TO_STR( MBEDTLS_SSL_CID_IN_LEN_MAX );
+ return( 0 );
+ }
+#endif /* MBEDTLS_SSL_CID_IN_LEN_MAX */
+
+#if defined(MBEDTLS_SSL_CID_OUT_LEN_MAX)
+ if( strcmp( "MBEDTLS_SSL_CID_OUT_LEN_MAX", config ) == 0 )
+ {
+ MACRO_EXPANSION_TO_STR( MBEDTLS_SSL_CID_OUT_LEN_MAX );
+ return( 0 );
+ }
+#endif /* MBEDTLS_SSL_CID_OUT_LEN_MAX */
+
#if defined(MBEDTLS_SSL_OUT_CONTENT_LEN)
if( strcmp( "MBEDTLS_SSL_OUT_CONTENT_LEN", config ) == 0 )
{
diff --git a/programs/ssl/ssl_client2.c b/programs/ssl/ssl_client2.c
index 1343970..db99ef6 100644
--- a/programs/ssl/ssl_client2.c
+++ b/programs/ssl/ssl_client2.c
@@ -103,6 +103,8 @@
#define DFL_DHMLEN -1
#define DFL_RECONNECT 0
#define DFL_RECO_DELAY 0
+#define DFL_CID_ENABLED 0
+#define DFL_CID_VALUE ""
#define DFL_RECONNECT_HARD 0
#define DFL_TICKETS MBEDTLS_SSL_SESSION_TICKETS_ENABLED
#define DFL_ALPN_STRING NULL
@@ -137,6 +139,16 @@
#define USAGE_IO ""
#endif /* MBEDTLS_X509_CRT_PARSE_C */
+#if defined(MBEDTLS_SSL_CID)
+#define USAGE_CID \
+ " cid=%%d Disable (0) or enable (1) the use of the DTLS Connection ID extension.\n" \
+ " default: 0 (disabled)\n" \
+ " cid_val=%%s The CID to use for incoming messages (in hex, without 0x).\n" \
+ " default: \"\"\n"
+#else /* MBEDTLS_SSL_CID */
+#define USAGE_CID ""
+#endif /* MBEDTLS_SSL_CID */
+
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
#define USAGE_PSK \
" psk=%%s default: \"\" (in hex, without 0x)\n" \
@@ -278,6 +290,7 @@
" max_resend=%%d default: 0 (no resend on timeout)\n" \
"\n" \
USAGE_DTLS \
+ USAGE_CID \
"\n" \
" auth_mode=%%s default: (library default: none)\n" \
" options: none, optional, required\n" \
@@ -385,6 +398,8 @@
int dgram_packing; /* allow/forbid datagram packing */
int extended_ms; /* negotiate extended master secret? */
int etm; /* negotiate encrypt then mac? */
+ int cid_enabled; /* whether to use the CID extension or not */
+ const char *cid_val; /* the CID to use for incoming messages */
} opt;
int query_config( const char *config );
@@ -536,6 +551,45 @@
return( 0 );
}
+/* Unhexify `hex` into `dst`. `dst` must have
+ * size at least `strlen( hex ) / 2`. */
+int unhexify( char const *hex, unsigned char *dst )
+{
+ unsigned char c;
+ size_t j;
+ size_t len = strlen( hex );
+
+ if( len % 2 != 0 )
+ return( -1 );
+
+ for( j = 0; j < len; j += 2 )
+ {
+ c = hex[j];
+ if( c >= '0' && c <= '9' )
+ c -= '0';
+ else if( c >= 'a' && c <= 'f' )
+ c -= 'a' - 10;
+ else if( c >= 'A' && c <= 'F' )
+ c -= 'A' - 10;
+ else
+ return( -1 );
+ dst[ j / 2 ] = c << 4;
+
+ c = hex[j + 1];
+ if( c >= '0' && c <= '9' )
+ c -= '0';
+ else if( c >= 'a' && c <= 'f' )
+ c -= 'a' - 10;
+ else if( c >= 'A' && c <= 'F' )
+ c -= 'A' - 10;
+ else
+ return( -1 );
+ dst[ j / 2 ] |= c;
+ }
+
+ return( 0 );
+}
+
int main( int argc, char *argv[] )
{
int ret = 0, len, tail_len, i, written, frags, retry_left;
@@ -547,6 +601,12 @@
unsigned char psk[MBEDTLS_PSK_MAX_LEN];
size_t psk_len = 0;
#endif
+
+#if defined(MBEDTLS_SSL_CID)
+ unsigned char cid[MBEDTLS_SSL_CID_IN_LEN_MAX];
+ size_t cid_len = 0;
+#endif
+
#if defined(MBEDTLS_SSL_ALPN)
const char *alpn_list[ALPN_LIST_SIZE];
#endif
@@ -620,6 +680,8 @@
opt.server_addr = DFL_SERVER_ADDR;
opt.server_port = DFL_SERVER_PORT;
opt.debug_level = DFL_DEBUG_LEVEL;
+ opt.cid_enabled = DFL_CID_ENABLED;
+ opt.cid_val = DFL_CID_VALUE;
opt.nbio = DFL_NBIO;
opt.event = DFL_EVENT;
opt.read_timeout = DFL_READ_TIMEOUT;
@@ -729,6 +791,18 @@
opt.crt_file = q;
else if( strcmp( p, "key_file" ) == 0 )
opt.key_file = q;
+#if defined(MBEDTLS_SSL_CID)
+ else if( strcmp( p, "cid" ) == 0 )
+ {
+ opt.cid_enabled = atoi( q );
+ if( opt.cid_enabled != 0 && opt.cid_enabled != 1 )
+ goto usage;
+ }
+ else if( strcmp( p, "cid_val" ) == 0 )
+ {
+ opt.cid_val = q;
+ }
+#endif /* MBEDTLS_SSL_CID */
else if( strcmp( p, "psk" ) == 0 )
opt.psk = q;
else if( strcmp( p, "psk_identity" ) == 0 )
@@ -1070,52 +1144,41 @@
}
}
+#if defined(MBEDTLS_SSL_CID)
+ if( strlen( opt.cid_val ) )
+ {
+ cid_len = strlen( opt.cid_val ) / 2;
+ if( cid_len > sizeof( cid ) )
+ {
+ mbedtls_printf( "CID too long\n" );
+ goto exit;
+ }
+
+ if( unhexify( opt.cid_val, cid ) != 0 )
+ {
+ mbedtls_printf( "CID not valid hex\n" );
+ goto exit;
+ }
+ }
+#endif /* MBEDTLS_SSL_CID */
+
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
/*
* Unhexify the pre-shared key if any is given
*/
if( strlen( opt.psk ) )
{
- unsigned char c;
- size_t j;
-
- if( strlen( opt.psk ) % 2 != 0 )
+ psk_len = strlen( opt.psk ) / 2;
+ if( psk_len > sizeof( psk ) )
{
- mbedtls_printf( "pre-shared key not valid hex\n" );
+ mbedtls_printf( "pre-shared key too long\n" );
goto exit;
}
- psk_len = strlen( opt.psk ) / 2;
-
- for( j = 0; j < strlen( opt.psk ); j += 2 )
+ if( unhexify( opt.psk, psk ) != 0 )
{
- c = opt.psk[j];
- if( c >= '0' && c <= '9' )
- c -= '0';
- else if( c >= 'a' && c <= 'f' )
- c -= 'a' - 10;
- else if( c >= 'A' && c <= 'F' )
- c -= 'A' - 10;
- else
- {
- mbedtls_printf( "pre-shared key not valid hex\n" );
- goto exit;
- }
- psk[ j / 2 ] = c << 4;
-
- c = opt.psk[j + 1];
- if( c >= '0' && c <= '9' )
- c -= '0';
- else if( c >= 'a' && c <= 'f' )
- c -= 'a' - 10;
- else if( c >= 'A' && c <= 'F' )
- c -= 'A' - 10;
- else
- {
- mbedtls_printf( "pre-shared key not valid hex\n" );
- goto exit;
- }
- psk[ j / 2 ] |= c;
+ mbedtls_printf( "pre-shared key not valid hex\n" );
+ goto exit;
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
@@ -1551,6 +1614,19 @@
mbedtls_net_send, mbedtls_net_recv,
opt.nbio == 0 ? mbedtls_net_recv_timeout : NULL );
+#if defined(MBEDTLS_SSL_CID)
+ if( opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
+ {
+ if( ( ret = mbedtls_ssl_set_cid( &ssl, opt.cid_enabled,
+ cid, cid_len ) ) != 0 )
+ {
+ mbedtls_printf( " failed\n ! mbedtls_ssl_set_cid returned %d\n\n",
+ ret );
+ goto exit;
+ }
+ }
+#endif /* MBEDTLS_SSL_CID */
+
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( opt.dtls_mtu != DFL_DTLS_MTU )
mbedtls_ssl_set_mtu( &ssl, opt.dtls_mtu );
@@ -1679,6 +1755,46 @@
}
#endif /* MBEDTLS_X509_CRT_PARSE_C */
+#if defined(MBEDTLS_SSL_CID)
+ if( opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
+ {
+ unsigned char peer_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ];
+ size_t peer_cid_len;
+ int cid_negotiated;
+
+ /* Check if the use of a CID has been negotiated */
+ ret = mbedtls_ssl_get_peer_cid( &ssl, &cid_negotiated,
+ peer_cid, &peer_cid_len );
+ if( ret != 0 )
+ {
+ mbedtls_printf( " failed\n ! mbedtls_ssl_get_peer_cid returned -0x%x\n\n",
+ -ret );
+ goto exit;
+ }
+
+ if( cid_negotiated == MBEDTLS_SSL_CID_DISABLED )
+ {
+ if( opt.cid_enabled == MBEDTLS_SSL_CID_ENABLED )
+ {
+ mbedtls_printf( "Use of Connection ID was rejected by the server.\n" );
+ }
+ }
+ else
+ {
+ size_t idx=0;
+ mbedtls_printf( "Use of Connection ID has been negotiated.\n" );
+ mbedtls_printf( "Peer CID (length %u Bytes): ",
+ (unsigned) peer_cid_len );
+ while( idx < peer_cid_len )
+ {
+ mbedtls_printf( "%#02x ", peer_cid[ idx ] );
+ idx++;
+ }
+ mbedtls_printf( "\n" );
+ }
+ }
+#endif /* MBEDTLS_SSL_CID */
+
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( opt.renegotiate )
{
diff --git a/programs/ssl/ssl_mail_client.c b/programs/ssl/ssl_mail_client.c
index bbe4c70..c73297c 100644
--- a/programs/ssl/ssl_mail_client.c
+++ b/programs/ssl/ssl_mail_client.c
@@ -110,9 +110,9 @@
#if defined(MBEDTLS_BASE64_C)
#define USAGE_AUTH \
- " authentication=%%d default: 0 (disabled)\n" \
- " user_name=%%s default: \"user\"\n" \
- " user_pwd=%%s default: \"password\"\n"
+ " authentication=%%d default: 0 (disabled)\n" \
+ " user_name=%%s default: \"" DFL_USER_NAME "\"\n" \
+ " user_pwd=%%s default: \"" DFL_USER_PWD "\"\n"
#else
#define USAGE_AUTH \
" authentication options disabled. (Require MBEDTLS_BASE64_C)\n"
@@ -129,17 +129,17 @@
#endif /* MBEDTLS_FS_IO */
#define USAGE \
- "\n usage: ssl_mail_client param=<>...\n" \
- "\n acceptable parameters:\n" \
- " server_name=%%s default: localhost\n" \
- " server_port=%%d default: 4433\n" \
- " debug_level=%%d default: 0 (disabled)\n" \
+ "\n usage: ssl_mail_client param=<>...\n" \
+ "\n acceptable parameters:\n" \
+ " server_name=%%s default: " DFL_SERVER_NAME "\n" \
+ " server_port=%%d default: " DFL_SERVER_PORT "\n" \
+ " debug_level=%%d default: 0 (disabled)\n" \
" mode=%%d default: 0 (SSL/TLS) (1 for STARTTLS)\n" \
- USAGE_AUTH \
- " mail_from=%%s default: \"\"\n" \
- " mail_to=%%s default: \"\"\n" \
- USAGE_IO \
- " force_ciphersuite=<name> default: all enabled\n"\
+ USAGE_AUTH \
+ " mail_from=%%s default: \"\"\n" \
+ " mail_to=%%s default: \"\"\n" \
+ USAGE_IO \
+ " force_ciphersuite=<name> default: all enabled\n" \
" acceptable ciphersuite names:\n"
#if defined(MBEDTLS_CHECK_PARAMS)
@@ -324,7 +324,7 @@
mbedtls_printf("\n%s", buf);
if( len && ( ret = mbedtls_net_send( sock_fd, buf, len ) ) <= 0 )
{
- mbedtls_printf( " failed\n ! mbedtls_ssl_write returned %d\n\n", ret );
+ mbedtls_printf( " failed\n ! mbedtls_net_send returned %d\n\n", ret );
return -1;
}
@@ -336,7 +336,7 @@
if( ret <= 0 )
{
- mbedtls_printf( "failed\n ! read returned %d\n\n", ret );
+ mbedtls_printf( "failed\n ! mbedtls_net_recv returned %d\n\n", ret );
return -1;
}
diff --git a/programs/ssl/ssl_server2.c b/programs/ssl/ssl_server2.c
index 2a499ad..dff899f 100644
--- a/programs/ssl/ssl_server2.c
+++ b/programs/ssl/ssl_server2.c
@@ -137,6 +137,8 @@
#define DFL_MAX_VERSION -1
#define DFL_ARC4 -1
#define DFL_SHA1 -1
+#define DFL_CID_ENABLED 0
+#define DFL_CID_VALUE ""
#define DFL_AUTH_MODE -1
#define DFL_CERT_REQ_CA_LIST MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED
#define DFL_MFL_CODE MBEDTLS_SSL_MAX_FRAG_LEN_NONE
@@ -222,6 +224,16 @@
#define USAGE_SSL_ASYNC ""
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
+#if defined(MBEDTLS_SSL_CID)
+#define USAGE_CID \
+ " cid=%%d Disable (0) or enable (1) the use of the DTLS Connection ID extension.\n" \
+ " default: 0 (disabled)\n" \
+ " cid_val=%%s The CID to use for incoming messages (in hex, without 0x).\n" \
+ " default: \"\"\n"
+#else /* MBEDTLS_SSL_CID */
+#define USAGE_CID ""
+#endif /* MBEDTLS_SSL_CID */
+
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
#define USAGE_PSK \
" psk=%%s default: \"\" (in hex, without 0x)\n" \
@@ -510,6 +522,8 @@
int dtls_mtu; /* UDP Maximum tranport unit for DTLS */
int dgram_packing; /* allow/forbid datagram packing */
int badmac_limit; /* Limit of records with bad MAC */
+ int cid_enabled; /* whether to use the CID extension or not */
+ const char *cid_val; /* the CID to use for incoming messages */
} opt;
int query_config( const char *config );
@@ -1260,6 +1274,11 @@
unsigned char alloc_buf[MEMORY_HEAP_SIZE];
#endif
+#if defined(MBEDTLS_SSL_CID)
+ unsigned char cid[MBEDTLS_SSL_CID_IN_LEN_MAX];
+ size_t cid_len = 0;
+#endif
+
int i;
char *p, *q;
const int *list;
@@ -1337,6 +1356,8 @@
opt.event = DFL_EVENT;
opt.response_size = DFL_RESPONSE_SIZE;
opt.nbio = DFL_NBIO;
+ opt.cid_enabled = DFL_CID_ENABLED;
+ opt.cid_val = DFL_CID_VALUE;
opt.read_timeout = DFL_READ_TIMEOUT;
opt.ca_file = DFL_CA_FILE;
opt.ca_path = DFL_CA_PATH;
@@ -1475,6 +1496,18 @@
opt.async_private_error = n;
}
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
+#if defined(MBEDTLS_SSL_CID)
+ else if( strcmp( p, "cid" ) == 0 )
+ {
+ opt.cid_enabled = atoi( q );
+ if( opt.cid_enabled != 0 && opt.cid_enabled != 1 )
+ goto usage;
+ }
+ else if( strcmp( p, "cid_val" ) == 0 )
+ {
+ opt.cid_val = q;
+ }
+#endif /* MBEDTLS_SSL_CID */
else if( strcmp( p, "psk" ) == 0 )
opt.psk = q;
else if( strcmp( p, "psk_identity" ) == 0 )
@@ -1882,6 +1915,24 @@
}
}
+#if defined(MBEDTLS_SSL_CID)
+ if( strlen( opt.cid_val ) )
+ {
+ cid_len = strlen( opt.cid_val ) / 2;
+ if( cid_len > sizeof( cid ) )
+ {
+ mbedtls_printf( "CID too long\n" );
+ goto exit;
+ }
+
+ if( unhexify( cid, opt.cid_val, &cid_len ) != 0 )
+ {
+ mbedtls_printf( "CID not valid hex\n" );
+ goto exit;
+ }
+ }
+#endif /* MBEDTLS_SSL_CID */
+
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
/*
* Unhexify the pre-shared key and parse the list if any given
@@ -2561,6 +2612,19 @@
mbedtls_ssl_set_bio( &ssl, &client_fd, mbedtls_net_send, mbedtls_net_recv,
opt.nbio == 0 ? mbedtls_net_recv_timeout : NULL );
+#if defined(MBEDTLS_SSL_CID)
+ if( opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
+ {
+ if( ( ret = mbedtls_ssl_set_cid( &ssl, opt.cid_enabled,
+ cid, cid_len ) ) != 0 )
+ {
+ mbedtls_printf( " failed\n ! mbedtls_ssl_set_cid returned %d\n\n",
+ ret );
+ goto exit;
+ }
+ }
+#endif /* MBEDTLS_SSL_CID */
+
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( opt.dtls_mtu != DFL_DTLS_MTU )
mbedtls_ssl_set_mtu( &ssl, opt.dtls_mtu );
@@ -2786,6 +2850,46 @@
}
#endif /* MBEDTLS_X509_CRT_PARSE_C */
+#if defined(MBEDTLS_SSL_CID)
+ if( opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
+ {
+ unsigned char peer_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ];
+ size_t peer_cid_len;
+ int cid_negotiated;
+
+ /* Check if the use of a CID has been negotiated */
+ ret = mbedtls_ssl_get_peer_cid( &ssl, &cid_negotiated,
+ peer_cid, &peer_cid_len );
+ if( ret != 0 )
+ {
+ mbedtls_printf( " failed\n ! mbedtls_ssl_get_peer_cid returned -0x%x\n\n",
+ -ret );
+ goto exit;
+ }
+
+ if( cid_negotiated == MBEDTLS_SSL_CID_DISABLED )
+ {
+ if( opt.cid_enabled == MBEDTLS_SSL_CID_ENABLED )
+ {
+ mbedtls_printf( "Use of Connection ID was not offered by the client.\n" );
+ }
+ }
+ else
+ {
+ size_t idx=0;
+ mbedtls_printf( "Use of Connection ID has been negotiated.\n" );
+ mbedtls_printf( "Peer CID (length %u Bytes): ",
+ (unsigned) peer_cid_len );
+ while( idx < peer_cid_len )
+ {
+ mbedtls_printf( "%#02x ", peer_cid[ idx ] );
+ idx++;
+ }
+ mbedtls_printf( "\n" );
+ }
+ }
+#endif /* MBEDTLS_SSL_CID */
+
if( opt.exchanges == 0 )
goto close_notify;
diff --git a/programs/test/CMakeLists.txt b/programs/test/CMakeLists.txt
index 65ff249..282ef58 100644
--- a/programs/test/CMakeLists.txt
+++ b/programs/test/CMakeLists.txt
@@ -21,9 +21,6 @@
target_link_libraries(cpp_dummy_build ${libs})
endif()
-add_executable(ssl_cert_test ssl_cert_test.c)
-target_link_libraries(ssl_cert_test ${libs})
-
add_executable(udp_proxy udp_proxy.c)
target_link_libraries(udp_proxy ${libs})
@@ -34,6 +31,6 @@
target_sources(query_compile_time_config PUBLIC ../ssl/query_config.c)
target_link_libraries(query_compile_time_config ${libs})
-install(TARGETS selftest benchmark ssl_cert_test udp_proxy query_compile_time_config
+install(TARGETS selftest benchmark udp_proxy query_compile_time_config
DESTINATION "bin"
PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
diff --git a/programs/test/ssl_cert_test.c b/programs/test/ssl_cert_test.c
deleted file mode 100644
index fdf30ef..0000000
--- a/programs/test/ssl_cert_test.c
+++ /dev/null
@@ -1,274 +0,0 @@
-/*
- * SSL certificate functionality tests
- *
- * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
- * SPDX-License-Identifier: Apache-2.0
- *
- * 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.
- *
- * This file is part of mbed TLS (https://tls.mbed.org)
- */
-
-#if !defined(MBEDTLS_CONFIG_FILE)
-#include "mbedtls/config.h"
-#else
-#include MBEDTLS_CONFIG_FILE
-#endif
-
-#if defined(MBEDTLS_PLATFORM_C)
-#include "mbedtls/platform.h"
-#else
-#include <stdio.h>
-#include <stdlib.h>
-#define mbedtls_snprintf snprintf
-#define mbedtls_printf printf
-#define mbedtls_exit exit
-#define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
-#define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
-#endif /* MBEDTLS_PLATFORM_C */
-
-#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_X509_CRT_PARSE_C) && \
- defined(MBEDTLS_FS_IO) && defined(MBEDTLS_X509_CRL_PARSE_C)
-#include "mbedtls/certs.h"
-#include "mbedtls/x509_crt.h"
-
-#include <stdio.h>
-#include <string.h>
-#endif
-
-#define MAX_CLIENT_CERTS 8
-
-#if !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \
- !defined(MBEDTLS_FS_IO) || !defined(MBEDTLS_X509_CRL_PARSE_C)
-int main( void )
-{
- mbedtls_printf("MBEDTLS_RSA_C and/or MBEDTLS_X509_CRT_PARSE_C "
- "MBEDTLS_FS_IO and/or MBEDTLS_X509_CRL_PARSE_C "
- "not defined.\n");
- return( 0 );
-}
-#else
-const char *client_certificates[MAX_CLIENT_CERTS] =
-{
- "client1.crt",
- "client2.crt",
- "server1.crt",
- "server2.crt",
- "cert_sha224.crt",
- "cert_sha256.crt",
- "cert_sha384.crt",
- "cert_sha512.crt"
-};
-
-const char *client_private_keys[MAX_CLIENT_CERTS] =
-{
- "client1.key",
- "client2.key",
- "server1.key",
- "server2.key",
- "cert_digest.key",
- "cert_digest.key",
- "cert_digest.key",
- "cert_digest.key"
-};
-
-#if defined(MBEDTLS_CHECK_PARAMS)
-#include "mbedtls/platform_util.h"
-void mbedtls_param_failed( const char *failure_condition,
- const char *file,
- int line )
-{
- mbedtls_printf( "%s:%i: Input param failed - %s\n",
- file, line, failure_condition );
- mbedtls_exit( MBEDTLS_EXIT_FAILURE );
-}
-#endif
-
-int main( void )
-{
- int ret = 1, i;
- int exit_code = MBEDTLS_EXIT_FAILURE;
- mbedtls_x509_crt cacert;
- mbedtls_x509_crl crl;
- char buf[10240];
-
- mbedtls_x509_crt_init( &cacert );
- mbedtls_x509_crl_init( &crl );
-
- /*
- * 1.1. Load the trusted CA
- */
- mbedtls_printf( "\n . Loading the CA root certificate ..." );
- fflush( stdout );
-
- /*
- * Alternatively, you may load the CA certificates from a .pem or
- * .crt file by calling mbedtls_x509_crt_parse_file( &cacert, "myca.crt" ).
- */
- ret = mbedtls_x509_crt_parse_file( &cacert, "ssl/test-ca/test-ca.crt" );
- if( ret != 0 )
- {
- mbedtls_printf( " failed\n ! mbedtls_x509_crt_parse_file returned %d\n\n", ret );
- goto exit;
- }
-
- mbedtls_printf( " ok\n" );
-
- mbedtls_x509_crt_info( buf, 1024, "CRT: ", &cacert );
- mbedtls_printf("%s\n", buf );
-
- /*
- * 1.2. Load the CRL
- */
- mbedtls_printf( " . Loading the CRL ..." );
- fflush( stdout );
-
- ret = mbedtls_x509_crl_parse_file( &crl, "ssl/test-ca/crl.pem" );
- if( ret != 0 )
- {
- mbedtls_printf( " failed\n ! mbedtls_x509_crl_parse_file returned %d\n\n", ret );
- goto exit;
- }
-
- mbedtls_printf( " ok\n" );
-
- mbedtls_x509_crl_info( buf, 1024, "CRL: ", &crl );
- mbedtls_printf("%s\n", buf );
-
- for( i = 0; i < MAX_CLIENT_CERTS; i++ )
- {
- /*
- * 1.3. Load own certificate
- */
- char name[512];
- uint32_t flags;
- mbedtls_x509_crt clicert;
- mbedtls_pk_context pk;
-
- mbedtls_x509_crt_init( &clicert );
- mbedtls_pk_init( &pk );
-
- mbedtls_snprintf(name, 512, "ssl/test-ca/%s", client_certificates[i]);
-
- mbedtls_printf( " . Loading the client certificate %s...", name );
- fflush( stdout );
-
- ret = mbedtls_x509_crt_parse_file( &clicert, name );
- if( ret != 0 )
- {
- mbedtls_printf( " failed\n ! mbedtls_x509_crt_parse_file returned %d\n\n", ret );
- goto exit;
- }
-
- mbedtls_printf( " ok\n" );
-
- /*
- * 1.4. Verify certificate validity with CA certificate
- */
- mbedtls_printf( " . Verify the client certificate with CA certificate..." );
- fflush( stdout );
-
- ret = mbedtls_x509_crt_verify( &clicert, &cacert, &crl, NULL, &flags, NULL,
- NULL );
- if( ret != 0 )
- {
- if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED )
- {
- char vrfy_buf[512];
-
- mbedtls_printf( " failed\n" );
- mbedtls_x509_crt_verify_info( vrfy_buf, sizeof( vrfy_buf ), " ! ", flags );
- mbedtls_printf( "%s\n", vrfy_buf );
- }
- else
- {
- mbedtls_printf( " failed\n ! mbedtls_x509_crt_verify returned %d\n\n", ret );
- goto exit;
- }
- }
-
- mbedtls_printf( " ok\n" );
-
- /*
- * 1.5. Load own private key
- */
- mbedtls_snprintf(name, 512, "ssl/test-ca/%s", client_private_keys[i]);
-
- mbedtls_printf( " . Loading the client private key %s...", name );
- fflush( stdout );
-
- ret = mbedtls_pk_parse_keyfile( &pk, name, NULL );
- if( ret != 0 )
- {
- mbedtls_printf( " failed\n ! mbedtls_pk_parse_keyfile returned %d\n\n", ret );
- goto exit;
- }
-
- mbedtls_printf( " ok\n" );
-
- /*
- * 1.6. Verify certificate validity with private key
- */
- mbedtls_printf( " . Verify the client certificate with private key..." );
- fflush( stdout );
-
-
- /* EC NOT IMPLEMENTED YET */
- if( ! mbedtls_pk_can_do( &clicert.pk, MBEDTLS_PK_RSA ) )
- {
- mbedtls_printf( " failed\n ! certificate's key is not RSA\n\n" );
- goto exit;
- }
-
- ret = mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa( pk )->N, &mbedtls_pk_rsa( clicert.pk )->N);
- if( ret != 0 )
- {
- mbedtls_printf( " failed\n ! mbedtls_mpi_cmp_mpi for N returned %d\n\n", ret );
- goto exit;
- }
-
- ret = mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa( pk )->E, &mbedtls_pk_rsa( clicert.pk )->E);
- if( ret != 0 )
- {
- mbedtls_printf( " failed\n ! mbedtls_mpi_cmp_mpi for E returned %d\n\n", ret );
- goto exit;
- }
-
- ret = mbedtls_rsa_check_privkey( mbedtls_pk_rsa( pk ) );
- if( ret != 0 )
- {
- mbedtls_printf( " failed\n ! mbedtls_rsa_check_privkey returned %d\n\n", ret );
- goto exit;
- }
-
- mbedtls_printf( " ok\n" );
-
- mbedtls_x509_crt_free( &clicert );
- mbedtls_pk_free( &pk );
- }
-
- exit_code = MBEDTLS_EXIT_SUCCESS;
-
-exit:
- mbedtls_x509_crt_free( &cacert );
- mbedtls_x509_crl_free( &crl );
-
-#if defined(_WIN32)
- mbedtls_printf( " + Press Enter to exit this program.\n" );
- fflush( stdout ); getchar();
-#endif
-
- return( exit_code );
-}
-#endif /* MBEDTLS_RSA_C && MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_FS_IO &&
- MBEDTLS_X509_CRL_PARSE_C */
diff --git a/scripts/abi_check.py b/scripts/abi_check.py
index 8f9cd0f..2a90b68 100755
--- a/scripts/abi_check.py
+++ b/scripts/abi_check.py
@@ -26,8 +26,16 @@
class AbiChecker(object):
+ """API and ABI checker."""
def __init__(self, report_dir, old_rev, new_rev, keep_all_reports):
+ """Instantiate the API/ABI checker.
+
+ report_dir: directory for output files
+ old_rev: reference git revision to compare against
+ new_rev: git revision to check
+ keep_all_reports: if false, delete old reports
+ """
self.repo_path = "."
self.log = None
self.setup_logger()
@@ -42,7 +50,8 @@
self.git_command = "git"
self.make_command = "make"
- def check_repo_path(self):
+ @staticmethod
+ def check_repo_path():
current_dir = os.path.realpath('.')
root_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if current_dir != root_dir:
@@ -53,12 +62,15 @@
self.log.setLevel(logging.INFO)
self.log.addHandler(logging.StreamHandler())
- def check_abi_tools_are_installed(self):
+ @staticmethod
+ def check_abi_tools_are_installed():
for command in ["abi-dumper", "abi-compliance-checker"]:
if not shutil.which(command):
raise Exception("{} not installed, aborting".format(command))
def get_clean_worktree_for_git_revision(self, git_rev):
+ """Make a separate worktree with git_rev checked out.
+ Do not modify the current worktree."""
self.log.info(
"Checking out git worktree for revision {}".format(git_rev)
)
@@ -76,6 +88,7 @@
return git_worktree_path
def build_shared_libraries(self, git_worktree_path):
+ """Build the shared libraries in the specified worktree."""
my_environment = os.environ.copy()
my_environment["CFLAGS"] = "-g -Og"
my_environment["SHARED"] = "1"
@@ -92,6 +105,9 @@
raise Exception("make failed, aborting")
def get_abi_dumps_from_shared_libraries(self, git_ref, git_worktree_path):
+ """Generate the ABI dumps for the specified git revision.
+ It must be checked out in git_worktree_path and the shared libraries
+ must have been built."""
abi_dumps = {}
for mbed_module in self.mbedtls_modules:
output_path = os.path.join(
@@ -117,6 +133,7 @@
return abi_dumps
def cleanup_worktree(self, git_worktree_path):
+ """Remove the specified git worktree."""
shutil.rmtree(git_worktree_path)
worktree_process = subprocess.Popen(
[self.git_command, "worktree", "prune"],
@@ -130,6 +147,7 @@
raise Exception("Worktree cleanup failed, aborting")
def get_abi_dump_for_ref(self, git_rev):
+ """Generate the ABI dumps for the specified git revision."""
git_worktree_path = self.get_clean_worktree_for_git_revision(git_rev)
self.build_shared_libraries(git_worktree_path)
abi_dumps = self.get_abi_dumps_from_shared_libraries(
@@ -139,6 +157,9 @@
return abi_dumps
def get_abi_compatibility_report(self):
+ """Generate a report of the differences between the reference ABI
+ and the new ABI. ABI dumps from self.old_rev and self.new_rev must
+ be available."""
compatibility_report = ""
compliance_return_code = 0
for mbed_module in self.mbedtls_modules:
@@ -188,6 +209,8 @@
return compliance_return_code
def check_for_abi_changes(self):
+ """Generate a report of ABI differences
+ between self.old_rev and self.new_rev."""
self.check_repo_path()
self.check_abi_tools_are_installed()
self.old_dumps = self.get_abi_dump_for_ref(self.old_rev)
@@ -232,7 +255,9 @@
)
return_code = abi_check.check_for_abi_changes()
sys.exit(return_code)
- except Exception:
+ except Exception: # pylint: disable=broad-except
+ # Print the backtrace and exit explicitly so as to exit with
+ # status 2, not 1.
traceback.print_exc()
sys.exit(2)
diff --git a/scripts/config.pl b/scripts/config.pl
index 42ec6f8..d5c2ed8 100755
--- a/scripts/config.pl
+++ b/scripts/config.pl
@@ -98,6 +98,7 @@
MBEDTLS_PKCS11_C
MBEDTLS_NO_UDBL_DIVISION
MBEDTLS_NO_64BIT_MULTIPLICATION
+MBEDTLS_USE_UECC
_ALT\s*$
);
diff --git a/tests/data_files/Makefile b/tests/data_files/Makefile
index 43fbe16..d023c8d 100644
--- a/tests/data_files/Makefile
+++ b/tests/data_files/Makefile
@@ -150,7 +150,7 @@
all_final += test-int-ca3-badsign.crt
server10_int3-bs.pem: server10.crt test-int-ca3-badsign.crt
cat server10.crt test-int-ca3-badsign.crt > $@
-all_final += server10-bs_int3-bs.pem
+all_final += server10_int3-bs.pem
rsa_pkcs1_2048_public.pem: server8.key
$(OPENSSL) rsa -in $< -outform PEM -RSAPublicKey_out -out $@
diff --git a/tests/scripts/all.sh b/tests/scripts/all.sh
index 53fbc7e..7bff5bc 100755
--- a/tests/scripts/all.sh
+++ b/tests/scripts/all.sh
@@ -590,6 +590,17 @@
#### Build and test many configurations and targets
################################################################
+component_test_default_out_of_box () {
+ msg "build: make, default config (out-of-box)" # ~1min
+ make
+
+ msg "test: main suites make, default config (out-of-box)" # ~10s
+ make test
+
+ msg "selftest: make, default config (out-of-box)" # ~10s
+ programs/test/selftest
+}
+
component_test_default_cmake_gcc_asan () {
msg "build: cmake, gcc, ASan" # ~ 1 min 50s
CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan .
@@ -952,10 +963,16 @@
# Build again with -O1, to compile in the i386 specific inline assembly
msg "build: i386, make, gcc -O1 (ASan build)" # ~ 30s
scripts/config.pl full
+ scripts/config.pl unset MBEDTLS_MEMORY_BACKTRACE
+ scripts/config.pl unset MBEDTLS_MEMORY_BUFFER_ALLOC_C
+ scripts/config.pl unset MBEDTLS_MEMORY_DEBUG
make CC=gcc CFLAGS='-O1 -Werror -Wall -Wextra -m32 -fsanitize=address'
msg "test: i386, make, gcc -O1 (ASan build)"
make test
+
+ msg "test ssl-opt.sh, i386, make, gcc-O1"
+ if_build_succeeded tests/ssl-opt.sh
}
support_test_m32_o1 () {
support_test_m32_o0 "$@"
@@ -1030,6 +1047,19 @@
make test
}
+component_build_uecc_cmake () {
+ msg "build: uecc native, cmake"
+ scripts/config.pl set MBEDTLS_USE_UECC
+ CC=gcc cmake .
+ make
+}
+
+component_build_uecc_make () {
+ msg "build: uecc native, make"
+ scripts/config.pl set MBEDTLS_USE_UECC
+ make CC=gcc CFLAGS='-Werror -O1'
+}
+
component_build_arm_none_eabi_gcc () {
msg "build: arm-none-eabi-gcc, make" # ~ 10s
scripts/config.pl full
@@ -1125,6 +1155,15 @@
armc6_build_test "--target=aarch64-arm-none-eabi -march=armv8.2-a"
}
+component_build_armcc_uecc_baremetal () {
+ msg "build: ARM Compiler 5, make with uecc and baremetal"
+ scripts/config.pl baremetal
+ scripts/config.pl set MBEDTLS_USE_UECC
+
+ make CC="$ARMC5_CC" AR="$ARMC5_AR" WARNING_CFLAGS='--strict --c99' lib
+ make clean
+}
+
component_test_allow_sha1 () {
msg "build: allow SHA1 in certificates by default"
scripts/config.pl set MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES
@@ -1176,10 +1215,8 @@
msg "test: main suites valgrind (Release)"
make memcheck
- # Optional part(s)
- # Currently broken, programs don't seem to receive signals
- # under valgrind on OS X
-
+ # Optional parts (slow; currently broken on OS X because programs don't
+ # seem to receive signals under valgrind on OS X).
if [ "$MEMORY" -gt 0 ]; then
msg "test: ssl-opt.sh --memcheck (Release)"
if_build_succeeded tests/ssl-opt.sh --memcheck
@@ -1247,6 +1284,9 @@
unset gdb_disable_aslr
}
+support_check_python_files () {
+ type pylint3 >/dev/null 2>/dev/null
+}
component_check_python_files () {
msg "Lint: Python scripts"
record_status tests/scripts/check-python-files.sh
diff --git a/tests/scripts/check-files.py b/tests/scripts/check-files.py
index 005a077..feea36c 100755
--- a/tests/scripts/check-files.py
+++ b/tests/scripts/check-files.py
@@ -19,14 +19,23 @@
import sys
-class IssueTracker(object):
- """Base class for issue tracking. Issues should inherit from this and
- overwrite either issue_with_line if they check the file line by line, or
- overwrite check_file_for_issue if they check the file as a whole."""
+class FileIssueTracker(object):
+ """Base class for file-wide issue tracking.
+
+ To implement a checker that processes a file as a whole, inherit from
+ this class and implement `check_file_for_issue` and define ``heading``.
+
+ ``files_exemptions``: files whose name ends with a string in this set
+ will not be checked.
+
+ ``heading``: human-readable description of the issue
+ """
+
+ files_exemptions = frozenset()
+ # heading must be defined in derived classes.
+ # pylint: disable=no-member
def __init__(self):
- self.heading = ""
- self.files_exemptions = []
self.files_with_issues = {}
def should_check_file(self, filepath):
@@ -35,23 +44,14 @@
return False
return True
- def issue_with_line(self, line):
- raise NotImplementedError
-
def check_file_for_issue(self, filepath):
- with open(filepath, "rb") as f:
- for i, line in enumerate(iter(f.readline, b"")):
- self.check_file_line(filepath, line, i + 1)
+ raise NotImplementedError
def record_issue(self, filepath, line_number):
if filepath not in self.files_with_issues.keys():
self.files_with_issues[filepath] = []
self.files_with_issues[filepath].append(line_number)
- def check_file_line(self, filepath, line, line_number):
- if self.issue_with_line(line):
- self.record_issue(filepath, line_number)
-
def output_file_issues(self, logger):
if self.files_with_issues.values():
logger.info(self.heading)
@@ -64,24 +64,44 @@
logger.info(filename)
logger.info("")
+class LineIssueTracker(FileIssueTracker):
+ """Base class for line-by-line issue tracking.
-class PermissionIssueTracker(IssueTracker):
+ To implement a checker that processes files line by line, inherit from
+ this class and implement `line_with_issue`.
+ """
- def __init__(self):
- super().__init__()
- self.heading = "Incorrect permissions:"
+ def issue_with_line(self, line, filepath):
+ raise NotImplementedError
+
+ def check_file_line(self, filepath, line, line_number):
+ if self.issue_with_line(line, filepath):
+ self.record_issue(filepath, line_number)
def check_file_for_issue(self, filepath):
- if not (os.access(filepath, os.X_OK) ==
- filepath.endswith((".sh", ".pl", ".py"))):
+ with open(filepath, "rb") as f:
+ for i, line in enumerate(iter(f.readline, b"")):
+ self.check_file_line(filepath, line, i + 1)
+
+class PermissionIssueTracker(FileIssueTracker):
+ """Track files with bad permissions.
+
+ Files that are not executable scripts must not be executable."""
+
+ heading = "Incorrect permissions:"
+
+ def check_file_for_issue(self, filepath):
+ is_executable = os.access(filepath, os.X_OK)
+ should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
+ if is_executable != should_be_executable:
self.files_with_issues[filepath] = None
-class EndOfFileNewlineIssueTracker(IssueTracker):
+class EndOfFileNewlineIssueTracker(FileIssueTracker):
+ """Track files that end with an incomplete line
+ (no newline character at the end of the last line)."""
- def __init__(self):
- super().__init__()
- self.heading = "Missing newline at end of file:"
+ heading = "Missing newline at end of file:"
def check_file_for_issue(self, filepath):
with open(filepath, "rb") as f:
@@ -89,11 +109,11 @@
self.files_with_issues[filepath] = None
-class Utf8BomIssueTracker(IssueTracker):
+class Utf8BomIssueTracker(FileIssueTracker):
+ """Track files that start with a UTF-8 BOM.
+ Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
- def __init__(self):
- super().__init__()
- self.heading = "UTF-8 BOM present:"
+ heading = "UTF-8 BOM present:"
def check_file_for_issue(self, filepath):
with open(filepath, "rb") as f:
@@ -101,79 +121,76 @@
self.files_with_issues[filepath] = None
-class LineEndingIssueTracker(IssueTracker):
+class LineEndingIssueTracker(LineIssueTracker):
+ """Track files with non-Unix line endings (i.e. files with CR)."""
- def __init__(self):
- super().__init__()
- self.heading = "Non Unix line endings:"
+ heading = "Non Unix line endings:"
- def issue_with_line(self, line):
+ def issue_with_line(self, line, _filepath):
return b"\r" in line
-class TrailingWhitespaceIssueTracker(IssueTracker):
+class TrailingWhitespaceIssueTracker(LineIssueTracker):
+ """Track lines with trailing whitespace."""
- def __init__(self):
- super().__init__()
- self.heading = "Trailing whitespace:"
- self.files_exemptions = [".md"]
+ heading = "Trailing whitespace:"
+ files_exemptions = frozenset(".md")
- def issue_with_line(self, line):
+ def issue_with_line(self, line, _filepath):
return line.rstrip(b"\r\n") != line.rstrip()
-class TabIssueTracker(IssueTracker):
+class TabIssueTracker(LineIssueTracker):
+ """Track lines with tabs."""
- def __init__(self):
- super().__init__()
- self.heading = "Tabs present:"
- self.files_exemptions = [
- "Makefile", "generate_visualc_files.pl"
- ]
+ heading = "Tabs present:"
+ files_exemptions = frozenset([
+ "Makefile",
+ "generate_visualc_files.pl",
+ ])
- def issue_with_line(self, line):
+ def issue_with_line(self, line, _filepath):
return b"\t" in line
-class MergeArtifactIssueTracker(IssueTracker):
+class MergeArtifactIssueTracker(LineIssueTracker):
+ """Track lines with merge artifacts.
+ These are leftovers from a ``git merge`` that wasn't fully edited."""
- def __init__(self):
- super().__init__()
- self.heading = "Merge artifact:"
+ heading = "Merge artifact:"
- def issue_with_line(self, filepath, line):
+ def issue_with_line(self, line, _filepath):
# Detect leftover git conflict markers.
if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
return True
if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
return True
if line.rstrip(b'\r\n') == b'=======' and \
- not filepath.endswith('.md'):
+ not _filepath.endswith('.md'):
return True
return False
- def check_file_line(self, filepath, line, line_number):
- if self.issue_with_line(filepath, line):
- self.record_issue(filepath, line_number)
+class TodoIssueTracker(LineIssueTracker):
+ """Track lines containing ``TODO``."""
-class TodoIssueTracker(IssueTracker):
+ heading = "TODO present:"
+ files_exemptions = frozenset([
+ os.path.basename(__file__),
+ "benchmark.c",
+ "pull_request_template.md",
+ ])
- def __init__(self):
- super().__init__()
- self.heading = "TODO present:"
- self.files_exemptions = [
- os.path.basename(__file__),
- "benchmark.c",
- "pull_request_template.md",
- ]
-
- def issue_with_line(self, line):
+ def issue_with_line(self, line, _filepath):
return b"todo" in line.lower()
class IntegrityChecker(object):
+ """Sanity-check files under the current directory."""
def __init__(self, log_file):
+ """Instantiate the sanity checker.
+ Check files under the current directory.
+ Write a report of issues to log_file."""
self.check_repo_path()
self.logger = None
self.setup_logger(log_file)
@@ -181,7 +198,7 @@
".c", ".h", ".sh", ".pl", ".py", ".md", ".function", ".data",
"Makefile", "CMakeLists.txt", "ChangeLog"
)
- self.excluded_directories = ['.git', 'mbed-os']
+ self.excluded_directories = ['.git', 'mbed-os', 'tinycrypt']
self.excluded_paths = list(map(os.path.normpath, [
'cov-int',
'examples',
@@ -197,7 +214,8 @@
TodoIssueTracker(),
]
- def check_repo_path(self):
+ @staticmethod
+ def check_repo_path():
if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
raise Exception("Must be run from Mbed TLS root")
diff --git a/tests/scripts/check-names.sh b/tests/scripts/check-names.sh
index f18a162..6d9ab0e 100755
--- a/tests/scripts/check-names.sh
+++ b/tests/scripts/check-names.sh
@@ -26,14 +26,21 @@
FAIL=0
printf "\nExported symbols declared in header: "
-UNDECLARED=$( diff exported-symbols identifiers | sed -n -e 's/^< //p' )
-if [ "x$UNDECLARED" = "x" ]; then
+UNDECLARED=$(diff exported-symbols identifiers | sed -n -e 's/^< //p') > undeclared
+
+FILTERED=$( diff tests/scripts/whitelist undeclared | sed -n -e 's/^< //p')
+
+if [ "x$UNDECLARED" != "x" ]; then
+if [ "x$FILTERED" = "x" ]; then
echo "PASS"
else
echo "FAIL"
- echo "$UNDECLARED"
+ echo "$FILTERED"
FAIL=1
fi
+else
+ echo "PASS"
+fi
diff macros identifiers | sed -n -e 's/< //p' > actual-macros
@@ -84,7 +91,7 @@
printf "\nOverall: "
if [ "$FAIL" -eq 0 ]; then
- rm macros actual-macros enum-consts identifiers exported-symbols
+ rm macros actual-macros enum-consts identifiers exported-symbols undeclared
echo "PASSED"
exit 0
else
diff --git a/tests/scripts/check-python-files.sh b/tests/scripts/check-python-files.sh
index 009ba4c..9290418 100755
--- a/tests/scripts/check-python-files.sh
+++ b/tests/scripts/check-python-files.sh
@@ -9,10 +9,4 @@
# Run 'pylint' on Python files for programming errors and helps enforcing
# PEP8 coding standards.
-if `hash pylint > /dev/null 2>&1`; then
- pylint -j 2 tests/scripts/generate_test_code.py --rcfile .pylint
- pylint -j 2 tests/scripts/test_generate_test_code.py --rcfile .pylint
- pylint -j 2 tests/scripts/mbedtls_test.py --rcfile .pylint
-else
- echo "$0: WARNING: 'pylint' not found! Skipping checks on Python files."
-fi
+pylint3 -j 2 scripts/*.py tests/scripts/*.py
diff --git a/tests/scripts/generate_test_code.py b/tests/scripts/generate_test_code.py
index 1258024..1fff099 100755
--- a/tests/scripts/generate_test_code.py
+++ b/tests/scripts/generate_test_code.py
@@ -238,7 +238,7 @@
if hasattr(parent, '__next__'):
line = parent.__next__() # Python 3
else:
- line = parent.next() # Python 2
+ line = parent.next() # Python 2 # pylint: disable=no-member
if line is not None:
self._line_no += 1
# Convert byte array to string with correct encoding and
diff --git a/tests/scripts/mbedtls_test.py b/tests/scripts/mbedtls_test.py
index c702765..ac2912d 100755
--- a/tests/scripts/mbedtls_test.py
+++ b/tests/scripts/mbedtls_test.py
@@ -37,7 +37,8 @@
import re
import os
import binascii
-from mbed_host_tests import BaseHostTest, event_callback
+
+from mbed_host_tests import BaseHostTest, event_callback # pylint: disable=import-error
class TestDataParserError(Exception):
diff --git a/tests/scripts/test_generate_test_code.py b/tests/scripts/test_generate_test_code.py
index 2ef12e1..6d7113e 100755
--- a/tests/scripts/test_generate_test_code.py
+++ b/tests/scripts/test_generate_test_code.py
@@ -22,7 +22,7 @@
Unit tests for generate_test_code.py
"""
-
+# pylint: disable=wrong-import-order
try:
# Python 2
from StringIO import StringIO
@@ -36,6 +36,7 @@
except ImportError:
# Python 3
from unittest.mock import patch
+# pylint: enable=wrong-import-order
from generate_test_code import gen_dependencies, gen_dependencies_one_line
from generate_test_code import gen_function_wrapper, gen_dispatch
from generate_test_code import parse_until_pattern, GeneratorInputError
@@ -336,6 +337,7 @@
:param length:
:return:
"""
+ # pylint: disable=unused-argument
line = super(StringIOWrapper, self).readline()
if line is not None:
self.line_no += 1
diff --git a/tests/scripts/whitelist b/tests/scripts/whitelist
new file mode 100644
index 0000000..99c4060
--- /dev/null
+++ b/tests/scripts/whitelist
@@ -0,0 +1,38 @@
+EccPoint_compute_public_key
+EccPoint_isZero
+EccPoint_mult
+regularize_k
+uECC_compute_public_key
+uECC_curve_private_key_size
+uECC_curve_public_key_size
+uECC_generate_random_int
+uECC_get_rng
+uECC_make_key
+uECC_make_key_with_d
+uECC_secp256r1
+uECC_set_rng
+uECC_shared_secret
+uECC_sign
+uECC_sign_with_k
+uECC_valid_point
+uECC_valid_public_key
+uECC_verify
+uECC_vli_bytesToNative
+uECC_vli_clear
+uECC_vli_cmp
+uECC_vli_cmp_unsafe
+uECC_vli_equal
+uECC_vli_isZero
+uECC_vli_mmod
+uECC_vli_modAdd
+uECC_vli_modInv
+uECC_vli_modMult
+uECC_vli_modMult_fast
+uECC_vli_modSub
+uECC_vli_nativeToBytes
+uECC_vli_numBits
+uECC_vli_set
+uECC_vli_sub
+uECC_vli_testBit
+vli_mmod_fast_secp256r1
+x_side_default
diff --git a/tests/ssl-opt.sh b/tests/ssl-opt.sh
index 9a96294..bd4f21d 100755
--- a/tests/ssl-opt.sh
+++ b/tests/ssl-opt.sh
@@ -1112,6 +1112,103 @@
-S "dumping 'expected mac' (20 bytes)" \
-s "dumping 'expected mac' (10 bytes)"
+# Tests for DTLS Connection ID extension
+
+# So far, the CID API isn't implemented, so we can't
+# grep for output witnessing its use. This needs to be
+# changed once the CID extension is implemented.
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client enabled, server disabled" \
+ "$P_SRV dtls=1 cid=0" \
+ "$P_CLI dtls=1 cid=1 cid_val=deadbeef" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client disabled, server enabled" \
+ "$P_SRV dtls=1 cid=1 cid_val=deadbeef" \
+ "$P_CLI dtls=1 cid=0" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Client+Server CID nonempty" \
+ "$P_SRV dtls=1 cid=1 cid_val=dead" \
+ "$P_CLI dtls=1 cid=1 cid_val=beef" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Client CID empty" \
+ "$P_SRV dtls=1 cid=1 cid_val=deadbeef" \
+ "$P_CLI dtls=1 cid=1" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Server CID empty" \
+ "$P_SRV dtls=1 cid=1" \
+ "$P_CLI dtls=1 cid=1 cid_val=deadbeef" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Client+Server CID empty" \
+ "$P_SRV dtls=1 cid=1" \
+ "$P_CLI dtls=1 cid=1" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Client+Server CID nonempty, AES-128-CCM-8" \
+ "$P_SRV dtls=1 cid=1 cid_val=dead" \
+ "$P_CLI dtls=1 cid=1 cid_val=beef force_ciphersuite=TLS-ECDHE-ECDSA-WITH-AES-128-CCM-8" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Client CID empty, AES-128-CCM-8" \
+ "$P_SRV dtls=1 cid=1 cid_val=deadbeef" \
+ "$P_CLI dtls=1 cid=1 force_ciphersuite=TLS-ECDHE-ECDSA-WITH-AES-128-CCM-8" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Server CID empty, AES-128-CCM-8" \
+ "$P_SRV dtls=1 cid=1" \
+ "$P_CLI dtls=1 cid=1 cid_val=deadbeef force_ciphersuite=TLS-ECDHE-ECDSA-WITH-AES-128-CCM-8" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Client+Server CID empty, AES-128-CCM-8" \
+ "$P_SRV dtls=1 cid=1" \
+ "$P_CLI dtls=1 cid=1 force_ciphersuite=TLS-ECDHE-ECDSA-WITH-AES-128-CCM-8" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Client+Server CID nonempty, AES-128-CBC" \
+ "$P_SRV dtls=1 cid=1 cid_val=dead" \
+ "$P_CLI dtls=1 cid=1 cid_val=beef force_ciphersuite=TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Client CID empty, AES-128-CBC" \
+ "$P_SRV dtls=1 cid=1 cid_val=deadbeef" \
+ "$P_CLI dtls=1 cid=1 force_ciphersuite=TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Server CID empty, AES-128-CBC" \
+ "$P_SRV dtls=1 cid=1" \
+ "$P_CLI dtls=1 cid=1 cid_val=deadbeef force_ciphersuite=TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+run_test "(STUB) Connection ID: Client+Server enabled, Client+Server CID empty, AES-128-CBC" \
+ "$P_SRV dtls=1 cid=1" \
+ "$P_CLI dtls=1 cid=1 force_ciphersuite=TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256" \
+ 0
+
+requires_config_enabled MBEDTLS_SSL_CID
+requires_config_enabled MBEDTLS_SSL_RENEGOTIATION
+run_test "(STUB) Connection ID: Client+Server enabled, renegotiate" \
+ "$P_SRV dtls=1 cid=1 cid_val=dead renegotiation=1" \
+ "$P_CLI dtls=1 cid=1 cid_val=beef renegotiation=1 renegotiate=1" \
+ 0
+
# Tests for Encrypt-then-MAC extension
run_test "Encrypt then MAC: default" \
diff --git a/tests/suites/test_suite_cipher.function b/tests/suites/test_suite_cipher.function
index 773c792..54fe1a3 100644
--- a/tests/suites/test_suite_cipher.function
+++ b/tests/suites/test_suite_cipher.function
@@ -976,6 +976,9 @@
TEST_ASSERT( memcmp( output, clear->x, clear->len ) == 0 );
/* then encrypt the clear->x and make sure we get the same ciphertext and tag->x */
+ TEST_ASSERT( 0 == mbedtls_cipher_setkey( &ctx, key->x, 8 * key->len,
+ MBEDTLS_ENCRYPT ) );
+
memset( output, 0xFF, sizeof( output ) );
outlen = 0;
@@ -984,8 +987,8 @@
my_tag, tag->len );
TEST_ASSERT( ret == 0 );
- TEST_ASSERT( outlen == clear->len );
- TEST_ASSERT( memcmp( output, cipher->x, clear->len ) == 0 );
+ TEST_ASSERT( outlen == cipher->len );
+ TEST_ASSERT( memcmp( output, cipher->x, cipher->len ) == 0 );
TEST_ASSERT( memcmp( my_tag, tag->x, tag->len ) == 0 );
/* make sure we didn't overwrite */
diff --git a/tests/suites/test_suite_ecdh.data b/tests/suites/test_suite_ecdh.data
index fe24ed4..af25359 100644
--- a/tests/suites/test_suite_ecdh.data
+++ b/tests/suites/test_suite_ecdh.data
@@ -79,3 +79,19 @@
ECDH exchange legacy context
depends_on:MBEDTLS_ECP_DP_SECP192R1_ENABLED
ecdh_exchange_legacy:MBEDTLS_ECP_DP_SECP192R1
+
+ECDH calc_secret: ours first, SECP256R1 (RFC 5903)
+depends_on:MBEDTLS_ECP_DP_SECP256R1_ENABLED
+ecdh_exchange_calc_secret:MBEDTLS_ECP_DP_SECP256R1:"c6ef9c5d78ae012a011164acb397ce2088685d8f06bf9be0b283ab46476bee53":"04dad0b65394221cf9b051e1feca5787d098dfe637fc90b9ef945d0c37725811805271a0461cdb8252d61f1c456fa3e59ab1f45b33accf5f58389e0577b8990bb3":0:"d6840f6b42f6edafd13116e0e12565202fef8e9ece7dce03812464d04b9442de"
+
+ECDH calc_secret: theirs first, SECP256R1 (RFC 5903)
+depends_on:MBEDTLS_ECP_DP_SECP256R1_ENABLED
+ecdh_exchange_calc_secret:MBEDTLS_ECP_DP_SECP256R1:"c6ef9c5d78ae012a011164acb397ce2088685d8f06bf9be0b283ab46476bee53":"04dad0b65394221cf9b051e1feca5787d098dfe637fc90b9ef945d0c37725811805271a0461cdb8252d61f1c456fa3e59ab1f45b33accf5f58389e0577b8990bb3":1:"d6840f6b42f6edafd13116e0e12565202fef8e9ece7dce03812464d04b9442de"
+
+ECDH get_params with mismatched groups: our BP256R1, their SECP256R1
+depends_on:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_ECP_DP_BP256R1_ENABLED
+ecdh_exchange_get_params_fail:MBEDTLS_ECP_DP_BP256R1:"1234567812345678123456781234567812345678123456781234567812345678":MBEDTLS_ECP_DP_SECP256R1:"04dad0b65394221cf9b051e1feca5787d098dfe637fc90b9ef945d0c37725811805271a0461cdb8252d61f1c456fa3e59ab1f45b33accf5f58389e0577b8990bb3":0:MBEDTLS_ERR_ECP_BAD_INPUT_DATA
+
+ECDH get_params with mismatched groups: their SECP256R1, our BP256R1
+depends_on:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_ECP_DP_BP256R1_ENABLED
+ecdh_exchange_get_params_fail:MBEDTLS_ECP_DP_BP256R1:"1234567812345678123456781234567812345678123456781234567812345678":MBEDTLS_ECP_DP_SECP256R1:"04dad0b65394221cf9b051e1feca5787d098dfe637fc90b9ef945d0c37725811805271a0461cdb8252d61f1c456fa3e59ab1f45b33accf5f58389e0577b8990bb3":1:MBEDTLS_ERR_ECP_BAD_INPUT_DATA
diff --git a/tests/suites/test_suite_ecdh.function b/tests/suites/test_suite_ecdh.function
index 08a1686..9a9cf5f 100644
--- a/tests/suites/test_suite_ecdh.function
+++ b/tests/suites/test_suite_ecdh.function
@@ -1,5 +1,41 @@
/* BEGIN_HEADER */
#include "mbedtls/ecdh.h"
+
+static int load_public_key( int grp_id, data_t *point,
+ mbedtls_ecp_keypair *ecp )
+{
+ int ok = 0;
+ TEST_ASSERT( mbedtls_ecp_group_load( &ecp->grp, grp_id ) == 0 );
+ TEST_ASSERT( mbedtls_ecp_point_read_binary( &ecp->grp,
+ &ecp->Q,
+ point->x,
+ point->len ) == 0 );
+ TEST_ASSERT( mbedtls_ecp_check_pubkey( &ecp->grp,
+ &ecp->Q ) == 0 );
+ ok = 1;
+exit:
+ return( ok );
+}
+
+static int load_private_key( int grp_id, data_t *private_key,
+ mbedtls_ecp_keypair *ecp,
+ rnd_pseudo_info *rnd_info )
+{
+ int ok = 0;
+ TEST_ASSERT( mbedtls_ecp_group_load( &ecp->grp, grp_id ) == 0 );
+ TEST_ASSERT( mbedtls_mpi_read_binary( &ecp->d,
+ private_key->x,
+ private_key->len ) == 0 );
+ TEST_ASSERT( mbedtls_ecp_check_privkey( &ecp->grp, &ecp->d ) == 0 );
+ /* Calculate the public key from the private key. */
+ TEST_ASSERT( mbedtls_ecp_mul( &ecp->grp, &ecp->Q, &ecp->d,
+ &ecp->grp.G,
+ &rnd_pseudo_rand, rnd_info ) == 0 );
+ ok = 1;
+exit:
+ return( ok );
+}
+
/* END_HEADER */
/* BEGIN_DEPENDENCIES
@@ -464,3 +500,107 @@
mbedtls_ecdh_free( &cli );
}
/* END_CASE */
+
+/* BEGIN_CASE */
+void ecdh_exchange_calc_secret( int grp_id,
+ data_t *our_private_key,
+ data_t *their_point,
+ int ours_first,
+ data_t *expected )
+{
+ rnd_pseudo_info rnd_info;
+ mbedtls_ecp_keypair our_key;
+ mbedtls_ecp_keypair their_key;
+ mbedtls_ecdh_context ecdh;
+ unsigned char shared_secret[MBEDTLS_ECP_MAX_BYTES];
+ size_t shared_secret_length = 0;
+
+ memset( &rnd_info, 0x00, sizeof( rnd_pseudo_info ) );
+ mbedtls_ecdh_init( &ecdh );
+ mbedtls_ecp_keypair_init( &our_key );
+ mbedtls_ecp_keypair_init( &their_key );
+
+ if( ! load_private_key( grp_id, our_private_key, &our_key, &rnd_info ) )
+ goto exit;
+ if( ! load_public_key( grp_id, their_point, &their_key ) )
+ goto exit;
+
+ /* Import the keys to the ECDH calculation. */
+ if( ours_first )
+ {
+ TEST_ASSERT( mbedtls_ecdh_get_params(
+ &ecdh, &our_key, MBEDTLS_ECDH_OURS ) == 0 );
+ TEST_ASSERT( mbedtls_ecdh_get_params(
+ &ecdh, &their_key, MBEDTLS_ECDH_THEIRS ) == 0 );
+ }
+ else
+ {
+ TEST_ASSERT( mbedtls_ecdh_get_params(
+ &ecdh, &their_key, MBEDTLS_ECDH_THEIRS ) == 0 );
+ TEST_ASSERT( mbedtls_ecdh_get_params(
+ &ecdh, &our_key, MBEDTLS_ECDH_OURS ) == 0 );
+ }
+
+ /* Perform the ECDH calculation. */
+ TEST_ASSERT( mbedtls_ecdh_calc_secret(
+ &ecdh,
+ &shared_secret_length,
+ shared_secret, sizeof( shared_secret ),
+ &rnd_pseudo_rand, &rnd_info ) == 0 );
+ TEST_ASSERT( shared_secret_length == expected->len );
+ TEST_ASSERT( memcmp( expected->x, shared_secret,
+ shared_secret_length ) == 0 );
+
+exit:
+ mbedtls_ecdh_free( &ecdh );
+ mbedtls_ecp_keypair_free( &our_key );
+ mbedtls_ecp_keypair_free( &their_key );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void ecdh_exchange_get_params_fail( int our_grp_id,
+ data_t *our_private_key,
+ int their_grp_id,
+ data_t *their_point,
+ int ours_first,
+ int expected_ret )
+{
+ rnd_pseudo_info rnd_info;
+ mbedtls_ecp_keypair our_key;
+ mbedtls_ecp_keypair their_key;
+ mbedtls_ecdh_context ecdh;
+
+ memset( &rnd_info, 0x00, sizeof( rnd_pseudo_info ) );
+ mbedtls_ecdh_init( &ecdh );
+ mbedtls_ecp_keypair_init( &our_key );
+ mbedtls_ecp_keypair_init( &their_key );
+
+ if( ! load_private_key( our_grp_id, our_private_key, &our_key, &rnd_info ) )
+ goto exit;
+ if( ! load_public_key( their_grp_id, their_point, &their_key ) )
+ goto exit;
+
+ if( ours_first )
+ {
+ TEST_ASSERT( mbedtls_ecdh_get_params(
+ &ecdh, &our_key, MBEDTLS_ECDH_OURS ) == 0 );
+ TEST_ASSERT( mbedtls_ecdh_get_params(
+ &ecdh, &their_key, MBEDTLS_ECDH_THEIRS ) ==
+ expected_ret );
+ }
+ else
+ {
+ TEST_ASSERT( mbedtls_ecdh_get_params(
+ &ecdh, &their_key, MBEDTLS_ECDH_THEIRS ) == 0 );
+ TEST_ASSERT( mbedtls_ecdh_get_params(
+ &ecdh, &our_key, MBEDTLS_ECDH_OURS ) ==
+ expected_ret );
+ }
+
+exit:
+ mbedtls_ecdh_free( &ecdh );
+ mbedtls_ecp_keypair_free( &our_key );
+ mbedtls_ecp_keypair_free( &their_key );
+}
+/* END_CASE */
diff --git a/tests/suites/test_suite_hkdf.function b/tests/suites/test_suite_hkdf.function
index c85a51a..3e87207 100644
--- a/tests/suites/test_suite_hkdf.function
+++ b/tests/suites/test_suite_hkdf.function
@@ -14,12 +14,16 @@
{
int ret;
size_t ikm_len, salt_len, info_len, okm_len;
- unsigned char ikm[1024] = { '\0' };
- unsigned char salt[1024] = { '\0' };
- unsigned char info[1024] = { '\0' };
- unsigned char expected_okm[1024] = { '\0' };
- unsigned char okm[1024] = { '\0' };
- unsigned char okm_string[1000] = { '\0' };
+ unsigned char ikm[128] = { '\0' };
+ unsigned char salt[128] = { '\0' };
+ unsigned char info[128] = { '\0' };
+ unsigned char expected_okm[128] = { '\0' };
+ unsigned char okm[128] = { '\0' };
+ /*
+ * okm_hex is the string representation of okm,
+ * so its size is twice the size of okm, and an extra null-termination.
+ */
+ unsigned char okm_hex[257] = { '\0' };
const mbedtls_md_info_t *md = mbedtls_md_info_from_type( md_alg );
TEST_ASSERT( md != NULL );
@@ -34,8 +38,8 @@
TEST_ASSERT( ret == 0 );
// Run hexify on it so that it looks nicer if the assertion fails
- hexify( okm_string, okm, okm_len );
- TEST_ASSERT( !strcmp( (char *)okm_string, hex_okm_string ) );
+ hexify( okm_hex, okm, okm_len );
+ TEST_ASSERT( !strcmp( (char *)okm_hex, hex_okm_string ) );
}
/* END_CASE */
diff --git a/tests/suites/test_suite_mpi.data b/tests/suites/test_suite_mpi.data
index 8b5f97d..425e93a 100644
--- a/tests/suites/test_suite_mpi.data
+++ b/tests/suites/test_suite_mpi.data
@@ -25,6 +25,9 @@
Base test mpi_read_write_string #3 (Negative decimal)
mpi_read_write_string:16:"-23":16:"-23":100:0:0
+Base test mpi_read_write_string #4 (Buffer just fits)
+mpi_read_write_string:16:"-4":4:"-10":4:0:0
+
Test mpi_read_write_string #1 (Invalid character)
mpi_read_write_string:10:"a28":0:"":100:MBEDTLS_ERR_MPI_INVALID_CHARACTER:0
diff --git a/tests/suites/test_suite_mpi.function b/tests/suites/test_suite_mpi.function
index d1fa5a4..f982385 100644
--- a/tests/suites/test_suite_mpi.function
+++ b/tests/suites/test_suite_mpi.function
@@ -294,6 +294,8 @@
mbedtls_mpi_init( &X );
+ memset( str, '!', sizeof( str ) );
+
TEST_ASSERT( mbedtls_mpi_read_string( &X, radix_X, input_X ) == result_read );
if( result_read == 0 )
{
@@ -301,6 +303,7 @@
if( result_write == 0 )
{
TEST_ASSERT( strcasecmp( str, input_A ) == 0 );
+ TEST_ASSERT( str[len] == '!' );
}
}
diff --git a/tests/suites/test_suite_version.data b/tests/suites/test_suite_version.data
index 62bb782..40fc923 100644
--- a/tests/suites/test_suite_version.data
+++ b/tests/suites/test_suite_version.data
@@ -1,8 +1,8 @@
Check compiletime library version
-check_compiletime_version:"2.16.0"
+check_compiletime_version:"2.16.1"
Check runtime library version
-check_runtime_version:"2.16.0"
+check_runtime_version:"2.16.1"
Check for MBEDTLS_VERSION_C
check_feature:"MBEDTLS_VERSION_C":0
diff --git a/tinycrypt/CMakeLists.txt b/tinycrypt/CMakeLists.txt
new file mode 100644
index 0000000..7674d83
--- /dev/null
+++ b/tinycrypt/CMakeLists.txt
@@ -0,0 +1,7 @@
+set(src_tinycrypt
+ ecc_dh.c
+ ecc_dsa.c
+ ecc.c
+)
+
+add_library(tinycrypt STATIC ${src_tinycrypt})
diff --git a/tinycrypt/ecc.c b/tinycrypt/ecc.c
new file mode 100644
index 0000000..090f691
--- /dev/null
+++ b/tinycrypt/ecc.c
@@ -0,0 +1,943 @@
+/* ecc.c - TinyCrypt implementation of common ECC functions */
+
+/*
+ * Copyright (c) 2014, Kenneth MacKay
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Copyright (C) 2017 by Intel Corporation, All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#if defined(MBEDTLS_USE_UECC)
+#include <tinycrypt/ecc.h>
+#include <string.h>
+
+/* IMPORTANT: Make sure a cryptographically-secure PRNG is set and the platform
+ * has access to enough entropy in order to feed the PRNG regularly. */
+#if default_RNG_defined
+static uECC_RNG_Function g_rng_function = &default_CSPRNG;
+#else
+static uECC_RNG_Function g_rng_function = 0;
+#endif
+
+void uECC_set_rng(uECC_RNG_Function rng_function)
+{
+ g_rng_function = rng_function;
+}
+
+uECC_RNG_Function uECC_get_rng(void)
+{
+ return g_rng_function;
+}
+
+int uECC_curve_private_key_size(uECC_Curve curve)
+{
+ return BITS_TO_BYTES(curve->num_n_bits);
+}
+
+int uECC_curve_public_key_size(uECC_Curve curve)
+{
+ return 2 * curve->num_bytes;
+}
+
+void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words)
+{
+ wordcount_t i;
+ for (i = 0; i < num_words; ++i) {
+ vli[i] = 0;
+ }
+}
+
+uECC_word_t uECC_vli_isZero(const uECC_word_t *vli, wordcount_t num_words)
+{
+ uECC_word_t bits = 0;
+ wordcount_t i;
+ for (i = 0; i < num_words; ++i) {
+ bits |= vli[i];
+ }
+ return (bits == 0);
+}
+
+uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit)
+{
+ return (vli[bit >> uECC_WORD_BITS_SHIFT] &
+ ((uECC_word_t)1 << (bit & uECC_WORD_BITS_MASK)));
+}
+
+/* Counts the number of words in vli. */
+static wordcount_t vli_numDigits(const uECC_word_t *vli,
+ const wordcount_t max_words)
+{
+
+ wordcount_t i;
+ /* Search from the end until we find a non-zero digit. We do it in reverse
+ * because we expect that most digits will be nonzero. */
+ for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {
+ }
+
+ return (i + 1);
+}
+
+bitcount_t uECC_vli_numBits(const uECC_word_t *vli,
+ const wordcount_t max_words)
+{
+
+ uECC_word_t i;
+ uECC_word_t digit;
+
+ wordcount_t num_digits = vli_numDigits(vli, max_words);
+ if (num_digits == 0) {
+ return 0;
+ }
+
+ digit = vli[num_digits - 1];
+ for (i = 0; digit; ++i) {
+ digit >>= 1;
+ }
+
+ return (((bitcount_t)(num_digits - 1) << uECC_WORD_BITS_SHIFT) + i);
+}
+
+void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src,
+ wordcount_t num_words)
+{
+ wordcount_t i;
+
+ for (i = 0; i < num_words; ++i) {
+ dest[i] = src[i];
+ }
+}
+
+cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left,
+ const uECC_word_t *right,
+ wordcount_t num_words)
+{
+ wordcount_t i;
+
+ for (i = num_words - 1; i >= 0; --i) {
+ if (left[i] > right[i]) {
+ return 1;
+ } else if (left[i] < right[i]) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right,
+ wordcount_t num_words)
+{
+
+ uECC_word_t diff = 0;
+ wordcount_t i;
+
+ for (i = num_words - 1; i >= 0; --i) {
+ diff |= (left[i] ^ right[i]);
+ }
+ return !(diff == 0);
+}
+
+uECC_word_t cond_set(uECC_word_t p_true, uECC_word_t p_false, unsigned int cond)
+{
+ return (p_true*(cond)) | (p_false*(!cond));
+}
+
+/* Computes result = left - right, returning borrow, in constant time.
+ * Can modify in place. */
+uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, wordcount_t num_words)
+{
+ uECC_word_t borrow = 0;
+ wordcount_t i;
+ for (i = 0; i < num_words; ++i) {
+ uECC_word_t diff = left[i] - right[i] - borrow;
+ uECC_word_t val = (diff > left[i]);
+ borrow = cond_set(val, borrow, (diff != left[i]));
+
+ result[i] = diff;
+ }
+ return borrow;
+}
+
+/* Computes result = left + right, returning carry, in constant time.
+ * Can modify in place. */
+static uECC_word_t uECC_vli_add(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, wordcount_t num_words)
+{
+ uECC_word_t carry = 0;
+ wordcount_t i;
+ for (i = 0; i < num_words; ++i) {
+ uECC_word_t sum = left[i] + right[i] + carry;
+ uECC_word_t val = (sum < left[i]);
+ carry = cond_set(val, carry, (sum != left[i]));
+ result[i] = sum;
+ }
+ return carry;
+}
+
+cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right,
+ wordcount_t num_words)
+{
+ uECC_word_t tmp[NUM_ECC_WORDS];
+ uECC_word_t neg = !!uECC_vli_sub(tmp, left, right, num_words);
+ uECC_word_t equal = uECC_vli_isZero(tmp, num_words);
+ return (!equal - 2 * neg);
+}
+
+/* Computes vli = vli >> 1. */
+static void uECC_vli_rshift1(uECC_word_t *vli, wordcount_t num_words)
+{
+ uECC_word_t *end = vli;
+ uECC_word_t carry = 0;
+
+ vli += num_words;
+ while (vli-- > end) {
+ uECC_word_t temp = *vli;
+ *vli = (temp >> 1) | carry;
+ carry = temp << (uECC_WORD_BITS - 1);
+ }
+}
+
+static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0,
+ uECC_word_t *r1, uECC_word_t *r2)
+{
+
+ uECC_dword_t p = (uECC_dword_t)a * b;
+ uECC_dword_t r01 = ((uECC_dword_t)(*r1) << uECC_WORD_BITS) | *r0;
+ r01 += p;
+ *r2 += (r01 < p);
+ *r1 = r01 >> uECC_WORD_BITS;
+ *r0 = (uECC_word_t)r01;
+
+}
+
+/* Computes result = left * right. Result must be 2 * num_words long. */
+static void uECC_vli_mult(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, wordcount_t num_words)
+{
+
+ uECC_word_t r0 = 0;
+ uECC_word_t r1 = 0;
+ uECC_word_t r2 = 0;
+ wordcount_t i, k;
+
+ /* Compute each digit of result in sequence, maintaining the carries. */
+ for (k = 0; k < num_words; ++k) {
+
+ for (i = 0; i <= k; ++i) {
+ muladd(left[i], right[k - i], &r0, &r1, &r2);
+ }
+
+ result[k] = r0;
+ r0 = r1;
+ r1 = r2;
+ r2 = 0;
+ }
+
+ for (k = num_words; k < num_words * 2 - 1; ++k) {
+
+ for (i = (k + 1) - num_words; i < num_words; ++i) {
+ muladd(left[i], right[k - i], &r0, &r1, &r2);
+ }
+ result[k] = r0;
+ r0 = r1;
+ r1 = r2;
+ r2 = 0;
+ }
+ result[num_words * 2 - 1] = r0;
+}
+
+void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, const uECC_word_t *mod,
+ wordcount_t num_words)
+{
+ uECC_word_t carry = uECC_vli_add(result, left, right, num_words);
+ if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) {
+ /* result > mod (result = mod + remainder), so subtract mod to get
+ * remainder. */
+ uECC_vli_sub(result, result, mod, num_words);
+ }
+}
+
+void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, const uECC_word_t *mod,
+ wordcount_t num_words)
+{
+ uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words);
+ if (l_borrow) {
+ /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
+ * we can get the correct result from result + mod (with overflow). */
+ uECC_vli_add(result, result, mod, num_words);
+ }
+}
+
+/* Computes result = product % mod, where product is 2N words long. */
+/* Currently only designed to work for curve_p or curve_n. */
+void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product,
+ const uECC_word_t *mod, wordcount_t num_words)
+{
+ uECC_word_t mod_multiple[2 * NUM_ECC_WORDS];
+ uECC_word_t tmp[2 * NUM_ECC_WORDS];
+ uECC_word_t *v[2] = {tmp, product};
+ uECC_word_t index;
+
+ /* Shift mod so its highest set bit is at the maximum position. */
+ bitcount_t shift = (num_words * 2 * uECC_WORD_BITS) -
+ uECC_vli_numBits(mod, num_words);
+ wordcount_t word_shift = shift / uECC_WORD_BITS;
+ wordcount_t bit_shift = shift % uECC_WORD_BITS;
+ uECC_word_t carry = 0;
+ uECC_vli_clear(mod_multiple, word_shift);
+ if (bit_shift > 0) {
+ for(index = 0; index < (uECC_word_t)num_words; ++index) {
+ mod_multiple[word_shift + index] = (mod[index] << bit_shift) | carry;
+ carry = mod[index] >> (uECC_WORD_BITS - bit_shift);
+ }
+ } else {
+ uECC_vli_set(mod_multiple + word_shift, mod, num_words);
+ }
+
+ for (index = 1; shift >= 0; --shift) {
+ uECC_word_t borrow = 0;
+ wordcount_t i;
+ for (i = 0; i < num_words * 2; ++i) {
+ uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow;
+ if (diff != v[index][i]) {
+ borrow = (diff > v[index][i]);
+ }
+ v[1 - index][i] = diff;
+ }
+ /* Swap the index if there was no borrow */
+ index = !(index ^ borrow);
+ uECC_vli_rshift1(mod_multiple, num_words);
+ mod_multiple[num_words - 1] |= mod_multiple[num_words] <<
+ (uECC_WORD_BITS - 1);
+ uECC_vli_rshift1(mod_multiple + num_words, num_words);
+ }
+ uECC_vli_set(result, v[index], num_words);
+}
+
+void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, const uECC_word_t *mod,
+ wordcount_t num_words)
+{
+ uECC_word_t product[2 * NUM_ECC_WORDS];
+ uECC_vli_mult(product, left, right, num_words);
+ uECC_vli_mmod(result, product, mod, num_words);
+}
+
+void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left,
+ const uECC_word_t *right, uECC_Curve curve)
+{
+ uECC_word_t product[2 * NUM_ECC_WORDS];
+ uECC_vli_mult(product, left, right, curve->num_words);
+
+ curve->mmod_fast(result, product);
+}
+
+static void uECC_vli_modSquare_fast(uECC_word_t *result,
+ const uECC_word_t *left,
+ uECC_Curve curve)
+{
+ uECC_vli_modMult_fast(result, left, left, curve);
+}
+
+
+#define EVEN(vli) (!(vli[0] & 1))
+
+static void vli_modInv_update(uECC_word_t *uv,
+ const uECC_word_t *mod,
+ wordcount_t num_words)
+{
+
+ uECC_word_t carry = 0;
+
+ if (!EVEN(uv)) {
+ carry = uECC_vli_add(uv, uv, mod, num_words);
+ }
+ uECC_vli_rshift1(uv, num_words);
+ if (carry) {
+ uv[num_words - 1] |= HIGH_BIT_SET;
+ }
+}
+
+void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input,
+ const uECC_word_t *mod, wordcount_t num_words)
+{
+ uECC_word_t a[NUM_ECC_WORDS], b[NUM_ECC_WORDS];
+ uECC_word_t u[NUM_ECC_WORDS], v[NUM_ECC_WORDS];
+ cmpresult_t cmpResult;
+
+ if (uECC_vli_isZero(input, num_words)) {
+ uECC_vli_clear(result, num_words);
+ return;
+ }
+
+ uECC_vli_set(a, input, num_words);
+ uECC_vli_set(b, mod, num_words);
+ uECC_vli_clear(u, num_words);
+ u[0] = 1;
+ uECC_vli_clear(v, num_words);
+ while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) {
+ if (EVEN(a)) {
+ uECC_vli_rshift1(a, num_words);
+ vli_modInv_update(u, mod, num_words);
+ } else if (EVEN(b)) {
+ uECC_vli_rshift1(b, num_words);
+ vli_modInv_update(v, mod, num_words);
+ } else if (cmpResult > 0) {
+ uECC_vli_sub(a, a, b, num_words);
+ uECC_vli_rshift1(a, num_words);
+ if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) {
+ uECC_vli_add(u, u, mod, num_words);
+ }
+ uECC_vli_sub(u, u, v, num_words);
+ vli_modInv_update(u, mod, num_words);
+ } else {
+ uECC_vli_sub(b, b, a, num_words);
+ uECC_vli_rshift1(b, num_words);
+ if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) {
+ uECC_vli_add(v, v, mod, num_words);
+ }
+ uECC_vli_sub(v, v, u, num_words);
+ vli_modInv_update(v, mod, num_words);
+ }
+ }
+ uECC_vli_set(result, u, num_words);
+}
+
+/* ------ Point operations ------ */
+
+void double_jacobian_default(uECC_word_t * X1, uECC_word_t * Y1,
+ uECC_word_t * Z1, uECC_Curve curve)
+{
+ /* t1 = X, t2 = Y, t3 = Z */
+ uECC_word_t t4[NUM_ECC_WORDS];
+ uECC_word_t t5[NUM_ECC_WORDS];
+ wordcount_t num_words = curve->num_words;
+
+ if (uECC_vli_isZero(Z1, num_words)) {
+ return;
+ }
+
+ uECC_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */
+ uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
+ uECC_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */
+ uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
+ uECC_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */
+
+ uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
+ uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
+ uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
+ uECC_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */
+
+ uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */
+ uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */
+ if (uECC_vli_testBit(X1, 0)) {
+ uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words);
+ uECC_vli_rshift1(X1, num_words);
+ X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1);
+ } else {
+ uECC_vli_rshift1(X1, num_words);
+ }
+
+ /* t1 = 3/2*(x1^2 - z1^4) = B */
+ uECC_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */
+ uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
+ uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
+ uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
+ uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */
+ /* t4 = B * (A - x3) - y1^4 = y3: */
+ uECC_vli_modSub(t4, X1, t4, curve->p, num_words);
+
+ uECC_vli_set(X1, Z1, num_words);
+ uECC_vli_set(Z1, Y1, num_words);
+ uECC_vli_set(Y1, t4, num_words);
+}
+
+void x_side_default(uECC_word_t *result,
+ const uECC_word_t *x,
+ uECC_Curve curve)
+{
+ uECC_word_t _3[NUM_ECC_WORDS] = {3}; /* -a = 3 */
+ wordcount_t num_words = curve->num_words;
+
+ uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */
+ uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
+ uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */
+ /* r = x^3 - 3x + b: */
+ uECC_vli_modAdd(result, result, curve->b, curve->p, num_words);
+}
+
+uECC_Curve uECC_secp256r1(void)
+{
+ return &curve_secp256r1;
+}
+
+void vli_mmod_fast_secp256r1(unsigned int *result, unsigned int*product)
+{
+ unsigned int tmp[NUM_ECC_WORDS];
+ int carry;
+
+ /* t */
+ uECC_vli_set(result, product, NUM_ECC_WORDS);
+
+ /* s1 */
+ tmp[0] = tmp[1] = tmp[2] = 0;
+ tmp[3] = product[11];
+ tmp[4] = product[12];
+ tmp[5] = product[13];
+ tmp[6] = product[14];
+ tmp[7] = product[15];
+ carry = uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS);
+ carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+ /* s2 */
+ tmp[3] = product[12];
+ tmp[4] = product[13];
+ tmp[5] = product[14];
+ tmp[6] = product[15];
+ tmp[7] = 0;
+ carry += uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS);
+ carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+ /* s3 */
+ tmp[0] = product[8];
+ tmp[1] = product[9];
+ tmp[2] = product[10];
+ tmp[3] = tmp[4] = tmp[5] = 0;
+ tmp[6] = product[14];
+ tmp[7] = product[15];
+ carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+ /* s4 */
+ tmp[0] = product[9];
+ tmp[1] = product[10];
+ tmp[2] = product[11];
+ tmp[3] = product[13];
+ tmp[4] = product[14];
+ tmp[5] = product[15];
+ tmp[6] = product[13];
+ tmp[7] = product[8];
+ carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+ /* d1 */
+ tmp[0] = product[11];
+ tmp[1] = product[12];
+ tmp[2] = product[13];
+ tmp[3] = tmp[4] = tmp[5] = 0;
+ tmp[6] = product[8];
+ tmp[7] = product[10];
+ carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+ /* d2 */
+ tmp[0] = product[12];
+ tmp[1] = product[13];
+ tmp[2] = product[14];
+ tmp[3] = product[15];
+ tmp[4] = tmp[5] = 0;
+ tmp[6] = product[9];
+ tmp[7] = product[11];
+ carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+ /* d3 */
+ tmp[0] = product[13];
+ tmp[1] = product[14];
+ tmp[2] = product[15];
+ tmp[3] = product[8];
+ tmp[4] = product[9];
+ tmp[5] = product[10];
+ tmp[6] = 0;
+ tmp[7] = product[12];
+ carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+ /* d4 */
+ tmp[0] = product[14];
+ tmp[1] = product[15];
+ tmp[2] = 0;
+ tmp[3] = product[9];
+ tmp[4] = product[10];
+ tmp[5] = product[11];
+ tmp[6] = 0;
+ tmp[7] = product[13];
+ carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+ if (carry < 0) {
+ do {
+ carry += uECC_vli_add(result, result, curve_secp256r1.p, NUM_ECC_WORDS);
+ }
+ while (carry < 0);
+ } else {
+ while (carry ||
+ uECC_vli_cmp_unsafe(curve_secp256r1.p, result, NUM_ECC_WORDS) != 1) {
+ carry -= uECC_vli_sub(result, result, curve_secp256r1.p, NUM_ECC_WORDS);
+ }
+ }
+}
+
+uECC_word_t EccPoint_isZero(const uECC_word_t *point, uECC_Curve curve)
+{
+ return uECC_vli_isZero(point, curve->num_words * 2);
+}
+
+void apply_z(uECC_word_t * X1, uECC_word_t * Y1, const uECC_word_t * const Z,
+ uECC_Curve curve)
+{
+ uECC_word_t t1[NUM_ECC_WORDS];
+
+ uECC_vli_modSquare_fast(t1, Z, curve); /* z^2 */
+ uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
+ uECC_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */
+ uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
+}
+
+/* P = (x1, y1) => 2P, (x2, y2) => P' */
+static void XYcZ_initial_double(uECC_word_t * X1, uECC_word_t * Y1,
+ uECC_word_t * X2, uECC_word_t * Y2,
+ const uECC_word_t * const initial_Z,
+ uECC_Curve curve)
+{
+ uECC_word_t z[NUM_ECC_WORDS];
+ wordcount_t num_words = curve->num_words;
+ if (initial_Z) {
+ uECC_vli_set(z, initial_Z, num_words);
+ } else {
+ uECC_vli_clear(z, num_words);
+ z[0] = 1;
+ }
+
+ uECC_vli_set(X2, X1, num_words);
+ uECC_vli_set(Y2, Y1, num_words);
+
+ apply_z(X1, Y1, z, curve);
+ curve->double_jacobian(X1, Y1, z, curve);
+ apply_z(X2, Y2, z, curve);
+}
+
+void XYcZ_add(uECC_word_t * X1, uECC_word_t * Y1,
+ uECC_word_t * X2, uECC_word_t * Y2,
+ uECC_Curve curve)
+{
+ /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
+ uECC_word_t t5[NUM_ECC_WORDS];
+ wordcount_t num_words = curve->num_words;
+
+ uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
+ uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
+ uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
+ uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
+ uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
+ uECC_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */
+
+ uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
+ uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
+ uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
+ uECC_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */
+ uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
+ uECC_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */
+ uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
+
+ uECC_vli_set(X2, t5, num_words);
+}
+
+/* Input P = (x1, y1, Z), Q = (x2, y2, Z)
+ Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
+ or P => P - Q, Q => P + Q
+ */
+static void XYcZ_addC(uECC_word_t * X1, uECC_word_t * Y1,
+ uECC_word_t * X2, uECC_word_t * Y2,
+ uECC_Curve curve)
+{
+ /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
+ uECC_word_t t5[NUM_ECC_WORDS];
+ uECC_word_t t6[NUM_ECC_WORDS];
+ uECC_word_t t7[NUM_ECC_WORDS];
+ wordcount_t num_words = curve->num_words;
+
+ uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
+ uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
+ uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
+ uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
+ uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
+ uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
+
+ uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
+ uECC_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */
+ uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
+ uECC_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */
+ uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */
+
+ uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
+ uECC_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */
+ /* t4 = (y2 - y1)*(B - x3) - E = y3: */
+ uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words);
+
+ uECC_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */
+ uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */
+ uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
+ uECC_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */
+ /* t2 = (y2+y1)*(x3' - B) - E = y3': */
+ uECC_vli_modSub(Y1, t6, Y1, curve->p, num_words);
+
+ uECC_vli_set(X1, t7, num_words);
+}
+
+void EccPoint_mult(uECC_word_t * result, const uECC_word_t * point,
+ const uECC_word_t * scalar,
+ const uECC_word_t * initial_Z,
+ bitcount_t num_bits, uECC_Curve curve)
+{
+ /* R0 and R1 */
+ uECC_word_t Rx[2][NUM_ECC_WORDS];
+ uECC_word_t Ry[2][NUM_ECC_WORDS];
+ uECC_word_t z[NUM_ECC_WORDS];
+ bitcount_t i;
+ uECC_word_t nb;
+ wordcount_t num_words = curve->num_words;
+
+ uECC_vli_set(Rx[1], point, num_words);
+ uECC_vli_set(Ry[1], point + num_words, num_words);
+
+ XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
+
+ for (i = num_bits - 2; i > 0; --i) {
+ nb = !uECC_vli_testBit(scalar, i);
+ XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
+ XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
+ }
+
+ nb = !uECC_vli_testBit(scalar, 0);
+ XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
+
+ /* Find final 1/Z value. */
+ uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
+ uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */
+ uECC_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */
+ uECC_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0))*/
+ /* yP / (xP * Yb * (X1 - X0)) */
+ uECC_vli_modMult_fast(z, z, point + num_words, curve);
+ /* Xb * yP / (xP * Yb * (X1 - X0)) */
+ uECC_vli_modMult_fast(z, z, Rx[1 - nb], curve);
+ /* End 1/Z calculation */
+
+ XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
+ apply_z(Rx[0], Ry[0], z, curve);
+
+ uECC_vli_set(result, Rx[0], num_words);
+ uECC_vli_set(result + num_words, Ry[0], num_words);
+}
+
+uECC_word_t regularize_k(const uECC_word_t * const k, uECC_word_t *k0,
+ uECC_word_t *k1, uECC_Curve curve)
+{
+
+ wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+
+ bitcount_t num_n_bits = curve->num_n_bits;
+
+ uECC_word_t carry = uECC_vli_add(k0, k, curve->n, num_n_words) ||
+ (num_n_bits < ((bitcount_t)num_n_words * uECC_WORD_SIZE * 8) &&
+ uECC_vli_testBit(k0, num_n_bits));
+
+ uECC_vli_add(k1, k0, curve->n, num_n_words);
+
+ return carry;
+}
+
+uECC_word_t EccPoint_compute_public_key(uECC_word_t *result,
+ uECC_word_t *private_key,
+ uECC_Curve curve)
+{
+
+ uECC_word_t tmp1[NUM_ECC_WORDS];
+ uECC_word_t tmp2[NUM_ECC_WORDS];
+ uECC_word_t *p2[2] = {tmp1, tmp2};
+ uECC_word_t carry;
+
+ /* Regularize the bitcount for the private key so that attackers cannot
+ * use a side channel attack to learn the number of leading zeros. */
+ carry = regularize_k(private_key, tmp1, tmp2, curve);
+
+ EccPoint_mult(result, curve->G, p2[!carry], 0, curve->num_n_bits + 1, curve);
+
+ if (EccPoint_isZero(result, curve)) {
+ return 0;
+ }
+ return 1;
+}
+
+/* Converts an integer in uECC native format to big-endian bytes. */
+void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
+ const unsigned int *native)
+{
+ wordcount_t i;
+ for (i = 0; i < num_bytes; ++i) {
+ unsigned b = num_bytes - 1 - i;
+ bytes[i] = native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE));
+ }
+}
+
+/* Converts big-endian bytes to an integer in uECC native format. */
+void uECC_vli_bytesToNative(unsigned int *native, const uint8_t *bytes,
+ int num_bytes)
+{
+ wordcount_t i;
+ uECC_vli_clear(native, (num_bytes + (uECC_WORD_SIZE - 1)) / uECC_WORD_SIZE);
+ for (i = 0; i < num_bytes; ++i) {
+ unsigned b = num_bytes - 1 - i;
+ native[b / uECC_WORD_SIZE] |=
+ (uECC_word_t)bytes[i] << (8 * (b % uECC_WORD_SIZE));
+ }
+}
+
+int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top,
+ wordcount_t num_words)
+{
+ uECC_word_t mask = (uECC_word_t)-1;
+ uECC_word_t tries;
+ bitcount_t num_bits = uECC_vli_numBits(top, num_words);
+
+ if (!g_rng_function) {
+ return 0;
+ }
+
+ for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
+ if (!g_rng_function((uint8_t *)random, num_words * uECC_WORD_SIZE)) {
+ return 0;
+ }
+ random[num_words - 1] &=
+ mask >> ((bitcount_t)(num_words * uECC_WORD_SIZE * 8 - num_bits));
+ if (!uECC_vli_isZero(random, num_words) &&
+ uECC_vli_cmp(top, random, num_words) == 1) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+
+int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve)
+{
+ uECC_word_t tmp1[NUM_ECC_WORDS];
+ uECC_word_t tmp2[NUM_ECC_WORDS];
+ wordcount_t num_words = curve->num_words;
+
+ /* The point at infinity is invalid. */
+ if (EccPoint_isZero(point, curve)) {
+ return -1;
+ }
+
+ /* x and y must be smaller than p. */
+ if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 ||
+ uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
+ return -2;
+ }
+
+ uECC_vli_modSquare_fast(tmp1, point + num_words, curve);
+ curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
+
+ /* Make sure that y^2 == x^3 + ax + b */
+ if (uECC_vli_equal(tmp1, tmp2, num_words) != 0)
+ return -3;
+
+ return 0;
+}
+
+int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve)
+{
+
+ uECC_word_t _public[NUM_ECC_WORDS * 2];
+
+ uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
+ uECC_vli_bytesToNative(
+ _public + curve->num_words,
+ public_key + curve->num_bytes,
+ curve->num_bytes);
+
+ if (uECC_vli_cmp_unsafe(_public, curve->G, NUM_ECC_WORDS * 2) == 0) {
+ return -4;
+ }
+
+ return uECC_valid_point(_public, curve);
+}
+
+int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key,
+ uECC_Curve curve)
+{
+
+ uECC_word_t _private[NUM_ECC_WORDS];
+ uECC_word_t _public[NUM_ECC_WORDS * 2];
+
+ uECC_vli_bytesToNative(
+ _private,
+ private_key,
+ BITS_TO_BYTES(curve->num_n_bits));
+
+ /* Make sure the private key is in the range [1, n-1]. */
+ if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
+ return 0;
+ }
+
+ if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) {
+ return 0;
+ }
+
+ /* Compute public key. */
+ if (!EccPoint_compute_public_key(_public, _private, curve)) {
+ return 0;
+ }
+
+ uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
+ uECC_vli_nativeToBytes(
+ public_key +
+ curve->num_bytes, curve->num_bytes, _public + curve->num_words);
+ return 1;
+}
+#else
+typedef int mbedtls_dummy_uecc_def;
+#endif /* MBEDTLS_USE_UECC */
+
diff --git a/tinycrypt/ecc_dh.c b/tinycrypt/ecc_dh.c
new file mode 100644
index 0000000..5d0a52f
--- /dev/null
+++ b/tinycrypt/ecc_dh.c
@@ -0,0 +1,201 @@
+/* ec_dh.c - TinyCrypt implementation of EC-DH */
+
+/*
+ * Copyright (c) 2014, Kenneth MacKay
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (C) 2017 by Intel Corporation, All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#if defined(MBEDTLS_USE_UECC)
+#include <tinycrypt/ecc.h>
+#include <tinycrypt/ecc_dh.h>
+#include <string.h>
+#include "mbedtls/platform_util.h"
+
+#if default_RNG_defined
+static uECC_RNG_Function g_rng_function = &default_CSPRNG;
+#else
+static uECC_RNG_Function g_rng_function = 0;
+#endif
+
+int uECC_make_key_with_d(uint8_t *public_key, uint8_t *private_key,
+ unsigned int *d, uECC_Curve curve)
+{
+
+ uECC_word_t _private[NUM_ECC_WORDS];
+ uECC_word_t _public[NUM_ECC_WORDS * 2];
+
+ /* This function is designed for test purposes-only (such as validating NIST
+ * test vectors) as it uses a provided value for d instead of generating
+ * it uniformly at random. */
+ memcpy (_private, d, NUM_ECC_BYTES);
+
+ /* Computing public-key from private: */
+ if (EccPoint_compute_public_key(_public, _private, curve)) {
+
+ /* Converting buffers to correct bit order: */
+ uECC_vli_nativeToBytes(private_key,
+ BITS_TO_BYTES(curve->num_n_bits),
+ _private);
+ uECC_vli_nativeToBytes(public_key,
+ curve->num_bytes,
+ _public);
+ uECC_vli_nativeToBytes(public_key + curve->num_bytes,
+ curve->num_bytes,
+ _public + curve->num_words);
+
+ /* erasing temporary buffer used to store secret: */
+ memset(_private, 0, NUM_ECC_BYTES);
+
+ return 1;
+ }
+ return 0;
+}
+
+int uECC_make_key(uint8_t *public_key, uint8_t *private_key, uECC_Curve curve)
+{
+
+ uECC_word_t _random[NUM_ECC_WORDS * 2];
+ uECC_word_t _private[NUM_ECC_WORDS];
+ uECC_word_t _public[NUM_ECC_WORDS * 2];
+ uECC_word_t tries;
+
+ for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
+ /* Generating _private uniformly at random: */
+ uECC_RNG_Function rng_function = uECC_get_rng();
+ if (!rng_function ||
+ !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS*uECC_WORD_SIZE)) {
+ return 0;
+ }
+
+ /* computing modular reduction of _random (see FIPS 186.4 B.4.1): */
+ uECC_vli_mmod(_private, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits));
+
+ /* Computing public-key from private: */
+ if (EccPoint_compute_public_key(_public, _private, curve)) {
+
+ /* Converting buffers to correct bit order: */
+ uECC_vli_nativeToBytes(private_key,
+ BITS_TO_BYTES(curve->num_n_bits),
+ _private);
+ uECC_vli_nativeToBytes(public_key,
+ curve->num_bytes,
+ _public);
+ uECC_vli_nativeToBytes(public_key + curve->num_bytes,
+ curve->num_bytes,
+ _public + curve->num_words);
+
+ /* erasing temporary buffer that stored secret: */
+ memset(_private, 0, NUM_ECC_BYTES);
+
+ return 1;
+ }
+ }
+ return 0;
+}
+
+int uECC_shared_secret(const uint8_t *public_key, const uint8_t *private_key,
+ uint8_t *secret, uECC_Curve curve)
+{
+
+ uECC_word_t _public[NUM_ECC_WORDS * 2];
+ uECC_word_t _private[NUM_ECC_WORDS];
+
+ uECC_word_t tmp[NUM_ECC_WORDS];
+ uECC_word_t *p2[2] = {_private, tmp};
+ uECC_word_t *initial_Z = 0;
+ uECC_word_t carry;
+ wordcount_t num_words = curve->num_words;
+ wordcount_t num_bytes = curve->num_bytes;
+ int r;
+
+ /* Converting buffers to correct bit order: */
+ uECC_vli_bytesToNative(_private,
+ private_key,
+ BITS_TO_BYTES(curve->num_n_bits));
+ uECC_vli_bytesToNative(_public,
+ public_key,
+ num_bytes);
+ uECC_vli_bytesToNative(_public + num_words,
+ public_key + num_bytes,
+ num_bytes);
+
+ /* Regularize the bitcount for the private key so that attackers cannot use a
+ * side channel attack to learn the number of leading zeros. */
+ carry = regularize_k(_private, _private, tmp, curve);
+
+ /* If an RNG function was specified, try to get a random initial Z value to
+ * improve protection against side-channel attacks. */
+ if (g_rng_function) {
+ if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) {
+ r = 0;
+ goto clear_and_out;
+ }
+ initial_Z = p2[carry];
+ }
+
+ EccPoint_mult(_public, _public, p2[!carry], initial_Z, curve->num_n_bits + 1,
+ curve);
+
+ uECC_vli_nativeToBytes(secret, num_bytes, _public);
+ r = !EccPoint_isZero(_public, curve);
+
+clear_and_out:
+ /* erasing temporary buffer used to store secret: */
+ mbedtls_platform_zeroize(p2, sizeof(p2));
+ mbedtls_platform_zeroize(tmp, sizeof(tmp));
+ mbedtls_platform_zeroize(_private, sizeof(_private));
+
+ return r;
+}
+#else
+typedef int mbedtls_dummy_uecc_def;
+#endif /* MBEDTLS_USE_UECC */
diff --git a/tinycrypt/ecc_dsa.c b/tinycrypt/ecc_dsa.c
new file mode 100644
index 0000000..ff8a78a
--- /dev/null
+++ b/tinycrypt/ecc_dsa.c
@@ -0,0 +1,297 @@
+/* ec_dsa.c - TinyCrypt implementation of EC-DSA */
+
+/* Copyright (c) 2014, Kenneth MacKay
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.*/
+
+/*
+ * Copyright (C) 2017 by Intel Corporation, All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#if defined(MBEDTLS_USE_UECC)
+#include <tinycrypt/ecc.h>
+#include <tinycrypt/ecc_dsa.h>
+
+#if default_RNG_defined
+static uECC_RNG_Function g_rng_function = &default_CSPRNG;
+#else
+static uECC_RNG_Function g_rng_function = 0;
+#endif
+
+static void bits2int(uECC_word_t *native, const uint8_t *bits,
+ unsigned bits_size, uECC_Curve curve)
+{
+ unsigned num_n_bytes = BITS_TO_BYTES(curve->num_n_bits);
+ unsigned num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+ int shift;
+ uECC_word_t carry;
+ uECC_word_t *ptr;
+
+ if (bits_size > num_n_bytes) {
+ bits_size = num_n_bytes;
+ }
+
+ uECC_vli_clear(native, num_n_words);
+ uECC_vli_bytesToNative(native, bits, bits_size);
+ if (bits_size * 8 <= (unsigned)curve->num_n_bits) {
+ return;
+ }
+ shift = bits_size * 8 - curve->num_n_bits;
+ carry = 0;
+ ptr = native + num_n_words;
+ while (ptr-- > native) {
+ uECC_word_t temp = *ptr;
+ *ptr = (temp >> shift) | carry;
+ carry = temp << (uECC_WORD_BITS - shift);
+ }
+
+ /* Reduce mod curve_n */
+ if (uECC_vli_cmp_unsafe(curve->n, native, num_n_words) != 1) {
+ uECC_vli_sub(native, native, curve->n, num_n_words);
+ }
+}
+
+int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
+ unsigned hash_size, uECC_word_t *k, uint8_t *signature,
+ uECC_Curve curve)
+{
+
+ uECC_word_t tmp[NUM_ECC_WORDS];
+ uECC_word_t s[NUM_ECC_WORDS];
+ uECC_word_t *k2[2] = {tmp, s};
+ uECC_word_t p[NUM_ECC_WORDS * 2];
+ uECC_word_t carry;
+ wordcount_t num_words = curve->num_words;
+ wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+ bitcount_t num_n_bits = curve->num_n_bits;
+
+ /* Make sure 0 < k < curve_n */
+ if (uECC_vli_isZero(k, num_words) ||
+ uECC_vli_cmp(curve->n, k, num_n_words) != 1) {
+ return 0;
+ }
+
+ carry = regularize_k(k, tmp, s, curve);
+ EccPoint_mult(p, curve->G, k2[!carry], 0, num_n_bits + 1, curve);
+ if (uECC_vli_isZero(p, num_words)) {
+ return 0;
+ }
+
+ /* If an RNG function was specified, get a random number
+ to prevent side channel analysis of k. */
+ if (!g_rng_function) {
+ uECC_vli_clear(tmp, num_n_words);
+ tmp[0] = 1;
+ }
+ else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) {
+ return 0;
+ }
+
+ /* Prevent side channel analysis of uECC_vli_modInv() to determine
+ bits of k / the private key by premultiplying by a random number */
+ uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
+ uECC_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */
+ uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
+
+ uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
+
+ /* tmp = d: */
+ uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
+
+ s[num_n_words - 1] = 0;
+ uECC_vli_set(s, p, num_words);
+ uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
+
+ bits2int(tmp, message_hash, hash_size, curve);
+ uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
+ uECC_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */
+ if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) {
+ return 0;
+ }
+
+ uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
+ return 1;
+}
+
+int uECC_sign(const uint8_t *private_key, const uint8_t *message_hash,
+ unsigned hash_size, uint8_t *signature, uECC_Curve curve)
+{
+ uECC_word_t _random[2*NUM_ECC_WORDS];
+ uECC_word_t k[NUM_ECC_WORDS];
+ uECC_word_t tries;
+
+ for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
+ /* Generating _random uniformly at random: */
+ uECC_RNG_Function rng_function = uECC_get_rng();
+ if (!rng_function ||
+ !rng_function((uint8_t *)_random, 2*NUM_ECC_WORDS*uECC_WORD_SIZE)) {
+ return 0;
+ }
+
+ // computing k as modular reduction of _random (see FIPS 186.4 B.5.1):
+ uECC_vli_mmod(k, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits));
+
+ if (uECC_sign_with_k(private_key, message_hash, hash_size, k, signature,
+ curve)) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static bitcount_t smax(bitcount_t a, bitcount_t b)
+{
+ return (a > b ? a : b);
+}
+
+int uECC_verify(const uint8_t *public_key, const uint8_t *message_hash,
+ unsigned hash_size, const uint8_t *signature,
+ uECC_Curve curve)
+{
+
+ uECC_word_t u1[NUM_ECC_WORDS], u2[NUM_ECC_WORDS];
+ uECC_word_t z[NUM_ECC_WORDS];
+ uECC_word_t sum[NUM_ECC_WORDS * 2];
+ uECC_word_t rx[NUM_ECC_WORDS];
+ uECC_word_t ry[NUM_ECC_WORDS];
+ uECC_word_t tx[NUM_ECC_WORDS];
+ uECC_word_t ty[NUM_ECC_WORDS];
+ uECC_word_t tz[NUM_ECC_WORDS];
+ const uECC_word_t *points[4];
+ const uECC_word_t *point;
+ bitcount_t num_bits;
+ bitcount_t i;
+
+ uECC_word_t _public[NUM_ECC_WORDS * 2];
+ uECC_word_t r[NUM_ECC_WORDS], s[NUM_ECC_WORDS];
+ wordcount_t num_words = curve->num_words;
+ wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+
+ rx[num_n_words - 1] = 0;
+ r[num_n_words - 1] = 0;
+ s[num_n_words - 1] = 0;
+
+ uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
+ uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes,
+ curve->num_bytes);
+ uECC_vli_bytesToNative(r, signature, curve->num_bytes);
+ uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
+
+ /* r, s must not be 0. */
+ if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) {
+ return 0;
+ }
+
+ /* r, s must be < n. */
+ if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 ||
+ uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
+ return 0;
+ }
+
+ /* Calculate u1 and u2. */
+ uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
+ u1[num_n_words - 1] = 0;
+ bits2int(u1, message_hash, hash_size, curve);
+ uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
+ uECC_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */
+
+ /* Calculate sum = G + Q. */
+ uECC_vli_set(sum, _public, num_words);
+ uECC_vli_set(sum + num_words, _public + num_words, num_words);
+ uECC_vli_set(tx, curve->G, num_words);
+ uECC_vli_set(ty, curve->G + num_words, num_words);
+ uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
+ XYcZ_add(tx, ty, sum, sum + num_words, curve);
+ uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
+ apply_z(sum, sum + num_words, z, curve);
+
+ /* Use Shamir's trick to calculate u1*G + u2*Q */
+ points[0] = 0;
+ points[1] = curve->G;
+ points[2] = _public;
+ points[3] = sum;
+ num_bits = smax(uECC_vli_numBits(u1, num_n_words),
+ uECC_vli_numBits(u2, num_n_words));
+
+ point = points[(!!uECC_vli_testBit(u1, num_bits - 1)) |
+ ((!!uECC_vli_testBit(u2, num_bits - 1)) << 1)];
+ uECC_vli_set(rx, point, num_words);
+ uECC_vli_set(ry, point + num_words, num_words);
+ uECC_vli_clear(z, num_words);
+ z[0] = 1;
+
+ for (i = num_bits - 2; i >= 0; --i) {
+ uECC_word_t index;
+ curve->double_jacobian(rx, ry, z, curve);
+
+ index = (!!uECC_vli_testBit(u1, i)) | ((!!uECC_vli_testBit(u2, i)) << 1);
+ point = points[index];
+ if (point) {
+ uECC_vli_set(tx, point, num_words);
+ uECC_vli_set(ty, point + num_words, num_words);
+ apply_z(tx, ty, z, curve);
+ uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
+ XYcZ_add(tx, ty, rx, ry, curve);
+ uECC_vli_modMult_fast(z, z, tz, curve);
+ }
+ }
+
+ uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
+ apply_z(rx, ry, z, curve);
+
+ /* v = x1 (mod n) */
+ if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
+ uECC_vli_sub(rx, rx, curve->n, num_n_words);
+ }
+
+ /* Accept only if v == r. */
+ return (int)(uECC_vli_equal(rx, r, num_words) == 0);
+}
+#else
+typedef int mbedtls_dummy_uecc_def;
+#endif /* MBEDTLS_USE_UECC */
diff --git a/visualc/VS2010/mbedTLS.sln b/visualc/VS2010/mbedTLS.sln
index 85429b8..5d2c99c 100644
--- a/visualc/VS2010/mbedTLS.sln
+++ b/visualc/VS2010/mbedTLS.sln
@@ -183,11 +183,6 @@
{46CF2D25-6A36-4189-B59C-E4815388E554} = {46CF2D25-6A36-4189-B59C-E4815388E554}
EndProjectSection
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ssl_cert_test", "ssl_cert_test.vcxproj", "{3FE0C0E1-D9BA-6A26-380C-F293E543B914}"
- ProjectSection(ProjectDependencies) = postProject
- {46CF2D25-6A36-4189-B59C-E4815388E554} = {46CF2D25-6A36-4189-B59C-E4815388E554}
- EndProjectSection
-EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "benchmark", "benchmark.vcxproj", "{90EFD9A4-C6B0-3EE8-1F06-0A0E0D55AEDA}"
ProjectSection(ProjectDependencies) = postProject
{46CF2D25-6A36-4189-B59C-E4815388E554} = {46CF2D25-6A36-4189-B59C-E4815388E554}
@@ -552,14 +547,6 @@
{5FCC71F6-FF33-EBCF-FBA2-8FC783D5318E}.Release|Win32.Build.0 = Release|Win32
{5FCC71F6-FF33-EBCF-FBA2-8FC783D5318E}.Release|x64.ActiveCfg = Release|x64
{5FCC71F6-FF33-EBCF-FBA2-8FC783D5318E}.Release|x64.Build.0 = Release|x64
- {3FE0C0E1-D9BA-6A26-380C-F293E543B914}.Debug|Win32.ActiveCfg = Debug|Win32
- {3FE0C0E1-D9BA-6A26-380C-F293E543B914}.Debug|Win32.Build.0 = Debug|Win32
- {3FE0C0E1-D9BA-6A26-380C-F293E543B914}.Debug|x64.ActiveCfg = Debug|x64
- {3FE0C0E1-D9BA-6A26-380C-F293E543B914}.Debug|x64.Build.0 = Debug|x64
- {3FE0C0E1-D9BA-6A26-380C-F293E543B914}.Release|Win32.ActiveCfg = Release|Win32
- {3FE0C0E1-D9BA-6A26-380C-F293E543B914}.Release|Win32.Build.0 = Release|Win32
- {3FE0C0E1-D9BA-6A26-380C-F293E543B914}.Release|x64.ActiveCfg = Release|x64
- {3FE0C0E1-D9BA-6A26-380C-F293E543B914}.Release|x64.Build.0 = Release|x64
{90EFD9A4-C6B0-3EE8-1F06-0A0E0D55AEDA}.Debug|Win32.ActiveCfg = Debug|Win32
{90EFD9A4-C6B0-3EE8-1F06-0A0E0D55AEDA}.Debug|Win32.Build.0 = Debug|Win32
{90EFD9A4-C6B0-3EE8-1F06-0A0E0D55AEDA}.Debug|x64.ActiveCfg = Debug|x64
diff --git a/visualc/VS2010/ssl_cert_test.vcxproj b/visualc/VS2010/ssl_cert_test.vcxproj
deleted file mode 100644
index b8f014e..0000000
--- a/visualc/VS2010/ssl_cert_test.vcxproj
+++ /dev/null
@@ -1,174 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <ItemGroup Label="ProjectConfigurations">
- <ProjectConfiguration Include="Debug|Win32">
- <Configuration>Debug</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Debug|x64">
- <Configuration>Debug</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release|Win32">
- <Configuration>Release</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release|x64">
- <Configuration>Release</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- </ItemGroup>
- <ItemGroup>
- <ClCompile Include="..\..\programs\test\ssl_cert_test.c" />
- </ItemGroup>
- <ItemGroup>
- <ProjectReference Include="mbedTLS.vcxproj">
- <Project>{46cf2d25-6a36-4189-b59c-e4815388e554}</Project>
- <LinkLibraryDependencies>true</LinkLibraryDependencies>
- </ProjectReference>
- </ItemGroup>
- <PropertyGroup Label="Globals">
- <ProjectGuid>{3FE0C0E1-D9BA-6A26-380C-F293E543B914}</ProjectGuid>
- <Keyword>Win32Proj</Keyword>
- <RootNamespace>ssl_cert_test</RootNamespace>
- </PropertyGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>true</UseDebugLibraries>
- <CharacterSet>Unicode</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>true</UseDebugLibraries>
- <CharacterSet>Unicode</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>false</UseDebugLibraries>
- <WholeProgramOptimization>true</WholeProgramOptimization>
- <CharacterSet>Unicode</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>false</UseDebugLibraries>
- <WholeProgramOptimization>true</WholeProgramOptimization>
- <CharacterSet>Unicode</CharacterSet>
- <PlatformToolset>Windows7.1SDK</PlatformToolset>
- </PropertyGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
- <ImportGroup Label="ExtensionSettings">
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <PropertyGroup Label="UserMacros" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <LinkIncremental>true</LinkIncremental>
- <IntDir>$(Configuration)\$(TargetName)\</IntDir>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
- <LinkIncremental>true</LinkIncremental>
- <IntDir>$(Configuration)\$(TargetName)\</IntDir>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <LinkIncremental>false</LinkIncremental>
- <IntDir>$(Configuration)\$(TargetName)\</IntDir>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
- <LinkIncremental>false</LinkIncremental>
- <IntDir>$(Configuration)\$(TargetName)\</IntDir>
- </PropertyGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <ClCompile>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <WarningLevel>Level3</WarningLevel>
- <Optimization>Disabled</Optimization>
- <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>../../include</AdditionalIncludeDirectories>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <ShowProgress>NotSet</ShowProgress>
- <AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- <AdditionalLibraryDirectories>Debug</AdditionalLibraryDirectories>
- </Link>
- <ProjectReference>
- <LinkLibraryDependencies>false</LinkLibraryDependencies>
- </ProjectReference>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
- <ClCompile>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <WarningLevel>Level3</WarningLevel>
- <Optimization>Disabled</Optimization>
- <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>../../include</AdditionalIncludeDirectories>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <ShowProgress>NotSet</ShowProgress>
- <AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- <AdditionalLibraryDirectories>Debug</AdditionalLibraryDirectories>
- </Link>
- <ProjectReference>
- <LinkLibraryDependencies>false</LinkLibraryDependencies>
- </ProjectReference>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <ClCompile>
- <WarningLevel>Level3</WarningLevel>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <Optimization>MaxSpeed</Optimization>
- <FunctionLevelLinking>true</FunctionLevelLinking>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>../../include</AdditionalIncludeDirectories>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <EnableCOMDATFolding>true</EnableCOMDATFolding>
- <OptimizeReferences>true</OptimizeReferences>
- <AdditionalLibraryDirectories>Release</AdditionalLibraryDirectories>
- <AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
- <ClCompile>
- <WarningLevel>Level3</WarningLevel>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <Optimization>MaxSpeed</Optimization>
- <FunctionLevelLinking>true</FunctionLevelLinking>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- <PreprocessorDefinitions>WIN64;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>../../include</AdditionalIncludeDirectories>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <EnableCOMDATFolding>true</EnableCOMDATFolding>
- <OptimizeReferences>true</OptimizeReferences>
- <AdditionalLibraryDirectories>Release</AdditionalLibraryDirectories>
- <AdditionalDependencies>%(AdditionalDependencies);</AdditionalDependencies>
- </Link>
- </ItemDefinitionGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
- <ImportGroup Label="ExtensionTargets">
- </ImportGroup>
-</Project>