diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..05cf3e7 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,38 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +# https://coverage.readthedocs.io/en/latest/config.html + +[report] +# Regexes for lines to exclude from consideration +exclude_lines = + # Have to re-enable the standard pragma + pragma: no cover + + # Don't complain about missing debug-only code: + def __repr__ + if self\.debug + + # Don't complain if tests don't hit defensive assertion code: + raise AssertionError + raise NotImplementedError + raise argparse.ArgumentTypeError + + # Don't complain if non-runnable code isn't run: + if 0: + if __name__ == .__main__.: diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..df00ec3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ + +.idea/ +*.pyc +*.so +build/ +*.egg-info/ +venv/ +dist/ +.coverage +htmlcov/ +.tox/ +.python-version +tests/mtool/test_data/ +.manifest-dev-tool/ +.vscode/ diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..78b80da --- /dev/null +++ b/.pylintrc @@ -0,0 +1,577 @@ +[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=manifesttool.armbsdiff + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=venv + +# Add files or directories matching the regex patterns to the blacklist. The +# regex matches against base names, not paths. +ignore-patterns=manifest_schema_v.*\.py + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# 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= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# 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, + non-ascii-bytes-literal, + raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + 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, + deprecated-itertools-function, + deprecated-types-field, + next-method-defined, + dict-items-not-iterating, + dict-keys-not-iterating, + dict-values-not-iterating, + deprecated-operator-function, + deprecated-urllib-function, + xreadlines-attribute, + deprecated-sys-function, + exception-escape, + comprehension-escape, + too-many-arguments, + too-many-locals, + missing-docstring, + duplicate-code, + too-many-public-methods + +# 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=c-extension-no-member + + +[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, e.g. +# 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 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit + + +[LOGGING] + +# Format style used to check logging format string. `old` means using % +# formatting, while `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# 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 + + +[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 + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=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 defining 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. expected to +# not be 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,past.builtins,future.builtins,builtins,io + + +[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*(# )??$ + +# 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=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# 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 + + +[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=15 + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. +#class-attribute-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=1000 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _, + fh, + logger + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. +#module-rgx= + +# 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. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. +#variable-rgx= + + +[STRING] + +# This flag controls whether the implicit-str-concat-in-sequence should +# generate a warning on implicit string concatenation in sequences defined over +# several lines. +check-str-concat-over-line-jumps=no + + +[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=optparse,tkinter.tix + +# 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 + + +[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=cls + + +[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 an 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 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception diff --git a/LICENSE b/LICENSE index 59cd3f8..147745e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,165 +1,15 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ +Copyright 2019 ARM Limited or its affiliates -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +SPDX-License-Identifier: Apache-2.0 -1. Definitions. +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 -"License" shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document. + http://www.apache.org/licenses/LICENSE-2.0 -"Licensor" shall mean the copyright owner or entity authorized by the copyright -owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities -that control, are controlled by, or are under common control with that entity. -For the purposes of this definition, "control" means (i) the power, direct or -indirect, to cause the direction or management of such entity, whether by -contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the -outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising -permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including -but not limited to software source code, documentation source, and configuration -files. - -"Object" form shall mean any form resulting from mechanical transformation or -translation of a Source form, including but not limited to compiled object code, -generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made -available under the License, as indicated by a copyright notice that is included -in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that -is based on (or derived from) the Work and for which the editorial revisions, -annotations, elaborations, or other modifications represent, as a whole, an -original work of authorship. For the purposes of this License, Derivative Works -shall not include works that remain separable from, or merely link (or bind by -name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version -of the Work and any modifications or additions to that Work or Derivative Works -thereof, that is intentionally submitted to Licensor for inclusion in the Work -by the copyright owner or by an individual or Legal Entity authorized to submit -on behalf of the copyright owner. For the purposes of this definition, -"submitted" means any form of electronic, verbal, or written communication sent -to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, and -issue tracking systems that are managed by, or on behalf of, the Licensor for -the purpose of discussing and improving the Work, but excluding communication -that is conspicuously marked or otherwise designated in writing by the copyright -owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf -of whom a Contribution has been received by Licensor and subsequently -incorporated within the Work. - -2. Grant of Copyright License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable copyright license to reproduce, prepare Derivative Works of, -publicly display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form. - -3. Grant of Patent License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable (except as stated in this section) patent license to make, have -made, use, offer to sell, sell, import, and otherwise transfer the Work, where -such license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by combination -of their Contribution(s) with the Work to which such Contribution(s) was -submitted. If You institute patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Work or a -Contribution incorporated within the Work constitutes direct or contributory -patent infringement, then any patent licenses granted to You under this License -for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. - -You may reproduce and distribute copies of the Work or Derivative Works thereof -in any medium, with or without modifications, and in Source or Object form, -provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -You must retain, in the Source form of any Derivative Works that You distribute, -all copyright, patent, trademark, and attribution notices from the Source form -of the Work, excluding those notices that do not pertain to any part of the -Derivative Works; and -If the Work includes a "NOTICE" text file as part of its distribution, then any -Derivative Works that You distribute must include a readable copy of the -attribution notices contained within such NOTICE file, excluding those notices -that do not pertain to any part of the Derivative Works, in at least one of the -following places: within a NOTICE text file distributed as part of the -Derivative Works; within the Source form or documentation, if provided along -with the Derivative Works; or, within a display generated by the Derivative -Works, if and wherever such third-party notices normally appear. The contents of -the NOTICE file are for informational purposes only and do not modify the -License. You may add Your own attribution notices within Derivative Works that -You distribute, alongside or as an addendum to the NOTICE text from the Work, -provided that such additional attribution notices cannot be construed as -modifying the License. -You may add Your own copyright statement to Your modifications and may provide -additional or different license terms and conditions for use, reproduction, or -distribution of Your modifications, or for any such Derivative Works as a whole, -provided Your use, reproduction, and distribution of the Work otherwise complies -with the conditions stated in this License. - -5. Submission of Contributions. - -Unless You explicitly state otherwise, any Contribution intentionally submitted -for inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the terms of -any separate license agreement you may have executed with Licensor regarding -such Contributions. - -6. Trademarks. - -This License does not grant permission to use the trade names, trademarks, -service marks, or product names of the Licensor, except as required for -reasonable and customary use in describing the origin of the Work and -reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. - -Unless required by applicable law or agreed to in writing, Licensor provides the -Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, -including, without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are -solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise of -permissions under this License. - -8. Limitation of Liability. - -In no event and under no legal theory, whether in tort (including negligence), -contract, or otherwise, unless required by applicable law (such as deliberate -and grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, incidental, -or consequential damages of any character arising as a result of this License or -out of the use or inability to use the Work (including but not limited to -damages for loss of goodwill, work stoppage, computer failure or malfunction, or -any and all other commercial damages or losses), even if such Contributor has -been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. - -While redistributing the Work or Derivative Works thereof, You may choose to -offer, and charge a fee for, acceptance of support, warranty, indemnity, or -other liability obligations and/or rights consistent with this License. However, -in accepting such obligations, You may act only on Your own behalf and on Your -sole responsibility, not on behalf of any other Contributor, and only if You -agree to indemnify, defend, and hold each Contributor harmless for any liability -incurred by, or claims asserted against, such Contributor by reason of your -accepting any such warranty or additional liability. +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. diff --git a/MANIFEST.in b/MANIFEST.in index 8afbefe..f702bce 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,2 +1,6 @@ include README.md +include changelog.md include requirements.txt +include bsdiff/*.h +include manifesttool/dev_tool/actions/code_template.txt +include manifesttool/mtool/manifest-input-schema.json diff --git a/README.md b/README.md index e333451..5a2681d 100644 --- a/README.md +++ b/README.md @@ -1,533 +1,658 @@ -## Update manifest creation +# Device Management manifest CLI tool -### Manifest tool +This document explains how to install and use the manifest tool. -The manifest tool creates and parses manifest files. You can use it as a command-line utility or Python package. +- [Manifest tool overview](#manifest-tool-overview) +- [Installing the manifest tool](#installing-the-manifest-tool) +- [Using the manifest tool](#using-the-manifest-tool) +- [Developer workflow example](#developer-workflow-example) +- [Troubleshooting](#troubleshooting) -### Installation +**Note:** Please see the [changelog](./changelog.md) for the list of all changes between release versions. -The manifest tool is compatible both with Python 2.7.11 and later and with Python 3.5.1 and later. +## Manifest tool overview +Device Management lets you perform Firmware Over-the-Air (FOTA) updates +on managed devices. -There are 4 options for installing the manifest tool, but all use `pip`: +On the device side, the firmware update process begins when the device +receives an update manifest. The OEM (original equipment manufacturer) +or update author cryptographically signs the manifest with a private key +paired to a public key that exists on the device, enabling the device to +authenticate the manifest before it accepts the firmware update. -1. Install from PyPi with pip. +Device Management supports: - ``` - $ pip install manifest-tool - ``` +* Full updates - Deliver new firmware and install it on the device. +* Delta updates - The manifest tool executes a diff algorithm that + produces a small delta patch file. The nano client constructs a new + firmware image based on the delta patch file and the firmware + currently present on the device. This technique saves traffic + bandwidth. -1. Install from GitHub over HTTPS. +The `manifest-tool` Python package includes these command line tools: - ``` - $ pip install git+https://github.com/ARMmbed/manifest-tool.git - ``` +- [`manifest-tool`](#manifest-tool) - Creates manifest files. +- [`manifest-delta-tool`](#manifest-delta-tool) - Generates delta patch + files. +- [`manifest-dev-tool`](#manifest-dev-tool) - A developer tool for + running a simplified update campaign. -1. Install from GitHub over SSH. +## Installing the manifest tool - ``` - $ pip install git+ssh://git@github.com/ARMmbed/manifest-tool.git - ``` +We recommend installing the `manifest-tool` Python package in a +[Python virtual environment](#creating-a-virtual-environment). -1. Install from a local copy of this repository. +### Installing from PyPi - ``` - $ pip install . - ``` - -**Note:** This repository includes `setup.py`, but it does not work on all systems. Please use `pip` for the best experience. - -See [Debugging Installation](#debugging-installation) if these steps do not work. +**Prerequisites:** -### Set up the Device Management Python SDK (optional) +* [Python 3.5 or higher](https://www.python.org/downloads/). +* [pip (Python Package Installer)](https://pip.pypa.io/en/stable/). +* Internet connectivity -You can use the SDKs to automate uploading your manifest to Device Management (as detailed below); this requires installing the SDKs. If you do not want to install the SDKs, use the Update service API or Device Management Portal to upload the manifest. +**To install the manifest tool from [PyPi](https://pypi.org/), run:** -Install the the Python SDK directly from GitHub: ``` - $ pip install git+https://github.com/ARMmbed/mbed-cloud-sdk-python.git +pip install manifest-tool ``` -### Workflow +### Installing from local source tree -The Update client workflow has three stages: +**Prerequisites:** -1. Send a payload to an update medium, for example a web service, a removable storage device or a broadcast system. -1. Create a manifest for that payload. The manifest includes the hash and size of the payload along with its URI on the update medium. -1. Send that manifest to an update medium. +* [Python 3.5 or later](https://www.python.org/downloads/). +* [pip (Python Package Installer)](https://pip.pypa.io/en/stable/). +* Native toolchain: + * GCC/Clang for Linux/MacOS. + * Microsoft Visual Studio 2017 or later for Windows. -### Quick Start +**To install the manifest tool from the local source tree, run:** -In a new project that will support the Update client, run the following command: - -``` -$ manifest-tool init -d "" -m "" -a "" -S "" -``` +1. Clone the ARMmbed/manifest-tool repository to your machine: -Note that you do not need to enter `-S` for the production environment. + ``` + $ git clone git@github.com:ARMmbed/manifest-tool.git ./manifest-tool + ``` -The manifest tool is able to use the Device Management Python SDK to upload firmware and manifests to Device Management. If you do not require this feature, you can call `manifest-tool init` with fewer arguments: +1. Run: -``` -$ manifest-tool init -d "" -m "" -``` + ``` + $ pip install + ``` -This will create several files: -* A certificate in `.update-certificates/default.der`. -* A matching private key in `.update-certificates/default.key.pem`. -* A set of default settings in `.manifest_tool.json`. -* Device Management settings in `.mbed_cloud_config.json`. + Where `` is the path to the local source tree. -The default settings include: -* A unique vendor identifier, based on the domain name supplied to `init`. -* A unique model identifier, based on the vendor identifier and the model name supplied to `init`. -* The path of the certificate and private key. +**Note:** Run `$ pip install -e ` to install the package in Python setuptools development mode. For more information, please see the [setuptools development mode documentation](https://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode). -If you do not want to enter the subject information for your certificate (country, state, city, organization and so on), add the `-q` flag to the command above. +### Creating a virtual environment -**Note:** The certificate created in `manifest-tool init` is not suitable for production. You should avoid using it except in testing and development. To create a certificate for production purposes, please use an air-gapped computer or a Hardware Security Module. You should conduct a security review on your manifest signing infrastructure, since it is the core of the security guarantees for Update client. +The `virtualenv` tool creates isolated Python environments, which are +useful in overcoming Python package collision issues when you work on +multiple projects. For more information, please see the +[Python documentation](https://docs.python.org/tutorial/venv.html). -#### Single-device update -Once you have run `manifest-tool init`, you can perform updates on a single device by: +**To create a virtual environment, run:** -```sh -$ manifest-tool update device -p -D +```shell +$ virtualenv -p python3 venv ``` -This will perform several actions: -1. Upload the payload to Device Management. -1. Hash the payload and create a manifest that links to its location in Device Management. -1. Create an update campaign for the supplied device ID, with the newly created manifest. -1. Start the campaign. -1. Wait for the campaign to complete. -1. Delete the payload, manifest and update campaign out of Device Management. - -This allows development with a device for testing purposes. +**To activate the virtual environment in the current shell, run:** -#### Multidevice update - -If more than one device needs updating, you can use Device Management Portal to create device filters that can include many devices into an update campaign. First, you need a manifest. Once you have run `manifest-tool init`, you can create manifests by: - -``` -$ manifest-tool update prepare -p +```shell +$ source venv/bin/activate ``` -Optionally, a name and description for the payload and corresponding manifest can be provided: - -``` -$ manifest-tool update prepare -p -n -d \ - --manifest-name --manifest-description -``` +## Using the manifest tool -Both methods of creating a manifest use the defaults created in `manifest-tool init`. You can override each default using an input file or command-line arguments. See below for more details. +This section explains how to use the CLI tools included in the +`manifest-tool` Python package: -Once `manifest-tool update prepare` has been executed the manifest file is automatically uploaded to Device Management and you can then create and start an update campaign using the Device Management portal. +- [manifest-tool](#manifest-tool) +- [manifest-delta-tool](#manifest-delta-tool) +- [manifest-dev-tool](#manifest-dev-tool) +- [Developer workflow example](#developer-workflow-example) -### External signing tool +### manifest-tool -The documentation can be found [here](https://cloud.mbed.com/docs/current/updating-firmware/external-signing-tools.html). +`manifest-tool` commands: -### Debugging Installation +- [`manifest-tool create`](#manifest-tool-create) - Creates manifests. +- [`manifest-tool create-v1`](#manifest-tool-create-v1) - Creates V1 + schema-compatible manifests. +- [`manifest-tool parse`](#manifest-tool-parse) - Parses and verifies + existing manifest files. +- [`manifest-tool schema`](#manifest-tool-schema) - Shows bundled input + validation schema. +- [`manifest-tool public-key`](#manifest-tool-public-key) - Generates an + uncompressed public key. -Some platforms require `python-dev` or `python3-dev` to install Python's cryptography library, which is a dependency of the manifest tool. For example, on Ubuntu, run: +**Note:** Run `manifest-tool --help` for more information about all commands, or `manifest-tool --help` for more information about a specific command, including its parameters and how to use them. -```sh -$ sudo apt-get install python-dev -``` +#### `manifest-tool create` -### Advanced usage +Creates a manifest. The manifest tool receives a configuration file +describing the update type. -The manifest tool allows for significantly more flexibility than the model above shows. You can override each of the defaults that `manifest-tool init` sets by using the command-line or an input file. The manifest tool supports a variety of commands. You can print a full list of commands by using `manifest-tool --help`. +**Prerequisites** +* An update private key and public key certificate. -#### Advanced creation Prerequisites + Keep the private key secret because it allows installing new + firmware images on your devices. -To create a manifest, you must provide an ECC certificate and private key. The certificate must be an ECC secp256r1 DER encoded certificate. Best practice is for an authority the target device trusts to sign this certificate. + Provision the public key to the device. -The Update client on the target device must have this certificate available, or the certificate must be signed by a certificate that is available on the target device. + * To generate a private key, run: -##### Creating a certificate for production use + ```shell + $ openssl ecparam -genkey -name prime256v1 -outform PEM -out my.pkey.pem + ``` -To use a certificate in production, please use a Hardware Security Module or an air-gapped computer to create the certificate. You can then use this device to create signatures for manifests. If you use certificate delegation, you can use the HSM or air-gapped computer to sign the delegated certificates. You should perform a security review on your signing infrastructure. + * To generate a public key in uncompressed point format (X9.62), use + the [`manifest-tool public-key`](#manifest-tool-public-key) + command. -##### Creating a certificate for development use +* Upload the new firmware binary to a server that the device you want to + update can reach, and obtain the URL for the uploaded firmware binary. -**For testing and evaluation only** +* A configuration file in JSON or YAML format. -Providing a self-signed certificate is adequate for testing purposes. There are many methods for creating a self-signed certificate. The manifest tool provides two commands: `init` and `cert create`, which creates a self-signed certificate. OpenSSL can also produce one, but we do not recommended this on Mac OS X, due to the old version of OpenSSL that ships with it, nor on Windows, because you must install OpenSSL separately. + Configuration file format: + ```yaml + vendor: # One of "domain" or "vendor-id" fields are expected + domain: arm.com # FW owner domain. Expected to include a dot (".") + vendor-id: fa6b4a53d5ad5fdfbe9de663e4d41ffe # Valid vendor UUID + device: # One of "model-name" or "class-id" fields are expected + model-name: Smart Slippers # A device model name + vendor-id: fa6b4a53d5ad5fdfbe9de663e4d41ffe # Valid device-class UUID -###### Creating a self-signed certificate with manifest-tool init + priority: 1 # Update priority as will be passed to authorization callback + # implemented by application on a device side + payload: + url: http://some-url.com/files?id=1234 # File storage URL for devices to + # acquire the FW candidate + file-path: ./my.fw.bin # Update candidate local file - for digest + # calculation & signing + format: raw-binary # one of following: + # raw-binary - for full image update + # arm-patch-stream - for differential update + component: MAIN # [Optional] Component name - only relevant for manifest v3 format. + # If omitted "MAIN" component name will be used for updating + # the main application image + sign-image: True # [Optional] Boolean field accepting True/False values - only + # relevant for manifest v3 format. + # When Set to True - 64 Bytes raw signature over the installed + # image will be added to the manifest. + # Image signature can be used for cases when device bootloader + # expects to work with signed images (e.g. secure-boot) + # When omitted False value is assumed + ``` +**Example** + +* For this configuration file, called `my.config.yaml`: + + ```yaml + vendor: + domain: arm.com + device: + model-name: Smart Flip-flops + priority: 1 + payload: + url: http://some-url.com/files?id=1234 + file-path: ./my.fw.bin + format: raw-binary + ``` -Running `manifest-tool init` in a project for the first time also creates a self-signed certificate. If a certificate already exists in `.update-certificates/default.der`, then no certificate is created. If you already have a certificate and private key, you should pass those in to `manifest-tool init` using the `-c ` and `-k ` arguments. +* Run: -###### Creating a self-signed certificate with manifest-tool cert create + ```shell + manifest-tool create \ + --config my.config.yml \ + --key my.priv.key.pem \ + --fw-version 1.2.3 \ + --output my.manifest.bin + ``` -The manifest tool provides a certificate creation command, which creates a self-signed certificate: +#### `manifest-tool create-v1` -``` -manifest-tool cert create -V -K -o -``` +Older versions of Device Management FOTA update client use manifest +schema V1 and assume the public key is packaged in a x.509 certificate. -In addition, you can provide subject arguments on the command-line to specify the country, state, locality, organization name and common name of the certificate's subject. +**Prerequisites** -###### Creating a self-signed certificate with OpenSSL +* An update private key and public key certificate. -Using OpenSSL, you can create a self-signed ECC certificate, but there are several caveats: + Keep the private key secret because it allows installing new + firmware images on your devices. -* OpenSSL defaults to SHA1 on many platforms, which is unsecure. -* On some platforms, it is not possible to specify SHA256. -* OpenSSL does not support ECC on some platforms. + Provision the public key to the device. -**Unless the version of OpenSSL your platform provides is at least 1.0.1, we do not recommend you use OpenSSL.** + * To generate a private key, run: -In order to generate a self-signed certificate, follow these steps: + ```shell + $ openssl ecparam -genkey -name prime256v1 -outform PEM -out my.pkey.pem + ``` + * To generate a public key x.509 certificate, run: -``` -openssl ecparam -genkey -name prime256v1 -out key.pem -openssl req -new -sha256 -key key.pem -out csr.csr -openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -outform der -out certificate.der -``` + ```shell + $ openssl req -new -sha256 \ + -key my.pkey.pem \ + -inform PEM \ + -out my.csr.csr + $ openssl req -x509 -sha256 \ + -days 7300 \ + -key my.pkey.pem \ + -in my.csr.csr \ + -outform der \ + -out my.x509.certificate.der + ``` -**Note:** `prime256v1` is an alias for `secp256r1`. + **Note:** Device Management FOTA treats the x.509 certificate as a container **ONLY** and does not enforce its validity - expiration, chain of trust, and so on - although it may be validated by other Device Management components. For production, we recommend creating a certificate with a lifespan greater than the product's expected lifespan (for example, 20 years). -Now, verify that OpenSSL used SHA256 to sign the certificate. Some OpenSSL installations ignore the `-sha256` parameter and create a SHA1 signature. This is a problem because of the deprecation of SHA1 due to weak security. +**Example** -``` -openssl req -in csr.csr -text -noout | grep -i "Signature.*SHA256" -``` +* For this configuration file, called `my.config.yaml`: -#### Examining a certificate + ```yaml + vendor: + domain: arm.com + device: + model-name: DUT.my.device + priority: 1 + payload: + url: http://some-url.com/files?id=1234 + file-path: ./my.fw.bin + format: raw-binary + ``` -To view the information in a certificate, use OpenSSL's x509 command: +* Run: -``` -openssl x509 -inform der -in certificate.der -text -noout -``` + ```shell + manifest-tool create-v1 \ + --config my.config.yaml \ + --key my.priv.key.pem \ + --update-certificate my.x509.certificate.der \ + --output my.manifest.bin + ``` -#### Obtaining a certificate fingerprint +#### `manifest-tool parse` -The manifest tool fingerprints certificates during the manifest creation process. If you used `manifest-tool init`, then it is not necessary to extract the fingerprint. +Parses and validates existing manifest files. -You can use OpenSSL to check the manifest-tool's output or to obtain the certificate fingerprint if `manifest-tool init` was not used: +**Prerequisites** -``` -openssl x509 -inform der -in certificate.der -sha256 -fingerprint -noout -``` +* A manifest file (in our example `my.manifest.bin`). +* Optionally, an update private key or public key or certificate to + validate the manifest signature. -OpenSSL reports the fingerprint of the certificate: +**Example** -``` -SHA256 Fingerprint=00:01:02:03:04:05:06:07:08:09:0A:0B:0C:0D:0E:0F:10:11:12:13:14:15:16:17:18:19:1A:1B:1C:1D:1E:1F +```shell +$ manifest-tool parse \ + --manifest my.manifest.bin \ + --private-key my.priv.key.pem +----- Manifest dump start ----- +Manifest: +vendor-id=fa6b4a53d5ad5fdfbe9de663e4d41ffe +class-id=3da0f138173350eba6f665498eace1b1 +update-priority=15 +payload-version=1572372313 +payload-digest=b5f07d6c646a7c014cc8c03d2c9caf066bd29006f1356eaeaf13b7d889d3502b +payload-size=512 +payload-uri=https://my.server.com/some.file?new=1 +payload-format=raw-binary +----- Manifest dump end ----- +2019-10-29 20:05:13,478 INFO Signature verified! ``` -When a C byte array is a requirement (for example, in the Update client's certificate manager), this must be converted to one, for example by finding all `:` and replacing with `, 0x`. +#### `manifest-tool schema` -``` -0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F -``` +Prints the input validation JSON schema bundled with the current tool. +The manifest tool contains an input validation schema, which you can use +as a self-documenting tool to better understand and validate the +manifest tool input configuration. -This can be done in an automated way on systems that support the `sed` command. For example: +**Example** +```shell +$ manifest-tool schema ``` -openssl x509 -inform der -in certificate.der -noout -fingerprint -sha256 | sed -e "s/.*=\(.*\)/\1/" | sed -e "s/:/, 0x/g" | sed -e "s/\(.*\)/uint8_t arm_uc_default_fingerprint[] = {0x\1};/" -uint8_t arm_uc_default_fingerprint[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F}; -``` +Output: -To turn the certificate itself into a byte array, use `xxd` or a similar tool for printing hexadecimal values: - -``` -xxd -i certificate.der +```json +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Manifest-tool input validator", + "description": "This schema is used to validate the input arguments for manifest-tool", + "type": "object", + "required": [ + "vendor", + "device", + "priority", + "payload" + ], + "properties": { + "vendor": { + "type": "object", + "properties": { + "domain": { + "$ref": "#/definitions/non_empty_string", + "description": "Vendor Domain", + "pattern": "\\w+(\\.\\w+)+" + }, + "vendor-id": { + "$ref": "#/definitions/uuid_hex_string", + "description": "Vendor UUID" + }, + "custom-data-path": { + "$ref": "#/definitions/non_empty_string", + "description": "Path to custom data file - must be accessible by the manifest-tool" + } + }, + "oneOf": [ + {"required": ["domain"]}, + {"required": ["vendor-id"]} + ] + }, + "device": { + "type": "object", + "properties": { + "model-name": { + "$ref": "#/definitions/non_empty_string", + "description": "Device model name" + }, + "class-id": { + "$ref": "#/definitions/uuid_hex_string", + "description": "Device class UUID" + } + }, + "oneOf": [ + {"required": ["model-name"]}, + {"required": ["class-id"]} + ] + }, + "priority": { + "description": "Update priority", + "type": "integer" + }, + "payload": { + "type": "object", + "required": [ + "url", + "format", + "file-path" + ], + "properties": { + "format": { + "description": "Payload format type", + "enum": [ + "raw-binary", + "arm-patch-stream" + ] + }, + "url": { + "$ref": "#/definitions/non_empty_string", + "description": "Payload URL in the cloud storage" + }, + "file-path": { + "$ref": "#/definitions/non_empty_string", + "description": "Path to payload file - must be accessible by the manifest-tool" + } + } + }, + "component": { + "description": "Component name - only relevant for manifest v3", + "$ref": "#/definitions/non_empty_string" + }, + "sign-image":{ + "description": "Do sign installed image - only relevant for manifest v3. Required for devices with PKI image authentication in bootloader", + "type": "boolean" + } + }, + "definitions": { + "non_empty_string": { + "type": "string", + "minLength": 1 + }, + "uuid_hex_string": { + "type": "string", + "pattern": "[0-9a-fA-F]{32}", + "description": "HEX encoded UUID string" + } + } +} ``` -The manifest tool automates this process as part of the `init` command and places the output in `update_default_resources.c`. - -#### Creating manifests +**Note:** This schema is an example captured for manifest-tool version 2.0. Make sure to execute the `manifest-tool schema` command on your machine to get the up-to-date schema for your installed tool version. -There are three ways to provide data to the manifest tool. It parses a JSON input file, which can contain all of the information used to create the manifest. If information is missing from the input file, the manifest tool checks for a file that contains defaults in the current working directory (`.manifest_tool.json`). You can create this file most easily using `manifest-tool init`. The third way of providing data is command-line arguments; you can override many of the fields the manifest tool uses on the command-line. +#### `manifest-tool public-key` -Currently, you need manifests to use SHA256 for hashes, ECDSA signatures on the secp256r1 curve, with no encryption. The manifest tool calls this encryption mode `none-ecc-secp256r1-sha256`. Future versions of the manifest tool will add support for payload encryption. +Creates a public key file containing a key in uncompressed point format +(X9.62). Provisioning this file to the device enables the device to +verify the manifest signature. -**Note:** The Update client currently only supports binary payloads, so the payload type is assumed to be binary. +**Example** -##### Mode none-ecc-secp256r1-sha256 - -###### Minimum requirements for none-ecc-secp256r1-sha256 +```shell +manifest-tool public-key my.priv.key.pem --out my.pub.key.bin +``` -The minimum requirements for creating a manifest with unencrypted payload are: +### manifest-delta-tool -* The cryptographic mode to use (none-ecc-secp256r1-sha256, in this case). -* The payload URI. -* One of: - * The URI of a certificate to be used for signing the manifest. - * A local file that is a certificate to be used for signing the manifest. -* A local file that is the signing key for that certificate. -* One of: - * The vendor ID and device class ID. - * The device ID. +Use this tool to generate delta patch files for delta updates. -###### What mode none-ecc-secp256r1-sha256 does +Run `manifest-delta-tool --help` for more information about usage and +arguments. -In this mode, the manifest tool creates and signs a manifest; the payload is unencrypted. The target device(s) must already have the provided certificate or must provide a way to fetch that certificate. +**Prerequisites** -The manifest tool: +* The firmware currently installed on the device and the updated + firmware image. Required for calculating the delta patch. -1. Fetches and hashes the payload. It loads the payload from a local file. -1. Fetches and fingerprints the certificate (either from the provided URI or the local file). -1. Creates the inner part of the manifest, containing: - 1. The provided IDs. - 1. The payload URI. - 1. The payload size. - 1. The payload hash. -1. Hashes the inner part of the manifest. -1. Uses the hash and the certificate private key to sign the inner part of the manifest. -1. Wraps the inner part, hash, signature, certificate fingerprint and certificate URI in the outer part of the manifest. +**Example** -###### Using mode none-ecc-secp256r1-sha256 +```shell +$ manifest-delta-tool -c current_fw.bin -n new_fw.bin -o delta-patch.bin +``` -When you invoke the manifest tool to create a manifest with encryption mode `none-ecc-secp256r1-sha256`, the information below must be provided. The manifest tool can find most of the information in more than one way. You can provide every item in the input file. Alternative options are provided in parentheses. +**Note 1:** Compression block size has a direct impact on the amount of memory required by the device receiving the update. The device requires twice the amount of RAM in runtime to decompress and apply the patch. -* The type of hashing, signing and encryption to use (calculated from mandatory inputs if absent). -* Vendor ID (extracted from defaults if absent). -* Class ID (extracted from defaults if absent). -* Payload URI (overridden by `-u`). -* Payload File (overridden by `-p`). -* Description (defaults to empty). -* Certificate used for signing (extracted from defaults if absent). +**Note 2:** Compression block must be aligned with network (COAP/HTTP) buffer size used for download. Misalignment in sizes may result in device failure to process the delta patch file. -###### Example 1: +### manifest-dev-tool -Providing all fields by using the input file: +`manifest-dev-tool` is a developer tool for running a simplified update +campaign. -```JSON -{ - "encryptionMode" : "none-ecc-secp256r1-sha256", - "vendorId" : "", - "classId" : "", - "payloadUri" : "http://path.to/payload.bin", - "payloadFile" : "/path/to/payload.bin", - "description" : "Description of the update", - "certificates": [ - { "uri": "http://path.to/certificate.der" , "file" : "/path/to/certificate.der" } - ] -} -``` +Use `manifest-dev-tool` for development flows only. -To create a manifest with this information, call the manifest tool: +`manifest-dev-tool` commands: +- [`manifest-dev-tool init`](#manifest-dev-tool-init) - Initializes the + developer environment. +- [`manifest-dev-tool create`](#manifest-dev-tool-create) - Simplified + tool for creating manifests. +- [`manifest-dev-tool create-v1`](#manifest-dev-tool-create-v1) - + Simplified tool for creating manifests using the V1 schema. +- [`manifest-dev-tool update`](#manifest-dev-tool-update) - Lets you + perform end-to-end tests without leaving the command shell. +- [`manifest-dev-tool update-v1`](#manifest-dev-tool-update-v1) - Lets + you perform end-to-end tests without leaving the command shell using a + V1-schema manifest. -```sh -$ manifest-tool create -i input.json -o output.manifest -k certificate_key.pem -``` +**Note:** Run `manifest-dev-tool --help` for more information about all commands, or `manifest-dev-tool --help` for more information about a specific command, including its parameters and how to use them. -###### Example 2: +#### `manifest-dev-tool init` -Providing no input file. Run this command one time in the root of the project: +Initializes the developer environment: +* Creates an update private key and a public key certificate. +* Generates a `fota_dev_resources.c` file with symbols that allow + bypassing the provisioning step in the developer flow. +* Creates configuration files, which you use when you run the + [`manifest-dev-tool create`](#manifest-dev-tool-create) and + [`manifest-dev-tool update`](#manifest-dev-tool-update) commands. -```sh -$ manifest-tool init -d "" -m "" -``` +**Note:** Only use the credentials the `manifest-dev-tool` tool generates in the development flow. -Then, use this command to prepare an update: +**Example** -```sh -$ manifest-tool create -u -p -o +```shell +manifest-dev-tool init --force -a [API key from Device Management Portal] ``` -#### Manifest creation input file - -If a `.manifest_tool.json` file is present in the current working directory when you run `manifest-tool create`, `manifest-tool update prepare` or `manifest-tool update device`, the manifest tool loads default values from this file. It overrides these values with the contents of the manifest creation input file. Then, it uses any command-line options to override the contents of the manifest creation input file. If you have used `manifest-tool init` to initialize the current working directory and you use `manifest-tool create -p -u `, then the input file is optional. +#### `manifest-dev-tool create` -This means that all fields in the manifest creation input file are optional. However, the `.manifest_tool.json` defaults file, the manifest creation input file or the command-line must specify some fields: +Creates developer manifest files without requiring an input +configuration file. -1. `vendorId`. -1. `classId`. -1. `payloadUri`. -1. `payloadFile` or `payloadHash`. -1. `certificateFingerprint` or `certificateFile`. -1. `privateKey`. +**Example** -The manifest creation input file follows the JSON representation of the [manifest format v1 specification]. Because there is a significant quantity of nesting in the input fields, there are short-hands for most fields. +```shell +manifest-dev-tool create \ + --payload-url http://test.pdmc.arm.com?fileId=1256 \ + --payload-path new_fw.bin \ + --fw-version 1.2.3 \ + --output update-manifest.bin +``` -Several parts in a nested structure comprise the manifest creation input file: +**Note:** To run a delta update, create the file specified in the `--payload-path` argument using the [`manifest-delta-tool`](#manifest-delta-tool) command. The file has the same name but a `.yaml` suffix (in the example, `new-fw.yaml` instead of `new-fw.bin`). -1. Signed resource. - 1. Manifest. - 1. Encryption info. - 1. Payload info. - 1. Signature block. +**Note:** Add the `--sign-image` argument to update a device with a secure bootloader, which requires an image signature. -##### Signed resource +#### `manifest-dev-tool create-v1` -The signed resource is the top level object in the input file. Because of this, its name does not appear. It contains only two objects: +Creates developer manifest files in v1 format without requiring an input +configuration file. -1. Manifest. -1. Signature block. +**Example** -```JSON -{ - "resource" : { - "resource" : { - "manifest" : - } - }, - "signature" : -} +```shell +manifest-dev-tool create-v1 \ + --payload-url http://test.pdmc.arm.com?fileId=1256 \ + --payload-path new-fw.bin \ + --output update-manifest.bin ``` -* `manifest`: See the [Manifest] section. -* `signature`: See the [Signature block] section. +**Note:** To run a delta update, create the file specified in the `--payload-path` argument using the [`manifest-delta-tool`](#manifest-delta-tool) command. The file has the same name but a `.yaml` suffix (in the example, `new-fw.yaml` instead of `new-fw.bin`). -If you wish to use short-hand parameters, you must place them at this level, within the `SignedResource` object (the un-named top-level JSON object). For example, to use the shorthand for specifying a payload hash, add the `payloadHash` short-hand as below: +#### `manifest-dev-tool update` -```JSON -{ - "resource" : { - "resource" : { - "manifest" : - } - }, - "payloadHash" : , - "signature" : -} -``` +Same as [`manifest-dev-tool create`](#manifest-dev-tool-create) but also +lets you interact with Device Management Portal to run a full update +campaign on a single device. -The full list of short-hand parameters is available in [Short-hand parameters]. +The command: -##### Manifest +1. Uploads the payload to Device Management Portal and obtains the URL. +2. Creates a manifest file with the URL from the previous step and + obtains a manifest URL. +3. Creates an update campaign with the manifest URL from the previous + step. +4. Starts the update campaign if you pass the `--start-campaign` or + `--wait-for-completion` argument. +5. If you pass the `--wait-for-completion` argument, the tool waits for + campaign completion for the time period specified by `--timeout` or + until the campaign reaches one of its terminating states in Device + Management Portal (`expired`, `userstopped`, or + `quotaallocationfailed`). +6. If you pass the `--wait-for-completion` argument without the + `--no-cleanup` flag, the tool removes the uploaded test resources + from Device Management Portal before exiting. When you terminate the + tool, the tool skips the cleanup step. -The manifest object contains several fields and one subobject. +**Note:** [`manifest-dev-tool init`](#manifest-dev-tool-init) creates the directory you specify in `--cache-dir`. -```JSON -{ - "payload": , - "description": "Description of the update", - "vendorId": , - "classId": , - "precursorDigest" : , - "applyImmediately": true, - "priority" : , - "encryptionMode": { - "enum": "none-ecc-secp256r1-sha256" - }, - "vendorInfo": -} -``` +**Example** -* `payload`: See the [Payload] section. -* `description`: A free-text description of the payload. This should be small. -* `vendorId`: Hex representation of the 128-bit RFC4122 GUID that represents the vendor. -* `classId`: Hex representation of the 128-bit RFC4122 GUID that represents the device class that the update targets. Device classes can mean devices of a given type (for example, smart lights) or model numbers. This allows targeting of updates to particular groups of devices based on the attributes they share, where a device class represents each set of attributes. Because of this, each device can have multiple device classes. Device Management Update client only supports the use of device classes to represent model numbers/revisions. -* `precursorDigest` - You can use this field in delta updates to specify the image that must already be present on the device for the delta update to produce the correct result. -* `precursorFile` - A path to a local copy of the precursor. The manifest tool uses this file to calculate the `precursorDigest`. This is not needed if you specify the precursor hash. -* `applyImmediately`: This is always assumed to be true. Device Management Update client does not currently implement it. -* `priority` - The importance of the update. You can use this integer field to tell your application how important an update is, so that it can decide whether to use it or not. The meanings of the values of `priority` are application-defined. 0 typically means "mandatory" and increasing values have lower priority. -* `encryptionMode`: Update client only supports two values: - * `none-ecc-secp256r1-sha256`: SHA256 hashing, ECDSA signatures, using the secp256r1 curve. This does not use payload encryption (Update client only). - * `none-psk-aes-128-ccm-sha256`: SHA256 hashing, manifest digest is authenticated with AES-CCM-128. This does not use payload encryption (Update Client Lite only). -* `vendorInfo`: You can place proprietary information in this field. We recommend DER encoding because this allows you to reuse the Update client's general purpose DER parser. + ```shell + manifest-dev-tool update \ + --payload-path my_mew_fw.bin \ + --fw-version 1.2.3 \ + --wait-for-completion + ``` -##### Payload +**Note:** The tool creates the device filter for the campaign based on the unique `class-id` and `vendor-id` fields the [`manifest-dev-tool init`](#manifest-dev-tool-init) command generates. -The payload section describes the payload object. +#### `manifest-dev-tool update-v1` -```JSON -{ - "storageIdentifier": , - "reference": { - "hash": , - "size": , - "uri": "http://path.to/payload", - "file": - } -} -``` +Same as [`manifest-dev-tool update`](#manifest-dev-tool-update) with a +v1-format manifest. -* `storageIdentifier`: A number that the device recognizes for where to store the payload. -* `hash`: The SHA256 hash of the payload. -* `size`: The size of the payload. -* `uri`: The URI from which the target devices should acquire the payload. -* `file`: A path to a local copy of the payload. The manifest tool uses this file to calculate the payload hash and payload size. This is not needed if you specify the payload hash and size in the input file. -* `installedDigest`: You can use this field with delta updates to specify the result of applying an update. The digest in `reference` specifies the digest of the downloaded object. For delta updates, a second digest is needed to ensure that the result of any processing applied to the resource results in the correct payload image. -* `installedSize`: You can use this field in delta updates to specify the size of an image after the delta update processing is applied. -* `installedFile`: You can use this field to specify a path to a local copy of the desired result of a delta update. The manifest tool uses this file to calculate the `installedDigest` and `installedFile`. This is not needed if you specify `installedDigest` and `installedFile` in the input file. +**Example** -##### Signature block + ```shell + manifest-dev-tool update-v1 \ + --payload-path my_mew_fw.bin \ + --wait-for-completion + ``` -Use the signature block to select the certificate the device should use to verify the signature of the manifest. +### Developer workflow example -```JSON -{ - "signatures": [ - { - "certificates": [ - { - "uri": "", - "fingerprint": "", - "file": "/path/to/certificate.der" - } - ] - } - ] -} -``` +1. Clone the https://github.com/ARMmbed/mbed-cloud-client-example + repository. +2. From within the repository, execute: -* `certificates`: A list of URI/fingerprint pairs. The first certificate in the list must match the private key that you provied to the manifest tool to sign the manifest, supplied through the `-k` command-line option. Each certificate must sign the certificate before it in the list. The last certificate in the list should be the root of trust in the device and can have an empty URI. Instead of a `fingerprint`, you can provide a `file` and the manifest tool will calculate the fingerprint. Note that Device Management Update client does not provide a mechanism to fetch certificates in this list. Implementing this feature requires the developer to override `arm_uc_kcm_cert_fetcher`. By default, Device Management Update client expects to have one certificate and that this certificate must verify all manifests. + ``` + manifest-dev-tool init --force -a $MY_API_KEY + ``` + The tool generates and compiles a `fota_dev_resources.c` file. -##### Short-hand parameters +1. Flash the bootloader and firmware to the device. +1. Create a firmware update candidate. -* `encryptionMode`: Sets the `encryptionMode` in `manifest`. -* `payloadFile`: Sets the `file` in `payload`. -* `payloadUri`: Sets the `uri` in `payload`. -* `payloadHash`: Sets the `hash` in `payload`. -* `payloadSize`: Sets the `size` in `payload`. -* `vendorInfo`: Sets the `vendorInfo` in `manifest`. -* `vendorId`: Sets the `vendorId` in `manifest`. -* `classId`: Sets the `classId` in `manifest`. -* `description`: Sets the `description` in `manifest` -* `certificates`: Sets the `certificates` in `signature`. -* `installedSize` : Sets the `installedSize` in `payload` -* `installedDigest` : Sets the `installedDigest` in `payload` -* `installedFile` : Sets the `installedFile` in `payload` -* `priority` : Sets the `priority` in `manifest` -* `precursorDigest` : Sets the `precursorDigest` in `manifest` -* `precursorFile` : Sets the `precursorFile` in `manifest` + OR + Create a delta-patch: + ``` + manifest-delta-tool -c curr_fw.bin -n new_fw.bin -o delta.bin + ``` -You can also override many of these parameters on the command-line. See `manifest-tool create --help` for more information. +1. Issue an update: -#### Parsing manifests + ``` + manifest-dev-tool update --payload-path + new_fw.bin --wait-for-completion + ``` + For a delta update, the payload is `delta.bin`. -##### Command-line +## Troubleshooting -To convert a manifest to JSON: +* **Getting more context on unexpected errors.** -```sh -manifest-tool parse -i input.manifest -``` + When the tool exits with a non-zero return code, it may be helpful to + get more context on the failure. -To make the JSON more readable, use the `-j` flag. + **Solution:** execute the tool with the `--debug` flag at the top + argument parser level. For example: -```sh -manifest-tool parse -ji input.manifest -``` + ``` + manifest-dev-tool --debug update + ``` -##### Python library +* **`manifest-dev-tool update ... --wait-for-completion` takes longer than expected.** -To convert a manifest file to a Python dictionary: + `manifest-dev-tool update` creates a unique `class-id` and + `vendor-id` generated per developer. Device Management expects a + single device with these properties to connect to Device Management + Portal. -``` -import manifesttool.parse + In rare cases, during development, a device's `device-id` might + change after you re-flash it. This may result in two devices having + the same `class-id` and `vendor-id` in Device Management Portal. In + this scenario, Device Management will detect both devices and try to + update them both, although one of them no longer exists -manifest = open('test0.manifest', 'rb').read() -parsed_manifest = manifesttool.parse.parseManifest(manifest) -print(parsed_manifest) -``` + **Solution:** Manually delete the unwanted device from Device + Management Portal. Alternatively, run `manifest-dev-tool update ... + --wait-for-completion` with `--device-id DEVICE_ID` to override the + default campaign filter and target a specific device by its ID. -### Development +* **Update fails and `manifest-dev-tool update ... + --wait-for-completion` cleans all resources.** -Install all required packages, and create a virtual environment: + You might want to leave the resources (firmware image candidate, + update manifest and update campaign) on a service for further + investigation/retry. -``` -pip2 install virtualenv -mkdir -p ~/virtualenvs -virtualenv ~/virtualenvs/manifest-tool -source ~/virtualenvs/manifest-tool/bin/activate -``` + **Solution:** Execute `manifest-dev-tool update ... + --wait-for-completion` with the `--no-cleanup` flag. diff --git a/bsdiff/bsdiff.c b/bsdiff/bsdiff.c new file mode 100755 index 0000000..adfbed9 --- /dev/null +++ b/bsdiff/bsdiff.c @@ -0,0 +1,497 @@ +/*- + * Copyright 2003-2005 Colin Percival + * Copyright 2012 Matthew Endsley + * Copyright (c) 2018-2019 ARM Limited + * All rights reserved + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted providing that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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 AUTHOR ``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 AUTHOR 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. + */ + +#include "bsdiff.h" +#include "varint.h" +#include +#include +#include +#include + +#include "lz4.h" + +#define MIN(x,y) (((x)<(y)) ? (x) : (y)) + + +//#define TRACING +#ifdef TRACING +#define log(...) printf(__VA_ARGS__) +#else +#define log(...) +#endif + + +static void split(int64_t *I, int64_t *V, int64_t start, int64_t len, int64_t h) +{ + int64_t i, j, k, x, tmp, jj, kk; + + if (len < 16) { + for (k = start; k < start + len; k += j) { + j = 1; + x = V[I[k] + h]; + for (i = 1; k + i < start + len; i++) { + if (V[I[k + i] + h] < x) { + x = V[I[k + i] + h]; + j = 0; + }; + if (V[I[k + i] + h] == x) { + tmp = I[k + j]; + I[k + j] = I[k + i]; + I[k + i] = tmp; + j++; + }; + }; + for (i = 0; i < j; i++){ + V[I[k + i]] = k + j - 1; + } + if (j == 1){ + I[k] = -1; + } + }; + return; + }; + + x = V[I[start + len / 2] + h]; + jj = 0; + kk = 0; + for (i = start; i < start + len; i++) { + if (V[I[i] + h] < x){ + jj++; + } + if (V[I[i] + h] == x){ + kk++; + } + }; + jj += start; + kk += jj; + + i = start; + j = 0; + k = 0; + while (i < jj) { + if (V[I[i] + h] < x) { + i++; + } else if (V[I[i] + h] == x) { + tmp = I[i]; + I[i] = I[jj + j]; + I[jj + j] = tmp; + j++; + } else { + tmp = I[i]; + I[i] = I[kk + k]; + I[kk + k] = tmp; + k++; + }; + }; + + while (jj + j < kk) { + if (V[I[jj + j] + h] == x) { + j++; + } else { + tmp = I[jj + j]; + I[jj + j] = I[kk + k]; + I[kk + k] = tmp; + k++; + }; + }; + + if (jj > start){ + split(I, V, start, jj - start, h); + } + + for (i = 0; i < kk - jj; i++){ + V[I[jj + i]] = kk - 1; + } + if (jj == kk - 1){ + I[jj] = -1; + } + + if (start + len > kk){ + split(I, V, kk, start + len - kk, h); + } +} + +static void qsufsort(int64_t *I, int64_t *V, const uint8_t *old, int64_t oldsize) +{ + int64_t buckets[256]; + int64_t i, h, len; + + for (i = 0; i < 256; i++) + buckets[i] = 0; + for (i = 0; i < oldsize; i++) + buckets[old[i]]++; + for (i = 1; i < 256; i++) + buckets[i] += buckets[i - 1]; + for (i = 255; i > 0; i--) + buckets[i] = buckets[i - 1]; + buckets[0] = 0; + + for (i = 0; i < oldsize; i++) + I[++buckets[old[i]]] = i; + I[0] = oldsize; + for (i = 0; i < oldsize; i++) + V[i] = buckets[old[i]]; + V[oldsize] = 0; + for (i = 1; i < 256; i++) + if (buckets[i] == buckets[i - 1] + 1) + I[buckets[i]] = -1; + I[0] = -1; + + for (h = 1; I[0] != -(oldsize + 1); h += h) { + len = 0; + for (i = 0; i < oldsize + 1;) { + if (I[i] < 0) { + len -= I[i]; + i -= I[i]; + } else { + if (len) + I[i - len] = -len; + len = V[I[i]] + 1 - i; + split(I, V, i, len, h); + i += len; + len = 0; + }; + }; + if (len) + I[i - len] = -len; + }; + + for (i = 0; i < oldsize + 1; i++) + I[V[i]] = i; +} + +static int64_t matchlen(const uint8_t *old, int64_t oldsize, const uint8_t *new, int64_t newsize) +{ + int64_t i; + + for (i = 0; (i < oldsize) && (i < newsize); i++) + if (old[i] != new[i]) + break; + + return i; +} + +static int64_t search(const int64_t *I, const uint8_t *old, int64_t oldsize, const uint8_t *new, int64_t newsize, + int64_t st, int64_t en, int64_t *pos) +{ + int64_t x, y; + + if (en - st < 2) { + x = matchlen(old + I[st], oldsize - I[st], new, newsize); + y = matchlen(old + I[en], oldsize - I[en], new, newsize); + + if (x > y) { + *pos = I[st]; + return x; + } else { + *pos = I[en]; + return y; + } + }; + + x = st + (en - st) / 2; + if (memcmp(old + I[x], new, MIN(oldsize - I[x], newsize)) < 0) { + return search(I, old, oldsize, new, newsize, x, en, pos); + } else { + return search(I, old, oldsize, new, newsize, st, x, pos); + }; +} + +void offtout(int64_t x, uint8_t *buf) +{ + int64_t y; + + if (x < 0) + y = -x; + else + y = x; + + buf[0] = y % 256; + y -= buf[0]; + y = y / 256; + buf[1] = y % 256; + y -= buf[1]; + y = y / 256; + buf[2] = y % 256; + y -= buf[2]; + y = y / 256; + buf[3] = y % 256; + y -= buf[3]; + y = y / 256; + buf[4] = y % 256; + y -= buf[4]; + y = y / 256; + buf[5] = y % 256; + y -= buf[5]; + y = y / 256; + buf[6] = y % 256; + y -= buf[6]; + y = y / 256; + buf[7] = y % 256; + + if (x < 0) + buf[7] |= 0x80; +} + +/** + * Write given buffer to stream in frames, with MAX_FRAME_SIZE as maximum deCompressBuffer and undeCompressBuffer size. + * Store the biggest deCompressBuffer frame size to max_deCompressBuffer_size, if it's bigger than current value. + * @return 0 on success, negative on error. + */ +static int writedeCompressBuffer(struct bsdiff_stream* stream, const void* buffer, int64_t length, + int64_t* max_deCompressBuffer_size, int64_t max_frame_size) +{ + int src_ptr; + char* temp; + int deCompressBuffer_size; + int written = 0; + uint8_t buf[8]; + + if (length == 0) + return 0; + + temp = stream->malloc(max_frame_size); + src_ptr = (int)(MIN(length, max_frame_size)); + + do { + deCompressBuffer_size = LZ4_compress_destSize(buffer, temp, &src_ptr, (int)(max_frame_size)); + + if (deCompressBuffer_size == 0) { + stream->free(temp); + return -1; + } + + int encodedSize = encode_unsigned_varint(deCompressBuffer_size, buf, sizeof(buf)); + + log("writedeCompressBuffer %llu compressedSize %u (var intS %u)\n", length, deCompressBuffer_size, encodedSize); + if (encodedSize <= 0) { + return encodedSize; // error in encoding + } + stream->write(stream, buf, encodedSize); + + stream->write(stream, temp, deCompressBuffer_size); + + buffer = (char*) buffer + src_ptr; + written += src_ptr; + + src_ptr = (int)(MIN(length - written, max_frame_size)); + + if (deCompressBuffer_size > *max_deCompressBuffer_size){ + *max_deCompressBuffer_size = deCompressBuffer_size; + } + + } while (written != length); + + stream->free(temp); + return 0; +} + +struct bsdiff_request { + const uint8_t* old; + int64_t oldsize; + const uint8_t* new; + int64_t newsize; + struct bsdiff_stream* stream; + int64_t *I; + uint8_t *buffer; +}; + +static int bsdiff_internal(const struct bsdiff_request req, int64_t* max_deCompressBuffer_size, + const int64_t max_frame_size) +{ + int64_t *I, *V; + int64_t scan, pos, len; + int64_t lastscan, lastpos, lastoffset; + int64_t oldscore, scsc; + int64_t s, Sf, lenf, Sb, lenb; + int64_t overlap, Ss, lens; + int64_t i; + uint8_t *buffer; + uint8_t buf[8 * 3]; + + if ((V = req.stream->malloc((req.oldsize + 1) * sizeof(int64_t))) == NULL){ + return -1; + } + I = req.I; + + qsufsort(I, V, req.old, req.oldsize); + req.stream->free(V); + + buffer = req.buffer; + + /* Compute the differences, writing ctrl as we go */ + scan = 0; + len = 0; + pos = 0; + lastscan = 0; + lastpos = 0; + lastoffset = 0; + while (scan < req.newsize) { + oldscore = 0; + + for (scsc = scan += len; scan < req.newsize; scan++) { + len = search(I, req.old, req.oldsize, req.new + scan, req.newsize - scan, 0, req.oldsize, &pos); + + for (; scsc < scan + len; scsc++) + if ((scsc + lastoffset < req.oldsize) && (req.old[scsc + lastoffset] == req.new[scsc])) + oldscore++; + + if (((len == oldscore) && (len != 0)) || (len > oldscore + 8)) + break; + + if ((scan + lastoffset < req.oldsize) && (req.old[scan + lastoffset] == req.new[scan])) + oldscore--; + }; + + if ((len != oldscore) || (scan == req.newsize)) { + s = 0; + Sf = 0; + lenf = 0; + for (i = 0; (lastscan + i < scan) && (lastpos + i < req.oldsize);) { + if (req.old[lastpos + i] == req.new[lastscan + i]) + s++; + i++; + if (s * 2 - i > Sf * 2 - lenf) { + Sf = s; + lenf = i; + }; + }; + + lenb = 0; + if (scan < req.newsize) { + s = 0; + Sb = 0; + for (i = 1; (scan >= lastscan + i) && (pos >= i); i++) { + if (req.old[pos - i] == req.new[scan - i]) + s++; + if (s * 2 - i > Sb * 2 - lenb) { + Sb = s; + lenb = i; + }; + }; + }; + + if (lastscan + lenf > scan - lenb) { + overlap = (lastscan + lenf) - (scan - lenb); + s = 0; + Ss = 0; + lens = 0; + for (i = 0; i < overlap; i++) { + if (req.new[lastscan + lenf - overlap + i] == req.old[lastpos + lenf - overlap + i]) + s++; + if (req.new[scan - lenb + i] == req.old[pos - lenb + i]) + s--; + if (s > Ss) { + Ss = s; + lens = i + 1; + }; + }; + + lenf += lens - overlap; + lenb -= lens; + }; + + int64_t diff_str_len = lenf; + int64_t extra_str_len_y = (scan - lenb) - (lastscan + lenf); + int64_t old_file_ctrl_off_set_jump = (pos - lenb) - (lastpos + lenf); + + int posInBuf = 0; + int encodedSize = encode_unsigned_varint(diff_str_len, &buf[posInBuf], 8); + + assert(encodedSize > 0 && encodedSize <= 8); + posInBuf += encodedSize; + + encodedSize = encode_unsigned_varint(extra_str_len_y, &buf[posInBuf], 8); + assert(encodedSize > 0 && encodedSize <= 8); + posInBuf += encodedSize; + + encodedSize = encode_signed_varint(old_file_ctrl_off_set_jump, &buf[posInBuf], 8); + assert(encodedSize > 0 && encodedSize <= 8); + posInBuf += encodedSize; + + log( "DIFF_STR_LEN_X: %lld EXTRA_STR_LEN_Y: %lld OLD_FILE_CTRL_OFF_SET_JUMP %lld (encoded to %i)\n", + lenf, (scan - lenb) - (lastscan + lenf), (pos - lenb) - (lastpos + lenf), posInBuf); + + /* Write control data */ + req.stream->write(req.stream, buf, posInBuf); + + /* Write diff data */ + for (i = 0; i < lenf; i++){ + buffer[i] = req.new[lastscan + i] - req.old[lastpos + i]; + } + if (writedeCompressBuffer(req.stream, buffer, lenf, max_deCompressBuffer_size, max_frame_size)) { + return -1; + } + + /* Write extra data */ + for (i = 0; i < (scan - lenb) - (lastscan + lenf); i++){ + buffer[i] = req.new[lastscan + lenf + i]; + } + if (writedeCompressBuffer(req.stream, buffer, (scan - lenb) - (lastscan + lenf), max_deCompressBuffer_size, + max_frame_size)) { + return -1; + } + + lastscan = scan - lenb; + lastpos = pos - lenb; + lastoffset = pos - scan; + }; + }; + + return 0; +} + +int bsdiff(const uint8_t* old, int64_t oldsize, const uint8_t* new, int64_t newsize, struct bsdiff_stream* stream, + int64_t* max_deCompressBuffer_size, const int64_t max_frame_size) +{ + int result; + struct bsdiff_request req; + + if ((req.I = stream->malloc((oldsize + 1) * sizeof(int64_t))) == NULL) { + return -1; + } + + if ((req.buffer = stream->malloc(newsize + 1)) == NULL) { + stream->free(req.I); + return -1; + } + + req.old = old; + req.oldsize = oldsize; + req.new = new; + req.newsize = newsize; + req.stream = stream; + + result = bsdiff_internal(req, max_deCompressBuffer_size, max_frame_size); + + stream->free(req.buffer); + stream->free(req.I); + + return result; +} + diff --git a/bsdiff/bsdiff.h b/bsdiff/bsdiff.h new file mode 100755 index 0000000..e5d0723 --- /dev/null +++ b/bsdiff/bsdiff.h @@ -0,0 +1,51 @@ +/*- + * Copyright 2003-2005 Colin Percival + * Copyright 2012 Matthew Endsley + * Copyright (c) 2018-2019 ARM Limited + * All rights reserved + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted providing that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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 AUTHOR ``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 AUTHOR 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. + */ + +#ifndef BSDIFF_H +#define BSDIFF_H + +# include +# include + +struct bsdiff_stream { + void* opaque; + void* (*malloc)(size_t size); + void (*free)(void* ptr); + int (*write)(struct bsdiff_stream* stream, const void* buffer, + uint64_t size); +}; + +int bsdiff( + const uint8_t* old, int64_t oldsize, + const uint8_t* new, int64_t newsize, + struct bsdiff_stream* stream, + int64_t* max_deCompressBuffer_size, + const int64_t max_frame_size +); + +#endif diff --git a/bsdiff/bsdiff_helper.c b/bsdiff/bsdiff_helper.c new file mode 100644 index 0000000..40be4e1 --- /dev/null +++ b/bsdiff/bsdiff_helper.c @@ -0,0 +1,189 @@ +// ---------------------------------------------------------------------------- +// Copyright 2019 ARM Ltd. +// +// 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. +// ---------------------------------------------------------------------------- +#include "common.h" +#include "bsdiff.h" +#include "bsdiff_helper.h" +#include +#include +#include +#include + +//#ifdef __unix +//#if defined(__gnuc__) +#if !defined(__CYGWIN__) && !defined(_WIN32) +#define fopen_s(pFile, filename, mode) ((*(pFile)) = fopen((filename), (mode))) == NULL +#endif + +#define ERR(msg) do { \ + deliver_error(msg); \ + status = -1; \ + goto end; \ + } while(0) + +void offtout(int64_t x, uint8_t *buf); + +static int file_write(struct bsdiff_stream* stream, const void* buffer, + uint64_t size) { + return fwrite(buffer, sizeof(uint8_t), size, (FILE*) stream->opaque) == size ? 0 : -1; +} + + +int do_diff( + const char* old_fw_img, + const char* new_fw_img, + const char* delta_file, + int64_t max_frame_size +) +{ + int status = 0; + uint8_t *old_data = NULL; + uint8_t *new_data = NULL; + size_t old_size = 0; + size_t new_size = 0; + uint8_t buf[24] = {0}; + FILE *delta_fp = NULL; + FILE *old_fp = NULL; + FILE *new_fp = NULL; + + int64_t max_deCompressBuffer_size = 0; + int64_t patch_file_size = 0; + + /* --------------- Load old FW -------------------------------------------*/ + { + if (fopen_s(&old_fp, old_fw_img, "rb")){ + ERR("Failed to open old FW image"); + } + + fseek(old_fp, 0L, SEEK_END); + old_size = ftell(old_fp); + if (0 >= old_size) { + ERR("Malformed old FW image"); + } + fseek(old_fp, 0L, SEEK_SET); + + /* Allocate oldsize+1 bytes instead of oldsize bytes to ensure + that we never try to malloc(0) and get a NULL pointer */ + old_data = malloc(old_size + 1); + if (NULL == old_data){ + ERR("Failed to allocate memory for old FW image"); + } + + if (1 != fread(old_data, old_size, 1, old_fp)) { + ERR("Failed to read old FW image"); + } + + } + /* -------------- Load new FW --------------------------------------------*/ + { + if (fopen_s(&new_fp, new_fw_img, "rb")){ + ERR("Failed to open new FW image"); + } + + fseek(new_fp, 0L, SEEK_END); + new_size = ftell(new_fp); + if (0 >= new_size) { + ERR("Malformed new FW image"); + } + fseek(new_fp, 0L, SEEK_SET); + + /* Allocate newsize+1 bytes instead of newsize bytes to ensure + that we never try to malloc(0) and get a NULL pointer */ + new_data = malloc(new_size + 1); + if (NULL == new_data){ + ERR("Failed to allocate memory for new FW image"); + } + + if (1 != fread(new_data, new_size, 1, new_fp)) { + ERR("Failed to read new FW image"); + } + + } + + /* ------------------- Create the patch file -----------------------------*/ + if (fopen_s(&delta_fp, delta_file, "wb")) { + ERR("Failed to create delta file"); + } + + /* Write header (signature+newsize+max undeCompressBuffer+maxdeCompressBuffer)*/ + offtout(new_size, buf); + offtout(max_frame_size, buf + 8); + offtout(max_deCompressBuffer_size, buf + 16); + if ( + (1 != fwrite(FILE_MAGIC, FILE_MAGIC_LEN, 1, delta_fp)) || + (1 != fwrite(buf, sizeof(buf), 1, delta_fp)) + ) { + ERR("Failed to write header"); + } + + struct bsdiff_stream stream = { + .malloc = malloc, + .free = free, + .write = file_write, + .opaque = delta_fp + + }; + if (bsdiff(old_data, old_size, new_data, new_size, &stream, &max_deCompressBuffer_size, + max_frame_size)) { + ERR("bsdiff failed"); + } + + /* Go back to header and fill the maxdeCompressBuffer properly */ + offtout(max_deCompressBuffer_size, buf); + fseek(delta_fp, 32, SEEK_SET); + if (fwrite(buf, 1, 8, delta_fp) != 8) { + ERR("Failed to write maxdeCompressBuffer"); + } + + fseek(delta_fp, 0, SEEK_END); + patch_file_size = ftell(delta_fp); + +end: + if (0 == status){ + printf( + "Wrote diff file %s, size %lld. Max undeCompressBuffer frame size was %lld, max deCompressBuffer frame size was %lld.\n", + delta_file, patch_file_size, max_frame_size, + max_deCompressBuffer_size + ); + } + + if (old_fp){ + fclose(old_fp); + } + + if (new_fp){ + fclose(new_fp); + } + + if (delta_fp){ + fclose(delta_fp); + } + + if(old_data){ + free(old_data); + } + if (new_data){ + free(new_data); + } + + return status; +} + +const char *bsdiff_get_version(void) +{ + return FILE_MAGIC; +} diff --git a/bsdiff/bsdiff_helper.h b/bsdiff/bsdiff_helper.h new file mode 100644 index 0000000..6425d86 --- /dev/null +++ b/bsdiff/bsdiff_helper.h @@ -0,0 +1,36 @@ +// ---------------------------------------------------------------------------- +// Copyright 2019 ARM Ltd. +// +// 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. +// ---------------------------------------------------------------------------- + +#ifndef DELTA_TOOL_INTERNAL_BSDIFF_BSDIFF_HELPER_H_ +#define DELTA_TOOL_INTERNAL_BSDIFF_BSDIFF_HELPER_H_ + +void deliver_error(const char *msg); + +int do_diff( + const char* old_fw_img, + const char* new_fw_img, + const char* delta_file, + int64_t max_frame_size +); + + +const char *bsdiff_get_version(void); + + + +#endif /* DELTA_TOOL_INTERNAL_BSDIFF_BSDIFF_HELPER_H_ */ diff --git a/bsdiff/bsdiff_python.c b/bsdiff/bsdiff_python.c new file mode 100644 index 0000000..21aaefb --- /dev/null +++ b/bsdiff/bsdiff_python.c @@ -0,0 +1,90 @@ +// ---------------------------------------------------------------------------- +// Copyright 2019 ARM Ltd. +// +// 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. +// ---------------------------------------------------------------------------- + +#include + +#include "common.h" +#include "bsdiff.h" +#include "bsdiff_helper.h" + +#define MODULE_NAME "armbsdiff" + +void deliver_error(const char *msg){ + PyErr_SetString(PyExc_RuntimeError, msg); +} + +static PyObject *armbsdiff_get_version(PyObject *self, PyObject *args) { + const char *version = bsdiff_get_version(); + + return Py_BuildValue("s", version); +} + + +static PyObject *armbsdiff_generate(PyObject *self, PyObject *args) { + const char* old_fw_img = NULL; + const char* new_fw_img = NULL; + const char* delta_file = NULL; + int64_t max_frame_size = 0; + + if (!PyArg_ParseTuple(args, "sssL", &old_fw_img, &new_fw_img, &delta_file, &max_frame_size)) { + return NULL; + } + + int status = do_diff(old_fw_img, new_fw_img, delta_file, max_frame_size); + if (0 != status) { + return NULL; // flag an error + } + Py_RETURN_NONE; +} + + +// Method definition object for this extension +static PyMethodDef armbsdiff_methods[] = { + { "get_version", (PyCFunction)armbsdiff_get_version, METH_NOARGS, "Get bsdiff version" }, + { "generate", (PyCFunction)armbsdiff_generate, METH_VARARGS, "Generate delta patch" }, + { NULL, NULL, 0, NULL } +}; + +#if PY_MAJOR_VERSION >= 3 + +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + MODULE_NAME, + NULL, + 0, + armbsdiff_methods, +}; + +PyMODINIT_FUNC PyInit_armbsdiff(void) +{ + PyObject *module = PyModule_Create(&moduledef); + return module; +} + + + +#else + +PyMODINIT_FUNC initarmbsdiff(void) +{ + Py_InitModule(MODULE_NAME, armbsdiff_methods); + return; +} + +#endif //PY_MAJOR_VERSION >= 3 + diff --git a/bsdiff/common.h b/bsdiff/common.h new file mode 100644 index 0000000..aa3b012 --- /dev/null +++ b/bsdiff/common.h @@ -0,0 +1,27 @@ +// ---------------------------------------------------------------------------- +// Copyright 2019 ARM Ltd. +// +// 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. +// ---------------------------------------------------------------------------- + +#ifndef DELTA_TOOL_INTERNAL_INCLUDE_COMMON_H_ +#define DELTA_TOOL_INTERNAL_INCLUDE_COMMON_H_ + +#define FILE_MAGIC "PELION/BSDIFF001" // BSDIFF version +#define FILE_MAGIC_LEN (sizeof(FILE_MAGIC) - 1) // without the null termination + +#define MAX_FRAME_SIZE_DEFAULT 512 + +#endif /* DELTA_TOOL_INTERNAL_INCLUDE_COMMON_H_ */ diff --git a/bsdiff/import.sh b/bsdiff/import.sh new file mode 100755 index 0000000..48a44b3 --- /dev/null +++ b/bsdiff/import.sh @@ -0,0 +1,41 @@ +#!/bin/bash -e +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + + +DELTA_TOOL_DIR=${1:?"missing delta-tool directory path"} +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" + +declare -a BSDIFF_FILES=( + "$DELTA_TOOL_DIR/bsdiff/bsdiff.c" + "$DELTA_TOOL_DIR/bsdiff/bsdiff.h" + "$DELTA_TOOL_DIR/bsdiff/bsdiff_helper.c" + "$DELTA_TOOL_DIR/bsdiff/bsdiff_helper.h" + "$DELTA_TOOL_DIR/bsdiff/common.h" + "$DELTA_TOOL_DIR/bsdiff/lz4.c" + "$DELTA_TOOL_DIR/bsdiff/lz4.h" + "$DELTA_TOOL_DIR/bsdiff/varint.c" + "$DELTA_TOOL_DIR/bsdiff/varint.h" +) + +for file in "${BSDIFF_FILES[@]}" +do + cp -v $file $SCRIPT_DIR +done + +echo "Imported from delta-tool at hash: $(git -C $DELTA_TOOL_DIR rev-parse HEAD)" > $SCRIPT_DIR/import_ref.txt \ No newline at end of file diff --git a/bsdiff/import_ref.txt b/bsdiff/import_ref.txt new file mode 100644 index 0000000..721ae19 --- /dev/null +++ b/bsdiff/import_ref.txt @@ -0,0 +1 @@ +Imported from delta-tool at hash: f2029f7867d37023cbf6dc5957c73b669d68a2a4 diff --git a/bsdiff/lz4.c b/bsdiff/lz4.c new file mode 100755 index 0000000..a299a72 --- /dev/null +++ b/bsdiff/lz4.c @@ -0,0 +1,1972 @@ +/* + LZ4 - Fast LZ compression algorithm + Copyright (C) 2011-present, Yann Collet. + + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + 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 + 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. + + You can contact the author at : + - LZ4 homepage : http://www.lz4.org + - LZ4 source repository : https://github.com/lz4/lz4 +*/ + + +/*-************************************ +* Tuning parameters +**************************************/ +/* + * LZ4_HEAPMODE : + * Select how default compression functions will allocate memory for their hash table, + * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()). + */ +#ifndef LZ4_HEAPMODE +# define LZ4_HEAPMODE 0 +#endif + +/* + * ACCELERATION_DEFAULT : + * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0 + */ +#define ACCELERATION_DEFAULT 1 + + +/*-************************************ +* CPU Feature Detection +**************************************/ +/* LZ4_FORCE_MEMORY_ACCESS + * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. + * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. + * The below switch allow to select different access method for improved performance. + * Method 0 (default) : use `memcpy()`. Safe and portable. + * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). + * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. + * Method 2 : direct access. This method is portable but violate C standard. + * It can generate buggy code on targets which assembly generation depends on alignment. + * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) + * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details. + * Prefer these methods in priority order (0 > 1 > 2) + */ +#ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */ +# if defined(__GNUC__) && \ + ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \ + || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) +# define LZ4_FORCE_MEMORY_ACCESS 2 +# elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__) +# define LZ4_FORCE_MEMORY_ACCESS 1 +# endif +#endif + +/* + * LZ4_FORCE_SW_BITCOUNT + * Define this parameter if your target system or compiler does not support hardware bit count + */ +#if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for WinCE doesn't support Hardware bit count */ +# define LZ4_FORCE_SW_BITCOUNT +#endif + + + +/*-************************************ +* Dependency +**************************************/ +#define LZ4_STATIC_LINKING_ONLY +#define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */ +#include "lz4.h" +/* see also "memory routines" below */ + + +/*-************************************ +* Compiler Options +**************************************/ +#ifdef _MSC_VER /* Visual Studio */ +# include +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +# pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */ +#endif /* _MSC_VER */ + +#ifndef LZ4_FORCE_INLINE +# ifdef _MSC_VER /* Visual Studio */ +# define LZ4_FORCE_INLINE static __forceinline +# else +# if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ +# ifdef __GNUC__ +# define LZ4_FORCE_INLINE static inline __attribute__((always_inline)) +# else +# define LZ4_FORCE_INLINE static inline +# endif +# else +# define LZ4_FORCE_INLINE static +# endif /* __STDC_VERSION__ */ +# endif /* _MSC_VER */ +#endif /* LZ4_FORCE_INLINE */ + +/* LZ4_FORCE_O2_GCC_PPC64LE and LZ4_FORCE_O2_INLINE_GCC_PPC64LE + * Gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy, + * together with a simple 8-byte copy loop as a fall-back path. + * However, this optimization hurts the decompression speed by >30%, + * because the execution does not go to the optimized loop + * for typical compressible data, and all of the preamble checks + * before going to the fall-back path become useless overhead. + * This optimization happens only with the -O3 flag, and -O2 generates + * a simple 8-byte copy loop. + * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy + * functions are annotated with __attribute__((optimize("O2"))), + * and also LZ4_wildCopy is forcibly inlined, so that the O2 attribute + * of LZ4_wildCopy does not affect the compression speed. + */ +#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) +# define LZ4_FORCE_O2_GCC_PPC64LE __attribute__((optimize("O2"))) +# define LZ4_FORCE_O2_INLINE_GCC_PPC64LE __attribute__((optimize("O2"))) LZ4_FORCE_INLINE +#else +# define LZ4_FORCE_O2_GCC_PPC64LE +# define LZ4_FORCE_O2_INLINE_GCC_PPC64LE static +#endif + +#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__) +# define expect(expr,value) (__builtin_expect ((expr),(value)) ) +#else +# define expect(expr,value) (expr) +#endif + +#ifndef likely +#define likely(expr) expect((expr) != 0, 1) +#endif +#ifndef unlikely +#define unlikely(expr) expect((expr) != 0, 0) +#endif + + +/*-************************************ +* Memory routines +**************************************/ +#include /* malloc, calloc, free */ +#define ALLOC(s) malloc(s) +#define ALLOC_AND_ZERO(s) calloc(1,s) +#define FREEMEM(p) free(p) +#include /* memset, memcpy */ +#define MEM_INIT(p,v,s) memset((p),(v),(s)) + + +/*-************************************ +* Basic Types +**************************************/ +#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# include + typedef uint8_t BYTE; + typedef uint16_t U16; + typedef uint32_t U32; + typedef int32_t S32; + typedef uint64_t U64; + typedef uintptr_t uptrval; +#else + typedef unsigned char BYTE; + typedef unsigned short U16; + typedef unsigned int U32; + typedef signed int S32; + typedef unsigned long long U64; + typedef size_t uptrval; /* generally true, except OpenVMS-64 */ +#endif + +#if defined(__x86_64__) + typedef U64 reg_t; /* 64-bits in x32 mode */ +#else + typedef size_t reg_t; /* 32-bits in x32 mode */ +#endif + +/*-************************************ +* Reading and writing into memory +**************************************/ +static unsigned LZ4_isLittleEndian(void) +{ + const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ + return one.c[0]; +} + + +#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2) +/* lie to the compiler about data alignment; use with caution */ + +static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; } +static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; } +static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; } + +static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; } +static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } + +#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1) + +/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ +/* currently only defined for gcc and icc */ +typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign; + +static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; } +static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } +static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; } + +static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; } +static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; } + +#else /* safe and portable access through memcpy() */ + +static U16 LZ4_read16(const void* memPtr) +{ + U16 val; memcpy(&val, memPtr, sizeof(val)); return val; +} + +static U32 LZ4_read32(const void* memPtr) +{ + U32 val; memcpy(&val, memPtr, sizeof(val)); return val; +} + +static reg_t LZ4_read_ARCH(const void* memPtr) +{ + reg_t val; memcpy(&val, memPtr, sizeof(val)); return val; +} + +static void LZ4_write16(void* memPtr, U16 value) +{ + memcpy(memPtr, &value, sizeof(value)); +} + +static void LZ4_write32(void* memPtr, U32 value) +{ + memcpy(memPtr, &value, sizeof(value)); +} + +#endif /* LZ4_FORCE_MEMORY_ACCESS */ + + +static U16 LZ4_readLE16(const void* memPtr) +{ + if (LZ4_isLittleEndian()) { + return LZ4_read16(memPtr); + } else { + const BYTE* p = (const BYTE*)memPtr; + return (U16)((U16)p[0] + (p[1]<<8)); + } +} + +static void LZ4_writeLE16(void* memPtr, U16 value) +{ + if (LZ4_isLittleEndian()) { + LZ4_write16(memPtr, value); + } else { + BYTE* p = (BYTE*)memPtr; + p[0] = (BYTE) value; + p[1] = (BYTE)(value>>8); + } +} + +/* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */ +LZ4_FORCE_O2_INLINE_GCC_PPC64LE +void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd) +{ + BYTE* d = (BYTE*)dstPtr; + const BYTE* s = (const BYTE*)srcPtr; + BYTE* const e = (BYTE*)dstEnd; + + do { memcpy(d,s,8); d+=8; s+=8; } while (d=1) +# include +#else +# ifndef assert +# define assert(condition) ((void)0) +# endif +#endif + +#define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use after variable declarations */ + +#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2) +# include +static int g_debuglog_enable = 1; +# define DEBUGLOG(l, ...) { \ + if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) { \ + fprintf(stderr, __FILE__ ": "); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, " \n"); \ + } } +#else +# define DEBUGLOG(l, ...) {} /* disabled */ +#endif + + +/*-************************************ +* Common functions +**************************************/ +static unsigned LZ4_NbCommonBytes (reg_t val) +{ + if (LZ4_isLittleEndian()) { + if (sizeof(val)==8) { +# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r = 0; + _BitScanForward64( &r, (U64)val ); + return (int)(r>>3); +# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_ctzll((U64)val) >> 3); +# else + static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, + 0, 3, 1, 3, 1, 4, 2, 7, + 0, 2, 3, 6, 1, 5, 3, 5, + 1, 3, 4, 4, 2, 5, 6, 7, + 7, 0, 1, 2, 3, 3, 4, 6, + 2, 6, 5, 5, 3, 4, 5, 6, + 7, 1, 2, 4, 6, 4, 4, 5, + 7, 2, 6, 5, 7, 6, 7, 7 }; + return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58]; +# endif + } else /* 32 bits */ { +# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r; + _BitScanForward( &r, (U32)val ); + return (int)(r>>3); +# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_ctz((U32)val) >> 3); +# else + static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, + 3, 2, 2, 1, 3, 2, 0, 1, + 3, 3, 1, 2, 2, 2, 2, 0, + 3, 1, 2, 0, 1, 0, 1, 1 }; + return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27]; +# endif + } + } else /* Big Endian CPU */ { + if (sizeof(val)==8) { /* 64-bits */ +# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r = 0; + _BitScanReverse64( &r, val ); + return (unsigned)(r>>3); +# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_clzll((U64)val) >> 3); +# else + static const U32 by32 = sizeof(val)*4; /* 32 on 64 bits (goal), 16 on 32 bits. + Just to avoid some static analyzer complaining about shift by 32 on 32-bits target. + Note that this code path is never triggered in 32-bits mode. */ + unsigned r; + if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; } + if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } + r += (!val); + return r; +# endif + } else /* 32 bits */ { +# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r = 0; + _BitScanReverse( &r, (unsigned long)val ); + return (unsigned)(r>>3); +# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_clz((U32)val) >> 3); +# else + unsigned r; + if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; } + r += (!val); + return r; +# endif + } + } +} + +#define STEPSIZE sizeof(reg_t) +LZ4_FORCE_INLINE +unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) +{ + const BYTE* const pStart = pIn; + + if (likely(pIn < pInLimit-(STEPSIZE-1))) { + reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); + if (!diff) { + pIn+=STEPSIZE; pMatch+=STEPSIZE; + } else { + return LZ4_NbCommonBytes(diff); + } } + + while (likely(pIn < pInLimit-(STEPSIZE-1))) { + reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); + if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; } + pIn += LZ4_NbCommonBytes(diff); + return (unsigned)(pIn - pStart); + } + + if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; } + if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; } + if ((pIn compression run slower on incompressible data */ + + +/*-************************************ +* Local Structures and types +**************************************/ +typedef enum { notLimited = 0, limitedOutput = 1, fillOutput = 2 } limitedOutput_directive; +typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t; + +/** + * This enum distinguishes several different modes of accessing previous + * content in the stream. + * + * - noDict : There is no preceding content. + * - withPrefix64k : Table entries up to ctx->dictSize before the current blob + * blob being deCompressBuffer are valid and refer to the preceding + * content (of length ctx->dictSize), which is available + * contiguously preceding in memory the content currently + * being deCompressBuffer. + * - usingExtDict : Like withPrefix64k, but the preceding content is somewhere + * else in memory, starting at ctx->dictionary with length + * ctx->dictSize. + * - usingDictCtx : Like usingExtDict, but everything concerning the preceding + * content is in a separate context, pointed to by + * ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table + * entries in the current context that refer to positions + * preceding the beginning of the current compression are + * ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx + * ->dictSize describe the location and size of the preceding + * content, and matches are found by looking in the ctx + * ->dictCtx->hashTable. + */ +typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive; +typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive; + + +/*-************************************ +* Local Utils +**************************************/ +int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; } +const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; } +int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); } +int LZ4_sizeofState() { return LZ4_STREAMSIZE; } + + +/*-************************************ +* Internal Definitions used in Tests +**************************************/ +#if defined (__cplusplus) +extern "C" { +#endif + +int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize); + +int LZ4_decompress_safe_forceExtDict(const char* in, char* out, int inSize, int outSize, const void* dict, size_t dictSize); + +#if defined (__cplusplus) +} +#endif + +/*-****************************** +* Compression functions +********************************/ +static U32 LZ4_hash4(U32 sequence, tableType_t const tableType) +{ + if (tableType == byU16) + return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1))); + else + return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG)); +} + +static U32 LZ4_hash5(U64 sequence, tableType_t const tableType) +{ + const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG; + if (LZ4_isLittleEndian()) { + const U64 prime5bytes = 889523592379ULL; + return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog)); + } else { + const U64 prime8bytes = 11400714785074694791ULL; + return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog)); + } +} + +LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType) +{ + if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType); + return LZ4_hash4(LZ4_read32(p), tableType); +} + +static void LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableType_t const tableType) +{ + switch (tableType) + { + default: /* fallthrough */ + case clearedTable: /* fallthrough */ + case byPtr: { /* illegal! */ assert(0); return; } + case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; } + case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; } + } +} + +static void LZ4_putPositionOnHash(const BYTE* p, U32 h, + void* tableBase, tableType_t const tableType, + const BYTE* srcBase) +{ + switch (tableType) + { + case clearedTable: { /* illegal! */ assert(0); return; } + case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; } + case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; } + case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; } + } +} + +LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase) +{ + U32 const h = LZ4_hashPosition(p, tableType); + LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase); +} + +/* LZ4_getIndexOnHash() : + * Index of match position registered in hash table. + * hash position must be calculated by using base+index, or dictBase+index. + * Assumption 1 : only valid if tableType == byU32 or byU16. + * Assumption 2 : h is presumed valid (within limits of hash table) + */ +static U32 LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_t tableType) +{ + LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2); + if (tableType == byU32) { + const U32* const hashTable = (const U32*) tableBase; + assert(h < (1U << (LZ4_MEMORY_USAGE-2))); + return hashTable[h]; + } + if (tableType == byU16) { + const U16* const hashTable = (const U16*) tableBase; + assert(h < (1U << (LZ4_MEMORY_USAGE-1))); + return hashTable[h]; + } + assert(0); return 0; /* forbidden case */ +} + +static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase) +{ + if (tableType == byPtr) { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; } + if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; return hashTable[h] + srcBase; } + { const U16* const hashTable = (const U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */ +} + +LZ4_FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p, + const void* tableBase, tableType_t tableType, + const BYTE* srcBase) +{ + U32 const h = LZ4_hashPosition(p, tableType); + return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase); +} + +LZ4_FORCE_INLINE void LZ4_prepareTable( + LZ4_stream_t_internal* const cctx, + const int inputSize, + const tableType_t tableType) { + /* If the table hasn't been used, it's guaranteed to be zeroed out, and is + * therefore safe to use no matter what mode we're in. Otherwise, we figure + * out if it's safe to leave as is or whether it needs to be reset. + */ + if (cctx->tableType != clearedTable) { + if (cctx->tableType != tableType + || (tableType == byU16 && cctx->currentOffset + inputSize >= 0xFFFFU) + || (tableType == byU32 && cctx->currentOffset > 1 GB) + || tableType == byPtr + || inputSize >= 4 KB) + { + DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", cctx); + MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE); + cctx->currentOffset = 0; + cctx->tableType = clearedTable; + } else { + DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)"); + } + } + + /* Adding a gap, so all previous entries are > MAX_DISTANCE back, is faster + * than compressing without a gap. However, compressing with + * currentOffset == 0 is faster still, so we preserve that case. + */ + if (cctx->currentOffset != 0 && tableType == byU32) { + DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset"); + cctx->currentOffset += 64 KB; + } + + /* Finally, clear history */ + cctx->dictCtx = NULL; + cctx->dictionary = NULL; + cctx->dictSize = 0; +} + +/** LZ4_compress_generic() : + inlined, to ensure branches are decided at compilation time */ +LZ4_FORCE_INLINE int LZ4_compress_generic( + LZ4_stream_t_internal* const cctx, + const char* const source, + char* const dest, + const int inputSize, + int *inputConsumed, /* only written when outputLimited == fillOutput */ + const int maxOutputSize, + const limitedOutput_directive outputLimited, + const tableType_t tableType, + const dict_directive dictDirective, + const dictIssue_directive dictIssue, + const U32 acceleration) +{ + const BYTE* ip = (const BYTE*) source; + + U32 const startIndex = cctx->currentOffset; + const BYTE* base = (const BYTE*) source - startIndex; + const BYTE* lowLimit; + + const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx; + const BYTE* const dictionary = + dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary; + const U32 dictSize = + dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize; + const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0; /* make indexes in dictCtx comparable with index in current context */ + + int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx); + U32 const prefixIdxLimit = startIndex - dictSize; /* used when dictDirective == dictSmall */ + const BYTE* const dictEnd = dictionary + dictSize; + const BYTE* anchor = (const BYTE*) source; + const BYTE* const iend = ip + inputSize; + const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1; + const BYTE* const matchlimit = iend - LASTLITERALS; + + /* the dictCtx currentOffset is indexed on the start of the dictionary, + * while a dictionary in the current context precedes the currentOffset */ + const BYTE* dictBase = (dictDirective == usingDictCtx) ? + dictionary + dictSize - dictCtx->currentOffset : + dictionary + dictSize - startIndex; + + BYTE* op = (BYTE*) dest; + BYTE* const olimit = op + maxOutputSize; + + U32 offset = 0; + U32 forwardH; + + DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, tableType=%u", inputSize, tableType); + /* Init conditions */ + if (outputLimited == fillOutput && maxOutputSize < 1) return 0; /* Impossible to store anything */ + if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */ + if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ + if (tableType==byPtr) assert(dictDirective==noDict); /* only supported use case with byPtr */ + assert(acceleration >= 1); + + lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0); + + /* Update context state */ + if (dictDirective == usingDictCtx) { + /* Subsequent linked blocks can't use the dictionary. */ + /* Instead, they use the block we just deCompressBuffer. */ + cctx->dictCtx = NULL; + cctx->dictSize = (U32)inputSize; + } else { + cctx->dictSize += (U32)inputSize; + } + cctx->currentOffset += (U32)inputSize; + cctx->tableType = (U16)tableType; + + if (inputSizehashTable, tableType, base); + ip++; forwardH = LZ4_hashPosition(ip, tableType); + + /* Main Loop */ + for ( ; ; ) { + const BYTE* match; + BYTE* token; + + /* Find a match */ + if (tableType == byPtr) { + const BYTE* forwardIp = ip; + unsigned step = 1; + unsigned searchMatchNb = acceleration << LZ4_skipTrigger; + do { + U32 const h = forwardH; + ip = forwardIp; + forwardIp += step; + step = (searchMatchNb++ >> LZ4_skipTrigger); + + if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; + assert(ip < mflimitPlusOne); + + match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base); + forwardH = LZ4_hashPosition(forwardIp, tableType); + LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base); + + } while ( (match+MAX_DISTANCE < ip) + || (LZ4_read32(match) != LZ4_read32(ip)) ); + + } else { /* byU32, byU16 */ + + const BYTE* forwardIp = ip; + unsigned step = 1; + unsigned searchMatchNb = acceleration << LZ4_skipTrigger; + do { + U32 const h = forwardH; + U32 const current = (U32)(forwardIp - base); + U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); + assert(matchIndex <= current); + assert(forwardIp - base < (ptrdiff_t)(2 GB - 1)); + ip = forwardIp; + forwardIp += step; + step = (searchMatchNb++ >> LZ4_skipTrigger); + + if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; + assert(ip < mflimitPlusOne); + + if (dictDirective == usingDictCtx) { + if (matchIndex < startIndex) { + /* there was no match, try the dictionary */ + assert(tableType == byU32); + matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32); + match = dictBase + matchIndex; + matchIndex += dictDelta; /* make dictCtx index comparable with current context */ + lowLimit = dictionary; + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; + } + } else if (dictDirective==usingExtDict) { + if (matchIndex < startIndex) { + DEBUGLOG(7, "extDict candidate: matchIndex=%5u < startIndex=%5u", matchIndex, startIndex); + assert(startIndex - matchIndex >= MINMATCH); + match = dictBase + matchIndex; + lowLimit = dictionary; + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; + } + } else { /* single continuous memory segment */ + match = base + matchIndex; + } + forwardH = LZ4_hashPosition(forwardIp, tableType); + LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); + + if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) continue; /* match outside of valid area */ + assert(matchIndex < current); + if ((tableType != byU16) && (matchIndex+MAX_DISTANCE < current)) continue; /* too far */ + if (tableType == byU16) assert((current - matchIndex) <= MAX_DISTANCE); /* too_far presumed impossible with byU16 */ + + if (LZ4_read32(match) == LZ4_read32(ip)) { + if (maybe_extMem) offset = current - matchIndex; + break; /* match found */ + } + + } while(1); + } + + /* Catch up */ + while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; } + + /* Encode Literals */ + { unsigned const litLength = (unsigned)(ip - anchor); + token = op++; + if ((outputLimited == limitedOutput) && /* Check output buffer overflow */ + (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit))) + return 0; + if ((outputLimited == fillOutput) && + (unlikely(op + (litLength+240)/255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))) { + op--; + goto _last_literals; + } + if (litLength >= RUN_MASK) { + int len = (int)litLength-RUN_MASK; + *token = (RUN_MASK<= 255 ; len-=255) *op++ = 255; + *op++ = (BYTE)len; + } + else *token = (BYTE)(litLength< olimit)) { + /* the match was too close to the end, rewind and go to last literals */ + op = token; + goto _last_literals; + } + + /* Encode Offset */ + if (maybe_extMem) { /* static test */ + DEBUGLOG(6, " with offset=%u (ext if > %i)", offset, (int)(ip - (const BYTE*)source)); + assert(offset <= MAX_DISTANCE && offset > 0); + LZ4_writeLE16(op, (U16)offset); op+=2; + } else { + DEBUGLOG(6, " with offset=%u (same segment)", (U32)(ip - match)); + assert(ip-match <= MAX_DISTANCE); + LZ4_writeLE16(op, (U16)(ip - match)); op+=2; + } + + /* Encode MatchLength */ + { unsigned matchCode; + + if ( (dictDirective==usingExtDict || dictDirective==usingDictCtx) + && (lowLimit==dictionary) /* match within extDict */ ) { + const BYTE* limit = ip + (dictEnd-match); + assert(dictEnd > match); + if (limit > matchlimit) limit = matchlimit; + matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit); + ip += MINMATCH + matchCode; + if (ip==limit) { + unsigned const more = LZ4_count(limit, (const BYTE*)source, matchlimit); + matchCode += more; + ip += more; + } + DEBUGLOG(6, " with matchLength=%u starting in extDict", matchCode+MINMATCH); + } else { + matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit); + ip += MINMATCH + matchCode; + DEBUGLOG(6, " with matchLength=%u", matchCode+MINMATCH); + } + + if ((outputLimited) && /* Check output buffer overflow */ + (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) ) { + if (outputLimited == limitedOutput) + return 0; + if (outputLimited == fillOutput) { + /* Match description too long : reduce it */ + U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 2 - 1 - LASTLITERALS) * 255; + ip -= matchCode - newMatchCode; + matchCode = newMatchCode; + } + } + if (matchCode >= ML_MASK) { + *token += ML_MASK; + matchCode -= ML_MASK; + LZ4_write32(op, 0xFFFFFFFF); + while (matchCode >= 4*255) { + op+=4; + LZ4_write32(op, 0xFFFFFFFF); + matchCode -= 4*255; + } + op += matchCode / 255; + *op++ = (BYTE)(matchCode % 255); + } else + *token += (BYTE)(matchCode); + } + + anchor = ip; + + /* Test end of chunk */ + if (ip >= mflimitPlusOne) break; + + /* Fill table */ + LZ4_putPosition(ip-2, cctx->hashTable, tableType, base); + + /* Test next position */ + if (tableType == byPtr) { + + match = LZ4_getPosition(ip, cctx->hashTable, tableType, base); + LZ4_putPosition(ip, cctx->hashTable, tableType, base); + if ( (match+MAX_DISTANCE >= ip) + && (LZ4_read32(match) == LZ4_read32(ip)) ) + { token=op++; *token=0; goto _next_match; } + + } else { /* byU32, byU16 */ + + U32 const h = LZ4_hashPosition(ip, tableType); + U32 const current = (U32)(ip-base); + U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); + assert(matchIndex < current); + if (dictDirective == usingDictCtx) { + if (matchIndex < startIndex) { + /* there was no match, try the dictionary */ + matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32); + match = dictBase + matchIndex; + lowLimit = dictionary; /* required for match length counter */ + matchIndex += dictDelta; + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; /* required for match length counter */ + } + } else if (dictDirective==usingExtDict) { + if (matchIndex < startIndex) { + match = dictBase + matchIndex; + lowLimit = dictionary; /* required for match length counter */ + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; /* required for match length counter */ + } + } else { /* single memory segment */ + match = base + matchIndex; + } + LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); + assert(matchIndex < current); + if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1) + && ((tableType==byU16) ? 1 : (matchIndex+MAX_DISTANCE >= current)) + && (LZ4_read32(match) == LZ4_read32(ip)) ) { + token=op++; + *token=0; + if (maybe_extMem) offset = current - matchIndex; + DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i", + (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source)); + goto _next_match; + } + } + + /* Prepare next loop */ + forwardH = LZ4_hashPosition(++ip, tableType); + + } + +_last_literals: + /* Encode Last Literals */ + { size_t lastRun = (size_t)(iend - anchor); + if ( (outputLimited) && /* Check output buffer overflow */ + (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) { + if (outputLimited == fillOutput) { + /* adapt lastRun to fill 'dst' */ + lastRun = (olimit-op) - 1; + lastRun -= (lastRun+240)/255; + } + if (outputLimited == limitedOutput) + return 0; + } + if (lastRun >= RUN_MASK) { + size_t accumulator = lastRun - RUN_MASK; + *op++ = RUN_MASK << ML_BITS; + for(; accumulator >= 255 ; accumulator-=255) *op++ = 255; + *op++ = (BYTE) accumulator; + } else { + *op++ = (BYTE)(lastRun<internal_donotuse; + if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; + LZ4_resetStream((LZ4_stream_t*)state); + if (maxOutputSize >= LZ4_compressBound(inputSize)) { + if (inputSize < LZ4_64Klimit) { + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration); + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > MAX_DISTANCE)) ? byPtr : byU32; + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); + } + } else { + if (inputSize < LZ4_64Klimit) {; + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > MAX_DISTANCE)) ? byPtr : byU32; + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration); + } + } +} + +/** + * LZ4_compress_fast_extState_fastReset() : + * A variant of LZ4_compress_fast_extState(). + * + * Using this variant avoids an expensive initialization step. It is only safe + * to call if the state buffer is known to be correctly initialized already + * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of + * "correctly initialized"). + */ +int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration) +{ + LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse; + if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; + + if (dstCapacity >= LZ4_compressBound(srcSize)) { + if (srcSize < LZ4_64Klimit) { + const tableType_t tableType = byU16; + LZ4_prepareTable(ctx, srcSize, tableType); + if (ctx->currentOffset) { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration); + } else { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); + } + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32; + LZ4_prepareTable(ctx, srcSize, tableType); + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); + } + } else { + if (srcSize < LZ4_64Klimit) { + const tableType_t tableType = byU16; + LZ4_prepareTable(ctx, srcSize, tableType); + if (ctx->currentOffset) { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration); + } else { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); + } + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32; + LZ4_prepareTable(ctx, srcSize, tableType); + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); + } + } +} + + +int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) +{ + int result; +#if (LZ4_HEAPMODE) + LZ4_stream_t* ctxPtr = ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ + if (ctxPtr == NULL) return 0; +#else + LZ4_stream_t ctx; + LZ4_stream_t* const ctxPtr = &ctx; +#endif + result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration); + +#if (LZ4_HEAPMODE) + FREEMEM(ctxPtr); +#endif + return result; +} + + +int LZ4_compress_default(const char* source, char* dest, int inputSize, int maxOutputSize) +{ + return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, 1); +} + + +/* hidden debug function */ +/* strangely enough, gcc generates faster code when this function is uncommented, even if unused */ +int LZ4_compress_fast_force(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) +{ + LZ4_stream_t ctx; + LZ4_resetStream(&ctx); + + if (inputSize < LZ4_64Klimit) + return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); + else + return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, sizeof(void*)==8 ? byU32 : byPtr, noDict, noDictIssue, acceleration); +} + + +/* Note!: This function leaves the stream in an unclean/broken state! + * It is not safe to subsequently use the same state with a _fastReset() or + * _continue() call without resetting it. */ +static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize) +{ + LZ4_resetStream(state); + + if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) { /* compression success is guaranteed */ + return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1); + } else { + if (*srcSizePtr < LZ4_64Klimit) { + return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1); + } else { + tableType_t const tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32; + return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, tableType, noDict, noDictIssue, 1); + } } +} + + +int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize) +{ +#if (LZ4_HEAPMODE) + LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ + if (ctx == NULL) return 0; +#else + LZ4_stream_t ctxBody; + LZ4_stream_t* ctx = &ctxBody; +#endif + + int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize); + +#if (LZ4_HEAPMODE) + FREEMEM(ctx); +#endif + return result; +} + + + +/*-****************************** +* Streaming functions +********************************/ + +LZ4_stream_t* LZ4_createStream(void) +{ + LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); + LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */ + DEBUGLOG(4, "LZ4_createStream %p", lz4s); + if (lz4s == NULL) return NULL; + LZ4_resetStream(lz4s); + return lz4s; +} + +void LZ4_resetStream (LZ4_stream_t* LZ4_stream) +{ + DEBUGLOG(5, "LZ4_resetStream (ctx:%p)", LZ4_stream); + MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t)); +} + +void LZ4_resetStream_fast(LZ4_stream_t* ctx) { + LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32); +} + +int LZ4_freeStream (LZ4_stream_t* LZ4_stream) +{ + if (!LZ4_stream) return 0; /* support free on NULL */ + DEBUGLOG(5, "LZ4_freeStream %p", LZ4_stream); + FREEMEM(LZ4_stream); + return (0); +} + + +#define HASH_UNIT sizeof(reg_t) +int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize) +{ + LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse; + const tableType_t tableType = byU32; + const BYTE* p = (const BYTE*)dictionary; + const BYTE* const dictEnd = p + dictSize; + const BYTE* base; + + DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict); + + /* It's necessary to reset the context, + * and not just continue it with prepareTable() + * to avoid any risk of generating overflowing matchIndex + * when compressing using this dictionary */ + LZ4_resetStream(LZ4_dict); + + /* We always increment the offset by 64 KB, since, if the dict is longer, + * we truncate it to the last 64k, and if it's shorter, we still want to + * advance by a whole window length so we can provide the guarantee that + * there are only valid offsets in the window, which allows an optimization + * in LZ4_compress_fast_continue() where it uses noDictIssue even when the + * dictionary isn't a full 64k. */ + + if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB; + base = dictEnd - 64 KB - dict->currentOffset; + dict->dictionary = p; + dict->dictSize = (U32)(dictEnd - p); + dict->currentOffset += 64 KB; + dict->tableType = tableType; + + if (dictSize < (int)HASH_UNIT) { + return 0; + } + + while (p <= dictEnd-HASH_UNIT) { + LZ4_putPosition(p, dict->hashTable, tableType, base); + p+=3; + } + + return dict->dictSize; +} + +void LZ4_attach_dictionary(LZ4_stream_t *working_stream, const LZ4_stream_t *dictionary_stream) { + if (dictionary_stream != NULL) { + /* If the current offset is zero, we will never look in the + * external dictionary context, since there is no value a table + * entry can take that indicate a miss. In that case, we need + * to bump the offset to something non-zero. + */ + if (working_stream->internal_donotuse.currentOffset == 0) { + working_stream->internal_donotuse.currentOffset = 64 KB; + } + working_stream->internal_donotuse.dictCtx = &(dictionary_stream->internal_donotuse); + } else { + working_stream->internal_donotuse.dictCtx = NULL; + } +} + + +static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, int nextSize) +{ + if (LZ4_dict->currentOffset + nextSize > 0x80000000) { /* potential ptrdiff_t overflow (32-bits mode) */ + /* rescale hash table */ + U32 const delta = LZ4_dict->currentOffset - 64 KB; + const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize; + int i; + DEBUGLOG(4, "LZ4_renormDictT"); + for (i=0; ihashTable[i] < delta) LZ4_dict->hashTable[i]=0; + else LZ4_dict->hashTable[i] -= delta; + } + LZ4_dict->currentOffset = 64 KB; + if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB; + LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize; + } +} + + +int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) +{ + const tableType_t tableType = byU32; + LZ4_stream_t_internal* streamPtr = &LZ4_stream->internal_donotuse; + const BYTE* dictEnd = streamPtr->dictionary + streamPtr->dictSize; + + DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i)", inputSize); + + if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */ + LZ4_renormDictT(streamPtr, inputSize); /* avoid index overflow */ + if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; + + /* invalidate tiny dictionaries */ + if ( (streamPtr->dictSize-1 < 4) /* intentional underflow */ + && (dictEnd != (const BYTE*)source) ) { + DEBUGLOG(5, "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", streamPtr->dictSize, streamPtr->dictionary); + streamPtr->dictSize = 0; + streamPtr->dictionary = (const BYTE*)source; + dictEnd = (const BYTE*)source; + } + + /* Check overlapping input/dictionary space */ + { const BYTE* sourceEnd = (const BYTE*) source + inputSize; + if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd)) { + streamPtr->dictSize = (U32)(dictEnd - sourceEnd); + if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB; + if (streamPtr->dictSize < 4) streamPtr->dictSize = 0; + streamPtr->dictionary = dictEnd - streamPtr->dictSize; + } + } + + /* prefix mode : source data follows dictionary */ + if (dictEnd == (const BYTE*)source) { + if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) + return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration); + else + return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration); + } + + /* external dictionary mode */ + { int result; + if (streamPtr->dictCtx) { + /* We depend here on the fact that dictCtx'es (produced by + * LZ4_loadDict) guarantee that their tables contain no references + * to offsets between dictCtx->currentOffset - 64 KB and + * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe + * to use noDictIssue even when the dict isn't a full 64 KB. + */ + if (inputSize > 4 KB) { + /* For compressing large blobs, it is faster to pay the setup + * cost to copy the dictionary's tables into the active context, + * so that the compression loop is only looking into one table. + */ + memcpy(streamPtr, streamPtr->dictCtx, sizeof(LZ4_stream_t)); + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration); + } + } else { + if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); + } + } + streamPtr->dictionary = (const BYTE*)source; + streamPtr->dictSize = (U32)inputSize; + return result; + } +} + + +/* Hidden debug function, to force-test external dictionary mode */ +int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize) +{ + LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse; + int result; + + LZ4_renormDictT(streamPtr, srcSize); + + if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { + result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1); + } + + streamPtr->dictionary = (const BYTE*)source; + streamPtr->dictSize = (U32)srcSize; + + return result; +} + + +/*! LZ4_saveDict() : + * If previously deCompressBuffer data block is not guaranteed to remain available at its memory location, + * save it into a safer place (char* safeBuffer). + * Note : you don't need to call LZ4_loadDict() afterwards, + * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue(). + * Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error. + */ +int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize) +{ + LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse; + const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize; + + if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */ + if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize; + + memmove(safeBuffer, previousDictEnd - dictSize, dictSize); + + dict->dictionary = (const BYTE*)safeBuffer; + dict->dictSize = (U32)dictSize; + + return dictSize; +} + + + +/*-******************************* + * Decompression functions + ********************************/ + +typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; +typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive; + +#undef MIN +#define MIN(a,b) ( (a) < (b) ? (a) : (b) ) + +/*! LZ4_decompress_generic() : + * This generic decompression function covers all use cases. + * It shall be instantiated several times, using different sets of directives. + * Note that it is important for performance that this function really get inlined, + * in order to remove useless branches during compilation optimization. + */ +LZ4_FORCE_INLINE int +LZ4_decompress_generic( + const char* const src, + char* const dst, + int srcSize, + int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */ + + endCondition_directive endOnInput, /* endOnOutputSize, endOnInputSize */ + earlyEnd_directive partialDecoding, /* full, partial */ + dict_directive dict, /* noDict, withPrefix64k, usingExtDict */ + const BYTE* const lowPrefix, /* always <= dst, == dst when no prefix */ + const BYTE* const dictStart, /* only if dict==usingExtDict */ + const size_t dictSize /* note : = 0 if noDict */ + ) +{ + if (src == NULL) return -1; + + { const BYTE* ip = (const BYTE*) src; + const BYTE* const iend = ip + srcSize; + + BYTE* op = (BYTE*) dst; + BYTE* const oend = op + outputSize; + BYTE* cpy; + + const BYTE* const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize; + const unsigned inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4}; + const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3}; + + const int safeDecode = (endOnInput==endOnInputSize); + const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB))); + + /* Set up the "end" pointers for the shortcut. */ + const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/; + const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/; + + DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize); + + /* Special cases */ + assert(lowPrefix <= op); + if ((endOnInput) && (unlikely(outputSize==0))) return ((srcSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */ + if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0 ? 1 : -1); + if ((endOnInput) && unlikely(srcSize==0)) return -1; + + /* Main Loop : decode sequences */ + while (1) { + const BYTE* match; + size_t offset; + + unsigned const token = *ip++; + size_t length = token >> ML_BITS; /* literal length */ + + assert(!endOnInput || ip <= iend); /* ip < iend before the increment */ + + /* A two-stage shortcut for the most common case: + * 1) If the literal length is 0..14, and there is enough space, + * enter the shortcut and copy 16 bytes on behalf of the literals + * (in the fast mode, only 8 bytes can be safely copied this way). + * 2) Further if the match length is 4..18, copy 18 bytes in a similar + * manner; but we ensure that there's enough space in the output for + * those 18 bytes earlier, upon entering the shortcut (in other words, + * there is a combined check for both stages). + */ + if ( (endOnInput ? length != RUN_MASK : length <= 8) + /* strictly "less than" on input, to re-enter the loop with at least one byte */ + && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) { + /* Copy the literals */ + memcpy(op, ip, endOnInput ? 16 : 8); + op += length; ip += length; + + /* The second stage: prepare for match copying, decode full info. + * If it doesn't work out, the info won't be wasted. */ + length = token & ML_MASK; /* match length */ + offset = LZ4_readLE16(ip); ip += 2; + match = op - offset; + assert(match <= op); /* check overflow */ + + /* Do not deal with overlapping matches. */ + if ( (length != ML_MASK) + && (offset >= 8) + && (dict==withPrefix64k || match >= lowPrefix) ) { + /* Copy the match. */ + memcpy(op + 0, match + 0, 8); + memcpy(op + 8, match + 8, 8); + memcpy(op +16, match +16, 2); + op += length + MINMATCH; + /* Both stages worked, load the next token. */ + continue; + } + + /* The second stage didn't work out, but the info is ready. + * Propel it right to the point of match copying. */ + goto _copy_match; + } + + /* decode literal length */ + if (length == RUN_MASK) { + unsigned s; + if (unlikely(endOnInput ? ip >= iend-RUN_MASK : 0)) goto _output_error; /* overflow detection */ + do { + s = *ip++; + length += s; + } while ( likely(endOnInput ? ip= WILDCOPYLENGTH); + if ( ((endOnInput) && ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) ) + || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) ) + { + if (partialDecoding) { + if (cpy > oend) { cpy = oend; length = oend-op; } /* Partial decoding : stop in the middle of literal segment */ + if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */ + } else { + if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */ + if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */ + } + memcpy(op, ip, length); + ip += length; + op += length; + if (!partialDecoding || (cpy == oend)) { + /* Necessarily EOF, due to parsing restrictions */ + break; + } + + } else { + LZ4_wildCopy(op, ip, cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */ + ip += length; op = cpy; + } + + /* get offset */ + offset = LZ4_readLE16(ip); ip+=2; + match = op - offset; + + /* get matchlength */ + length = token & ML_MASK; + + _copy_match: + if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */ + if (!partialDecoding) { + assert(oend > op); + assert(oend - op >= 4); + LZ4_write32(op, 0); /* silence an msan warning when offset==0; costs <1%; */ + } /* note : when partialDecoding, there is no guarantee that at least 4 bytes remain available in output buffer */ + + if (length == ML_MASK) { + unsigned s; + do { + s = *ip++; + if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error; + length += s; + } while (s==255); + if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */ + } + length += MINMATCH; + + /* match starting within external dictionary */ + if ((dict==usingExtDict) && (match < lowPrefix)) { + if (unlikely(op+length > oend-LASTLITERALS)) { + if (partialDecoding) length = MIN(length, (size_t)(oend-op)); + else goto _output_error; /* doesn't respect parsing restriction */ + } + + if (length <= (size_t)(lowPrefix-match)) { + /* match fits entirely within external dictionary : just copy */ + memmove(op, dictEnd - (lowPrefix-match), length); + op += length; + } else { + /* match stretches into both external dictionary and current block */ + size_t const copySize = (size_t)(lowPrefix - match); + size_t const restSize = length - copySize; + memcpy(op, dictEnd - copySize, copySize); + op += copySize; + if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */ + BYTE* const endOfMatch = op + restSize; + const BYTE* copyFrom = lowPrefix; + while (op < endOfMatch) *op++ = *copyFrom++; + } else { + memcpy(op, lowPrefix, restSize); + op += restSize; + } } + continue; + } + + /* copy match within block */ + cpy = op + length; + + /* partialDecoding : may not respect endBlock parsing restrictions */ + assert(op<=oend); + if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { + size_t const mlen = MIN(length, (size_t)(oend-op)); + const BYTE* const matchEnd = match + mlen; + BYTE* const copyEnd = op + mlen; + if (matchEnd > op) { /* overlap copy */ + while (op < copyEnd) *op++ = *match++; + } else { + memcpy(op, match, mlen); + } + op = copyEnd; + if (op==oend) break; + continue; + } + + if (unlikely(offset<8)) { + op[0] = match[0]; + op[1] = match[1]; + op[2] = match[2]; + op[3] = match[3]; + match += inc32table[offset]; + memcpy(op+4, match, 4); + match -= dec64table[offset]; + } else { + memcpy(op, match, 8); + match += 8; + } + op += 8; + + if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { + BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1); + if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (undeCompressBuffer) */ + if (op < oCopyLimit) { + LZ4_wildCopy(op, match, oCopyLimit); + match += oCopyLimit - op; + op = oCopyLimit; + } + while (op < cpy) *op++ = *match++; + } else { + memcpy(op, match, 8); + if (length > 16) LZ4_wildCopy(op+8, match+8, cpy); + } + op = cpy; /* wildcopy correction */ + } + + /* end of decoding */ + if (endOnInput) + return (int) (((char*)op)-dst); /* Nb of output bytes decoded */ + else + return (int) (((const char*)ip)-src); /* Nb of input bytes read */ + + /* Overflow error detected */ + _output_error: + return (int) (-(((const char*)ip)-src))-1; + } +} + + +/*===== Instantiate the API decoding functions. =====*/ + +LZ4_FORCE_O2_GCC_PPC64LE +int LZ4_decompress_safe(const char* source, char* dest, int deCompressBufferSize, int maxDedeCompressBufferSize) +{ + return LZ4_decompress_generic(source, dest, deCompressBufferSize, maxDedeCompressBufferSize, + endOnInputSize, decode_full_block, noDict, + (BYTE*)dest, NULL, 0); +} + +LZ4_FORCE_O2_GCC_PPC64LE +int LZ4_decompress_safe_partial(const char* src, char* dst, int deCompressBufferSize, int targetOutputSize, int dstCapacity) +{ + dstCapacity = MIN(targetOutputSize, dstCapacity); + return LZ4_decompress_generic(src, dst, deCompressBufferSize, dstCapacity, + endOnInputSize, partial_decode, + noDict, (BYTE*)dst, NULL, 0); +} + +LZ4_FORCE_O2_GCC_PPC64LE +int LZ4_decompress_fast(const char* source, char* dest, int originalSize) +{ + return LZ4_decompress_generic(source, dest, 0, originalSize, + endOnOutputSize, decode_full_block, withPrefix64k, + (BYTE*)dest - 64 KB, NULL, 0); +} + +/*===== Instantiate a few more decoding cases, used more than once. =====*/ + +LZ4_FORCE_O2_GCC_PPC64LE /* Exported, an obsolete API function. */ +int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int deCompressBufferSize, int maxOutputSize) +{ + return LZ4_decompress_generic(source, dest, deCompressBufferSize, maxOutputSize, + endOnInputSize, decode_full_block, withPrefix64k, + (BYTE*)dest - 64 KB, NULL, 0); +} + +/* Another obsolete API function, paired with the previous one. */ +int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize) +{ + /* LZ4_decompress_fast doesn't validate match offsets, + * and thus serves well with any prefixed dictionary. */ + return LZ4_decompress_fast(source, dest, originalSize); +} + +LZ4_FORCE_O2_GCC_PPC64LE +static int LZ4_decompress_safe_withSmallPrefix(const char* source, char* dest, int deCompressBufferSize, int maxOutputSize, + size_t prefixSize) +{ + return LZ4_decompress_generic(source, dest, deCompressBufferSize, maxOutputSize, + endOnInputSize, decode_full_block, noDict, + (BYTE*)dest-prefixSize, NULL, 0); +} + +LZ4_FORCE_O2_GCC_PPC64LE +int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, + int deCompressBufferSize, int maxOutputSize, + const void* dictStart, size_t dictSize) +{ + return LZ4_decompress_generic(source, dest, deCompressBufferSize, maxOutputSize, + endOnInputSize, decode_full_block, usingExtDict, + (BYTE*)dest, (const BYTE*)dictStart, dictSize); +} + +LZ4_FORCE_O2_GCC_PPC64LE +static int LZ4_decompress_fast_extDict(const char* source, char* dest, int originalSize, + const void* dictStart, size_t dictSize) +{ + return LZ4_decompress_generic(source, dest, 0, originalSize, + endOnOutputSize, decode_full_block, usingExtDict, + (BYTE*)dest, (const BYTE*)dictStart, dictSize); +} + +/* The "double dictionary" mode, for use with e.g. ring buffers: the first part + * of the dictionary is passed as prefix, and the second via dictStart + dictSize. + * These routines are used only once, in LZ4_decompress_*_continue(). + */ +LZ4_FORCE_INLINE +int LZ4_decompress_safe_doubleDict(const char* source, char* dest, int deCompressBufferSize, int maxOutputSize, + size_t prefixSize, const void* dictStart, size_t dictSize) +{ + return LZ4_decompress_generic(source, dest, deCompressBufferSize, maxOutputSize, + endOnInputSize, decode_full_block, usingExtDict, + (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize); +} + +LZ4_FORCE_INLINE +int LZ4_decompress_fast_doubleDict(const char* source, char* dest, int originalSize, + size_t prefixSize, const void* dictStart, size_t dictSize) +{ + return LZ4_decompress_generic(source, dest, 0, originalSize, + endOnOutputSize, decode_full_block, usingExtDict, + (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize); +} + +/*===== streaming decompression functions =====*/ + +LZ4_streamDecode_t* LZ4_createStreamDecode(void) +{ + LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t)); + return lz4s; +} + +int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream) +{ + if (!LZ4_stream) return 0; /* support free on NULL */ + FREEMEM(LZ4_stream); + return 0; +} + +/*! LZ4_setStreamDecode() : + * Use this function to instruct where to find the dictionary. + * This function is not necessary if previous data is still available where it was decoded. + * Loading a size of 0 is allowed (same effect as no dictionary). + * @return : 1 if OK, 0 if error + */ +int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize) +{ + LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; + lz4sd->prefixSize = (size_t) dictSize; + lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize; + lz4sd->externalDict = NULL; + lz4sd->extDictSize = 0; + return 1; +} + +/*! LZ4_decoderRingBufferSize() : + * when setting a ring buffer for streaming decompression (optional scenario), + * provides the minimum size of this ring buffer + * to be compatible with any source respecting maxBlockSize condition. + * Note : in a ring buffer scenario, + * blocks are presumed dedeCompressBuffer next to each other. + * When not enough space remains for next block (remainingSize < maxBlockSize), + * decoding resumes from beginning of ring buffer. + * @return : minimum ring buffer size, + * or 0 if there is an error (invalid maxBlockSize). + */ +int LZ4_decoderRingBufferSize(int maxBlockSize) +{ + if (maxBlockSize < 0) return 0; + if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0; + if (maxBlockSize < 16) maxBlockSize = 16; + return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize); +} + +/* +*_continue() : + These decoding functions allow decompression of multiple blocks in "streaming" mode. + Previously decoded blocks must still be available at the memory position where they were decoded. + If it's not possible, save the relevant part of decoded data into a safe buffer, + and indicate where it stands using LZ4_setStreamDecode() +*/ +LZ4_FORCE_O2_GCC_PPC64LE +int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int deCompressBufferSize, int maxOutputSize) +{ + LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; + int result; + + if (lz4sd->prefixSize == 0) { + /* The first call, no dictionary yet. */ + assert(lz4sd->extDictSize == 0); + result = LZ4_decompress_safe(source, dest, deCompressBufferSize, maxOutputSize); + if (result <= 0) return result; + lz4sd->prefixSize = result; + lz4sd->prefixEnd = (BYTE*)dest + result; + } else if (lz4sd->prefixEnd == (BYTE*)dest) { + /* They're rolling the current segment. */ + if (lz4sd->prefixSize >= 64 KB - 1) + result = LZ4_decompress_safe_withPrefix64k(source, dest, deCompressBufferSize, maxOutputSize); + else if (lz4sd->extDictSize == 0) + result = LZ4_decompress_safe_withSmallPrefix(source, dest, deCompressBufferSize, maxOutputSize, + lz4sd->prefixSize); + else + result = LZ4_decompress_safe_doubleDict(source, dest, deCompressBufferSize, maxOutputSize, + lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); + if (result <= 0) return result; + lz4sd->prefixSize += result; + lz4sd->prefixEnd += result; + } else { + /* The buffer wraps around, or they're switching to another buffer. */ + lz4sd->extDictSize = lz4sd->prefixSize; + lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; + result = LZ4_decompress_safe_forceExtDict(source, dest, deCompressBufferSize, maxOutputSize, + lz4sd->externalDict, lz4sd->extDictSize); + if (result <= 0) return result; + lz4sd->prefixSize = result; + lz4sd->prefixEnd = (BYTE*)dest + result; + } + + return result; +} + +LZ4_FORCE_O2_GCC_PPC64LE +int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize) +{ + LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; + int result; + + if (lz4sd->prefixSize == 0) { + assert(lz4sd->extDictSize == 0); + result = LZ4_decompress_fast(source, dest, originalSize); + if (result <= 0) return result; + lz4sd->prefixSize = originalSize; + lz4sd->prefixEnd = (BYTE*)dest + originalSize; + } else if (lz4sd->prefixEnd == (BYTE*)dest) { + if (lz4sd->prefixSize >= 64 KB - 1 || lz4sd->extDictSize == 0) + result = LZ4_decompress_fast(source, dest, originalSize); + else + result = LZ4_decompress_fast_doubleDict(source, dest, originalSize, + lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); + if (result <= 0) return result; + lz4sd->prefixSize += originalSize; + lz4sd->prefixEnd += originalSize; + } else { + lz4sd->extDictSize = lz4sd->prefixSize; + lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; + result = LZ4_decompress_fast_extDict(source, dest, originalSize, + lz4sd->externalDict, lz4sd->extDictSize); + if (result <= 0) return result; + lz4sd->prefixSize = originalSize; + lz4sd->prefixEnd = (BYTE*)dest + originalSize; + } + + return result; +} + + +/* +Advanced decoding functions : +*_usingDict() : + These decoding functions work the same as "_continue" ones, + the dictionary must be explicitly provided within parameters +*/ + +int LZ4_decompress_safe_usingDict(const char* source, char* dest, int deCompressBufferSize, int maxOutputSize, const char* dictStart, int dictSize) +{ + if (dictSize==0) + return LZ4_decompress_safe(source, dest, deCompressBufferSize, maxOutputSize); + if (dictStart+dictSize == dest) { + if (dictSize >= 64 KB - 1) + return LZ4_decompress_safe_withPrefix64k(source, dest, deCompressBufferSize, maxOutputSize); + return LZ4_decompress_safe_withSmallPrefix(source, dest, deCompressBufferSize, maxOutputSize, dictSize); + } + return LZ4_decompress_safe_forceExtDict(source, dest, deCompressBufferSize, maxOutputSize, dictStart, dictSize); +} + +int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize) +{ + if (dictSize==0 || dictStart+dictSize == dest) + return LZ4_decompress_fast(source, dest, originalSize); + return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, dictSize); +} + + +/*=************************************************* +* Obsolete Functions +***************************************************/ +/* obsolete compression functions */ +int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) +{ + return LZ4_compress_default(source, dest, inputSize, maxOutputSize); +} +int LZ4_compress(const char* source, char* dest, int inputSize) +{ + return LZ4_compress_default(source, dest, inputSize, LZ4_compressBound(inputSize)); +} +int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) +{ + return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); +} +int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) +{ + return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); +} +int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity) +{ + return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1); +} +int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) +{ + return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); +} + +/* +These decompression functions are deprecated and should no longer be used. +They are only provided here for compatibility with older user programs. +- LZ4_uncompress is totally equivalent to LZ4_decompress_fast +- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe +*/ +int LZ4_uncompress (const char* source, char* dest, int outputSize) +{ + return LZ4_decompress_fast(source, dest, outputSize); +} +int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) +{ + return LZ4_decompress_safe(source, dest, isize, maxOutputSize); +} + +/* Obsolete Streaming functions */ + +int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; } + +int LZ4_resetStreamState(void* state, char* inputBuffer) +{ + (void)inputBuffer; + LZ4_resetStream((LZ4_stream_t*)state); + return 0; +} + +void* LZ4_create (char* inputBuffer) +{ + (void)inputBuffer; + return LZ4_createStream(); +} + +char* LZ4_slideInputBuffer (void* state) +{ + /* avoid const char * -> char * conversion warning */ + return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary; +} + +#endif /* LZ4_COMMONDEFS_ONLY */ diff --git a/bsdiff/lz4.h b/bsdiff/lz4.h new file mode 100755 index 0000000..e873c13 --- /dev/null +++ b/bsdiff/lz4.h @@ -0,0 +1,660 @@ +/* + * LZ4 - Fast LZ compression algorithm + * Header File + * Copyright (C) 2011-present, Yann Collet. + + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + 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 + 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. + + You can contact the author at : + - LZ4 homepage : http://www.lz4.org + - LZ4 source repository : https://github.com/lz4/lz4 + */ +#if defined (__cplusplus) +extern "C" { +#endif + +#ifndef LZ4_H_2983827168210 +#define LZ4_H_2983827168210 + +/* --- Dependency --- */ +#include /* size_t */ + +/** + Introduction + + LZ4 is lossless compression algorithm, providing compression speed at 500 MB/s per core, + scalable with multi-cores CPU. It features an extremely fast decoder, with speed in + multiple GB/s per core, typically reaching RAM speed limits on multi-core systems. + + The LZ4 compression library provides in-memory compression and decompression functions. + Compression can be done in: + - a single step (described as Simple Functions) + - a single step, reusing a context (described in Advanced Functions) + - unbounded multiple steps (described as Streaming compression) + + lz4.h provides block compression functions. It gives full buffer control to user. + Decompressing an lz4-deCompressBuffer block also requires metadata (such as deCompressBuffer size). + Each application is free to encode such metadata in whichever way it wants. + + An additional format, called LZ4 frame specification (doc/lz4_Frame_format.md), + take care of encoding standard metadata alongside LZ4-deCompressBuffer blocks. + Frame format is required for interoperability. + It is delivered through a companion API, declared in lz4frame.h. + */ + +/*^*************************************************************** + * Export parameters + *****************************************************************/ +/* + * LZ4_DLL_EXPORT : + * Enable exporting of functions when building a Windows DLL + * LZ4LIB_VISIBILITY : + * Control library symbols visibility. + */ +#ifndef LZ4LIB_VISIBILITY +# if defined(__GNUC__) && (__GNUC__ >= 4) +# define LZ4LIB_VISIBILITY __attribute__ ((visibility ("default"))) +# else +# define LZ4LIB_VISIBILITY +# endif +#endif +#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1) +# define LZ4LIB_API __declspec(dllexport) LZ4LIB_VISIBILITY +#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1) +# define LZ4LIB_API __declspec(dllimport) LZ4LIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ +#else +# define LZ4LIB_API LZ4LIB_VISIBILITY +#endif + +/*------ Version ------*/ +#define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */ +#define LZ4_VERSION_MINOR 8 /* for new (non-breaking) interface capabilities */ +#define LZ4_VERSION_RELEASE 3 /* for tweaks, bug-fixes, or development */ + +#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE) + +#define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE +#define LZ4_QUOTE(str) #str +#define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str) +#define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION) + +LZ4LIB_API int LZ4_versionNumber(void); /**< library version number; useful to check dll version */ +LZ4LIB_API const char* LZ4_versionString(void); /**< library version string; useful to check dll version */ + +/*-************************************ + * Tuning parameter + **************************************/ +/*! + * LZ4_MEMORY_USAGE : + * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) + * Increasing memory usage improves compression ratio. + * Reduced memory usage may improve speed, thanks to better cache locality. + * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache + */ +#ifndef LZ4_MEMORY_USAGE +# define LZ4_MEMORY_USAGE 14 +#endif + +/*-************************************ + * Simple Functions + **************************************/ +/*! LZ4_compress_default() : + Compresses 'srcSize' bytes from buffer 'src' + into already allocated 'dst' buffer of size 'dstCapacity'. + Compression is guaranteed to succeed if 'dstCapacity' >= LZ4_compressBound(srcSize). + It also runs faster, so it's a recommended setting. + If the function cannot compress 'src' into a more limited 'dst' budget, + compression stops *immediately*, and the function result is zero. + In which case, 'dst' content is undefined (invalid). + srcSize : max supported value is LZ4_MAX_INPUT_SIZE. + dstCapacity : size of buffer 'dst' (which must be already allocated) + @return : the number of bytes written into buffer 'dst' (necessarily <= dstCapacity) + or 0 if compression fails + Note : This function is protected against buffer overflow scenarios (never writes outside 'dst' buffer, nor read outside 'source' buffer). + */ +LZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize, + int dstCapacity); + +/*! LZ4_decompress_safe() : + deCompressBufferSize : is the exact complete size of the deCompressBuffer block. + dstCapacity : is the size of destination buffer, which must be already allocated. + @return : the number of bytes dedeCompressBuffer into destination buffer (necessarily <= dstCapacity) + If destination buffer is not large enough, decoding will stop and output an error code (negative value). + If the source stream is detected malformed, the function will stop decoding and return a negative result. + Note : This function is protected against malicious data packets (never writes outside 'dst' buffer, nor read outside 'source' buffer). + */ +LZ4LIB_API int LZ4_decompress_safe(const char* src, char* dst, + int deCompressBufferSize, int dstCapacity); + +/*-************************************ + * Advanced Functions + **************************************/ +#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ +#define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16) + +/*! LZ4_compressBound() : + Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible) + This function is primarily useful for memory allocation purposes (destination buffer size). + Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example). + Note that LZ4_compress_default() compresses faster when dstCapacity is >= LZ4_compressBound(srcSize) + inputSize : max supported value is LZ4_MAX_INPUT_SIZE + return : maximum output size in a "worst case" scenario + or 0, if input size is incorrect (too large or negative) + */ +LZ4LIB_API int LZ4_compressBound(int inputSize); + +/*! LZ4_compress_fast() : + Same as LZ4_compress_default(), but allows selection of "acceleration" factor. + The larger the acceleration value, the faster the algorithm, but also the lesser the compression. + It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed. + An acceleration value of "1" is the same as regular LZ4_compress_default() + Values <= 0 will be replaced by ACCELERATION_DEFAULT (currently == 1, see lz4.c). + */ +LZ4LIB_API int LZ4_compress_fast(const char* src, char* dst, int srcSize, + int dstCapacity, int acceleration); + +/*! LZ4_compress_fast_extState() : + * Same as LZ4_compress_fast(), using an externally allocated memory space for its state. + * Use LZ4_sizeofState() to know how much memory must be allocated, + * and allocate it on 8-bytes boundaries (using `malloc()` typically). + * Then, provide this buffer as `void* state` to compression function. + */ +LZ4LIB_API int LZ4_sizeofState(void); +LZ4LIB_API int LZ4_compress_fast_extState(void* state, const char* src, + char* dst, int srcSize, int dstCapacity, int acceleration); + +/*! LZ4_compress_destSize() : + * Reverse the logic : compresses as much data as possible from 'src' buffer + * into already allocated buffer 'dst', of size >= 'targetDestSize'. + * This function either compresses the entire 'src' content into 'dst' if it's large enough, + * or fill 'dst' buffer completely with as much data as possible from 'src'. + * note: acceleration parameter is fixed to "default". + * + * *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'. + * New value is necessarily <= input value. + * @return : Nb bytes written into 'dst' (necessarily <= targetDestSize) + * or 0 if compression fails. + */ +LZ4LIB_API int LZ4_compress_destSize(const char* src, char* dst, + int* srcSizePtr, int targetDstSize); + +/*! LZ4_decompress_fast() : **unsafe!** + * This function used to be a bit faster than LZ4_decompress_safe(), + * though situation has changed in recent versions, + * and now `LZ4_decompress_safe()` can be as fast and sometimes faster than `LZ4_decompress_fast()`. + * Moreover, LZ4_decompress_fast() is not protected vs malformed input, as it doesn't perform full validation of deCompressBuffer data. + * As a consequence, this function is no longer recommended, and may be deprecated in future versions. + * It's last remaining specificity is that it can decompress data without knowing its deCompressBuffer size. + * + * originalSize : is the undeCompressBuffer size to regenerate. + * `dst` must be already allocated, its size must be >= 'originalSize' bytes. + * @return : number of bytes read from source buffer (== deCompressBuffer size). + * If the source stream is detected malformed, the function stops decoding and returns a negative result. + * note : This function requires undeCompressBuffer originalSize to be known in advance. + * The function never writes past the output buffer. + * However, since it doesn't know its 'src' size, it may read past the intended input. + * Also, because match offsets are not validated during decoding, + * reads from 'src' may underflow. + * Use this function in trusted environment **only**. + */ +LZ4LIB_API int LZ4_decompress_fast(const char* src, char* dst, + int originalSize); + +/*! LZ4_decompress_safe_partial() : + * Decompress an LZ4 deCompressBuffer block, of size 'srcSize' at position 'src', + * into destination buffer 'dst' of size 'dstCapacity'. + * Up to 'targetOutputSize' bytes will be decoded. + * The function stops decoding on reaching this objective, + * which can boost performance when only the beginning of a block is required. + * + * @return : the number of bytes decoded in `dst` (necessarily <= dstCapacity) + * If source stream is detected malformed, function returns a negative result. + * + * Note : @return can be < targetOutputSize, if deCompressBuffer block contains less data. + * + * Note 2 : this function features 2 parameters, targetOutputSize and dstCapacity, + * and expects targetOutputSize <= dstCapacity. + * It effectively stops decoding on reaching targetOutputSize, + * so dstCapacity is kind of redundant. + * This is because in a previous version of this function, + * decoding operation would not "break" a sequence in the middle. + * As a consequence, there was no guarantee that decoding would stop at exactly targetOutputSize, + * it could write more bytes, though only up to dstCapacity. + * Some "margin" used to be required for this operation to work properly. + * This is no longer necessary. + * The function nonetheless keeps its signature, in an effort to not break API. + */ +LZ4LIB_API int LZ4_decompress_safe_partial(const char* src, char* dst, + int srcSize, int targetOutputSize, int dstCapacity); + +/*-********************************************* + * Streaming Compression Functions + ***********************************************/ +typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */ + +LZ4LIB_API LZ4_stream_t* LZ4_createStream(void); +LZ4LIB_API int LZ4_freeStream(LZ4_stream_t* streamPtr); + +/*! LZ4_resetStream() : + * An LZ4_stream_t structure can be allocated once and re-used multiple times. + * Use this function to start compressing a new stream. + */ +LZ4LIB_API void LZ4_resetStream(LZ4_stream_t* streamPtr); + +/*! LZ4_loadDict() : + * Use this function to load a static dictionary into LZ4_stream_t. + * Any previous data will be forgotten, only 'dictionary' will remain in memory. + * Loading a size of 0 is allowed, and is the same as reset. + * @return : dictionary size, in bytes (necessarily <= 64 KB) + */ +LZ4LIB_API int LZ4_loadDict(LZ4_stream_t* streamPtr, const char* dictionary, + int dictSize); + +/*! LZ4_compress_fast_continue() : + * Compress 'src' content using data from previously deCompressBuffer blocks, for better compression ratio. + * 'dst' buffer must be already allocated. + * If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster. + * + * @return : size of deCompressBuffer block + * or 0 if there is an error (typically, cannot fit into 'dst'). + * + * Note 1 : Each invocation to LZ4_compress_fast_continue() generates a new block. + * Each block has precise boundaries. + * Each block must be dedeCompressBuffer separately, calling LZ4_decompress_*() with relevant metadata. + * It's not possible to append blocks together and expect a single invocation of LZ4_decompress_*() to decompress them together. + * + * Note 2 : The previous 64KB of source data is __assumed__ to remain present, unmodified, at same address in memory ! + * + * Note 3 : When input is structured as a double-buffer, each buffer can have any size, including < 64 KB. + * Make sure that buffers are separated, by at least one byte. + * This construction ensures that each block only depends on previous block. + * + * Note 4 : If input buffer is a ring-buffer, it can have any size, including < 64 KB. + * + * Note 5 : After an error, the stream status is undefined (invalid), it can only be reset or freed. + */ +LZ4LIB_API int LZ4_compress_fast_continue(LZ4_stream_t* streamPtr, + const char* src, char* dst, int srcSize, int dstCapacity, + int acceleration); + +/*! LZ4_saveDict() : + * If last 64KB data cannot be guaranteed to remain available at its current memory location, + * save it into a safer place (char* safeBuffer). + * This is schematically equivalent to a memcpy() followed by LZ4_loadDict(), + * but is much faster, because LZ4_saveDict() doesn't need to rebuild tables. + * @return : saved dictionary size in bytes (necessarily <= maxDictSize), or 0 if error. + */ +LZ4LIB_API int LZ4_saveDict(LZ4_stream_t* streamPtr, char* safeBuffer, + int maxDictSize); + +/*-********************************************** + * Streaming Decompression Functions + * Bufferless synchronous API + ************************************************/ +typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* tracking context */ + +/*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() : + * creation / destruction of streaming decompression tracking context. + * A tracking context can be re-used multiple times. + */ +LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void); +LZ4LIB_API int LZ4_freeStreamDecode(LZ4_streamDecode_t* LZ4_stream); + +/*! LZ4_setStreamDecode() : + * An LZ4_streamDecode_t context can be allocated once and re-used multiple times. + * Use this function to start decompression of a new stream of blocks. + * A dictionary can optionally be set. Use NULL or size 0 for a reset order. + * Dictionary is presumed stable : it must remain accessible and unmodified during next decompression. + * @return : 1 if OK, 0 if error + */ +LZ4LIB_API int LZ4_setStreamDecode(LZ4_streamDecode_t* LZ4_streamDecode, + const char* dictionary, int dictSize); + +/*! LZ4_decoderRingBufferSize() : v1.8.2+ + * Note : in a ring buffer scenario (optional), + * blocks are presumed dedeCompressBuffer next to each other + * up to the moment there is not enough remaining space for next block (remainingSize < maxBlockSize), + * at which stage it resumes from beginning of ring buffer. + * When setting such a ring buffer for streaming decompression, + * provides the minimum size of this ring buffer + * to be compatible with any source respecting maxBlockSize condition. + * @return : minimum ring buffer size, + * or 0 if there is an error (invalid maxBlockSize). + */ +LZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize); +#define LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize) (65536 + 14 + (maxBlockSize)) /* for static allocation; maxBlockSize presumed valid */ + +/*! LZ4_decompress_*_continue() : + * These decoding functions allow decompression of consecutive blocks in "streaming" mode. + * A block is an unsplittable entity, it must be presented entirely to a decompression function. + * Decompression functions only accepts one block at a time. + * The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded. + * If less than 64KB of data has been decoded, all the data must be present. + * + * Special : if decompression side sets a ring buffer, it must respect one of the following conditions : + * - Decompression buffer size is _at least_ LZ4_decoderRingBufferSize(maxBlockSize). + * maxBlockSize is the maximum size of any single block. It can have any value > 16 bytes. + * In which case, encoding and decoding buffers do not need to be synchronized. + * Actually, data can be produced by any source compliant with LZ4 format specification, and respecting maxBlockSize. + * - Synchronized mode : + * Decompression buffer size is _exactly_ the same as compression buffer size, + * and follows exactly same update rule (block boundaries at same positions), + * and decoding function is provided with exact dedeCompressBuffer size of each block (exception for last block of the stream), + * _then_ decoding & encoding ring buffer can have any size, including small ones ( < 64 KB). + * - Decompression buffer is larger than encoding buffer, by a minimum of maxBlockSize more bytes. + * In which case, encoding and decoding buffers do not need to be synchronized, + * and encoding ring buffer can have any size, including small ones ( < 64 KB). + * + * Whenever these conditions are not possible, + * save the last 64KB of decoded data into a safe buffer where it can't be modified during decompression, + * then indicate where this data is saved using LZ4_setStreamDecode(), before decompressing next block. + */ +LZ4LIB_API int LZ4_decompress_safe_continue( + LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, + int srcSize, int dstCapacity); +LZ4LIB_API int LZ4_decompress_fast_continue( + LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, + int originalSize); + +/*! LZ4_decompress_*_usingDict() : + * These decoding functions work the same as + * a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue() + * They are stand-alone, and don't need an LZ4_streamDecode_t structure. + * Dictionary is presumed stable : it must remain accessible and unmodified during decompression. + * Performance tip : Decompression speed can be substantially increased + * when dst == dictStart + dictSize. + */ +LZ4LIB_API int LZ4_decompress_safe_usingDict(const char* src, char* dst, + int srcSize, int dstCapcity, const char* dictStart, int dictSize); +LZ4LIB_API int LZ4_decompress_fast_usingDict(const char* src, char* dst, + int originalSize, const char* dictStart, int dictSize); + +/*^********************************************** + * !!!!!! STATIC LINKING ONLY !!!!!! + ***********************************************/ + +/*-************************************ + * Unstable declarations + ************************************** + * Declarations in this section must be considered unstable. + * Their signatures may change, or may be removed in the future. + * They are therefore only safe to depend on + * when the caller is statically linked against the library. + * To access their declarations, define LZ4_STATIC_LINKING_ONLY. + **************************************/ + +#ifdef LZ4_STATIC_LINKING_ONLY + +/* By default, symbols in this section aren't published into shared/dynamic libraries. + * You can override this behavior and force them to be published + * by defining LZ4_PUBLISH_STATIC_FUNCTIONS. + * Use at your own risk. + */ + +#ifdef LZ4_PUBLISH_STATIC_FUNCTIONS +#define LZ4LIB_STATIC_API LZ4LIB_API +#else +#define LZ4LIB_STATIC_API +#endif + +/*! LZ4_resetStream_fast() : + * Use this, like LZ4_resetStream(), to prepare a context for a new chain of + * calls to a streaming API (e.g., LZ4_compress_fast_continue()). + * + * Note: + * Using this in advance of a non-streaming-compression function is redundant, + * since they all perform their own custom reset internally. + * + * Differences from LZ4_resetStream(): + * When an LZ4_stream_t is known to be in a internally coherent state, + * it can often be prepared for a new compression with almost no work, + * only sometimes falling back to the full, expensive reset + * that is always required when the stream is in an indeterminate state + * (i.e., the reset performed by LZ4_resetStream()). + * + * LZ4_streams are guaranteed to be in a valid state when: + * - returned from LZ4_createStream() + * - reset by LZ4_resetStream() + * - memset(stream, 0, sizeof(LZ4_stream_t)), though this is discouraged + * - the stream was in a valid state and was reset by LZ4_resetStream_fast() + * - the stream was in a valid state and was then used in any compression call + * that returned success + * - the stream was in an indeterminate state and was used in a compression + * call that fully reset the state (e.g., LZ4_compress_fast_extState()) and + * that returned success + * + * When a stream isn't known to be in a valid state, it is not safe to pass to + * any fastReset or streaming function. It must first be cleansed by the full + * LZ4_resetStream(). + */ +LZ4LIB_STATIC_API void LZ4_resetStream_fast (LZ4_stream_t* streamPtr); + +/*! LZ4_compress_fast_extState_fastReset() : + * A variant of LZ4_compress_fast_extState(). + * + * Using this variant avoids an expensive initialization step. + * It is only safe to call if the state buffer is known to be correctly initialized already + * (see above comment on LZ4_resetStream_fast() for a definition of "correctly initialized"). + * From a high level, the difference is that + * this function initializes the provided state with a call to something like LZ4_resetStream_fast() + * while LZ4_compress_fast_extState() starts with a call to LZ4_resetStream(). + */ +LZ4LIB_STATIC_API int LZ4_compress_fast_extState_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); + +/*! LZ4_attach_dictionary() : + * This is an experimental API that allows + * efficient use of a static dictionary many times. + * + * Rather than re-loading the dictionary buffer into a working context before + * each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a + * working LZ4_stream_t, this function introduces a no-copy setup mechanism, + * in which the working stream references the dictionary stream in-place. + * + * Several assumptions are made about the state of the dictionary stream. + * Currently, only streams which have been prepared by LZ4_loadDict() should + * be expected to work. + * + * Alternatively, the provided dictionaryStream may be NULL, + * in which case any existing dictionary stream is unset. + * + * If a dictionary is provided, it replaces any pre-existing stream history. + * The dictionary contents are the only history that can be referenced and + * logically immediately precede the data deCompressBuffer in the first subsequent + * compression call. + * + * The dictionary will only remain attached to the working stream through the + * first compression call, at the end of which it is cleared. The dictionary + * stream (and source buffer) must remain in-place / accessible / unchanged + * through the completion of the first compression call on the stream. + */ +LZ4LIB_STATIC_API void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream); + +#endif + +/*-************************************ + * Private definitions + ************************************** + * Do not use these definitions directly. + * They are only exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`. + * Accessing members will expose code to API and/or ABI break in future versions of the library. + **************************************/ +#define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2) +#define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE) +#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */ + +#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +#include + +typedef struct LZ4_stream_t_internal LZ4_stream_t_internal; +struct LZ4_stream_t_internal { + uint32_t hashTable[LZ4_HASH_SIZE_U32]; + uint32_t currentOffset; + uint16_t initCheck; + uint16_t tableType; + const uint8_t* dictionary; + const LZ4_stream_t_internal* dictCtx; + uint32_t dictSize; +}; + +typedef struct { + const uint8_t* externalDict; + size_t extDictSize; + const uint8_t* prefixEnd; + size_t prefixSize; +} LZ4_streamDecode_t_internal; + +#else + +typedef struct LZ4_stream_t_internal LZ4_stream_t_internal; +struct LZ4_stream_t_internal { + unsigned int hashTable[LZ4_HASH_SIZE_U32]; + unsigned int currentOffset; + unsigned short initCheck; + unsigned short tableType; + const unsigned char* dictionary; + const LZ4_stream_t_internal* dictCtx; + unsigned int dictSize; +}; + +typedef struct { + const unsigned char* externalDict; + size_t extDictSize; + const unsigned char* prefixEnd; + size_t prefixSize; +}LZ4_streamDecode_t_internal; + +#endif + +/*! LZ4_stream_t : + * information structure to track an LZ4 stream. + * init this structure with LZ4_resetStream() before first use. + * note : only use in association with static linking ! + * this definition is not API/ABI safe, + * it may change in a future version ! + */ +#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4) +#define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(unsigned long long)) +union LZ4_stream_u { + unsigned long long table[LZ4_STREAMSIZE_U64]; + LZ4_stream_t_internal internal_donotuse; +}; +/* previously typedef'd to LZ4_stream_t */ + +/*! LZ4_streamDecode_t : + * information structure to track an LZ4 stream during decompression. + * init this structure using LZ4_setStreamDecode() before first use. + * note : only use in association with static linking ! + * this definition is not API/ABI safe, + * and may change in a future version ! + */ +#define LZ4_STREAMDECODESIZE_U64 4 +#define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long)) +union LZ4_streamDecode_u { + unsigned long long table[LZ4_STREAMDECODESIZE_U64]; + LZ4_streamDecode_t_internal internal_donotuse; +}; +/* previously typedef'd to LZ4_streamDecode_t */ + +/*-************************************ + * Obsolete Functions + **************************************/ + +/*! Deprecation warnings + Should deprecation warnings be a problem, + it is generally possible to disable them, + typically with -Wno-deprecated-declarations for gcc + or _CRT_SECURE_NO_WARNINGS in Visual. + Otherwise, it's also possible to define LZ4_DISABLE_DEPRECATE_WARNINGS */ +#ifdef LZ4_DISABLE_DEPRECATE_WARNINGS +# define LZ4_DEPRECATED(message) /* disable deprecation warnings */ +#else +# define LZ4_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ +# define LZ4_DEPRECATED(message) [[deprecated(message)]] +# elif (LZ4_GCC_VERSION >= 405) || defined(__clang__) +# define LZ4_DEPRECATED(message) __attribute__((deprecated(message))) +# elif (LZ4_GCC_VERSION >= 301) +# define LZ4_DEPRECATED(message) __attribute__((deprecated)) +# elif defined(_MSC_VER) +# define LZ4_DEPRECATED(message) __declspec(deprecated(message)) +# else +# pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler") +# define LZ4_DEPRECATED(message) +# endif +#endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */ + +/* Obsolete compression functions */ +LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress( + const char* source, char* dest, int sourceSize); +LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress_limitedOutput( + const char* source, char* dest, int sourceSize, int maxOutputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_withState( + void* state, const char* source, char* dest, int inputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_limitedOutput_withState( + void* state, const char* source, char* dest, int inputSize, + int maxOutputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_continue( + LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, + int inputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_limitedOutput_continue( + LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, + int inputSize, int maxOutputSize); + +/* Obsolete decompression functions */ +LZ4_DEPRECATED("use LZ4_decompress_fast() instead") LZ4LIB_API int LZ4_uncompress( + const char* source, char* dest, int outputSize); +LZ4_DEPRECATED("use LZ4_decompress_safe() instead") LZ4LIB_API int LZ4_uncompress_unknownOutputSize( + const char* source, char* dest, int isize, int maxOutputSize); + +/* Obsolete streaming functions; degraded functionality; do not use! + * + * In order to perform streaming compression, these functions depended on data + * that is no longer tracked in the state. They have been preserved as well as + * possible: using them will still produce a correct output. However, they don't + * actually retain any history between compression calls. The compression ratio + * achieved will therefore be no better than compressing each chunk + * independently. + */ +LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API void* LZ4_create( + char* inputBuffer); +LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API int LZ4_sizeofStreamState( + void); +LZ4_DEPRECATED("Use LZ4_resetStream() instead") LZ4LIB_API int LZ4_resetStreamState( + void* state, char* inputBuffer); +LZ4_DEPRECATED("Use LZ4_saveDict() instead") LZ4LIB_API char* LZ4_slideInputBuffer( + void* state); + +/* Obsolete streaming decoding functions */ +LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") LZ4LIB_API int LZ4_decompress_safe_withPrefix64k( + const char* src, char* dst, int deCompressBufferSize, int maxDstSize); +LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k( + const char* src, char* dst, int originalSize); + +#endif /* LZ4_H_2983827168210 */ + +#if defined (__cplusplus) +} +#endif diff --git a/bsdiff/varint.c b/bsdiff/varint.c new file mode 100644 index 0000000..fb80b0f --- /dev/null +++ b/bsdiff/varint.c @@ -0,0 +1,152 @@ +/*- + * Copyright (c) 2018-2019 ARM Limited + * All rights reserved + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted providing that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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 AUTHOR ``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 AUTHOR 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. + */ + +#include +#include +#include + +const unsigned char TOP_BIT_ON_BYTE = (128); +const unsigned char TOP_BIT_OFF_BYTE = (127); + +// return 0 if decode completed otherwise 1 negative on error +var_int_op_code decode_unsigned_varint(unsigned char varIntByte, uint64_t* varIntValue, int count) +{ + var_int_op_code returnValue = OPERATION_COMPLETED; + + if (count > 9 || varIntValue == 0) { + return ERR_PARAMETTERS; + } + + if (count == 0) { + *varIntValue = 0; + } + + int hasMore = varIntByte & TOP_BIT_ON_BYTE; + varIntByte &= TOP_BIT_OFF_BYTE; + + uint64_t byteAs64int = varIntByte; + + for (int i = 0; i < count; i++) { + byteAs64int <<= 7; + } + *varIntValue |= byteAs64int; + + if (hasMore) { + returnValue = OPERATION_NEEDS_MORE_DATA; + } else { + returnValue = OPERATION_COMPLETED; + } + + return returnValue; +} + +int encode_unsigned_varint(uint64_t value, unsigned char *buf, uint32_t BUFF_SIZE_MAX) +{ + unsigned int pos = 0; + do { + if (pos >= BUFF_SIZE_MAX) { + return ERR_BUFFER_TOO_SMALL; // protecting buf from overwrite + } + buf[pos] = (unsigned char) value; + value >>= 7; + if (value > 0) { + buf[pos] |= TOP_BIT_ON_BYTE; + } else { + buf[pos] &= TOP_BIT_OFF_BYTE; + } + pos++; + } while (value > 0); + + return pos; +} + +int encode_signed_varint(int64_t value, unsigned char *buf, uint32_t BUFF_SIZE_MAX) +{ + unsigned int pos = 0; + + if (value < 0) { + value = value * -1; // change value to positive number. + value <<= 1; + value |= 1; // set lowest bit 1 if it was negative; + } else { + value <<= 1; // lower bit set to 0 if not negative. + } + + do { + if (pos >= BUFF_SIZE_MAX) { + return ERR_BUFFER_TOO_SMALL; // protecting buf from overwrite + } + buf[pos] = (unsigned char) value; + value >>= 7; + if (value > 0) { + buf[pos] |= TOP_BIT_ON_BYTE; + } else { + buf[pos] &= TOP_BIT_OFF_BYTE; + } + pos++; + } while (value > 0); + + return pos; +} + +var_int_op_code decode_signed_varint(unsigned char varIntByte, int64_t* varIntValue, int count) +{ + var_int_op_code returnValue = OPERATION_COMPLETED; + + if (count > 9 || varIntValue == 0) { + return ERR_PARAMETTERS; + } + + if (count == 0) { + *varIntValue = 0; + } + + int hasMore = varIntByte & TOP_BIT_ON_BYTE; + varIntByte &= TOP_BIT_OFF_BYTE; + + uint64_t byteAs64int = varIntByte; + + for (int i = 0; i < count; i++) { + byteAs64int <<= 7; + } + *varIntValue |= byteAs64int; + + if (hasMore) { + returnValue = OPERATION_NEEDS_MORE_DATA; + } else { + returnValue = OPERATION_COMPLETED; + if (*varIntValue & 1) // this is negative value + { + *varIntValue >>= 1; + *varIntValue = *varIntValue * -1; + } else { + *varIntValue >>= 1; // positive value just eat the lowest bit away. + } + } + + return returnValue; +} + diff --git a/bsdiff/varint.h b/bsdiff/varint.h new file mode 100644 index 0000000..89806e3 --- /dev/null +++ b/bsdiff/varint.h @@ -0,0 +1,40 @@ +// ---------------------------------------------------------------------------- +// Copyright 2019 ARM Ltd. +// +// 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. +// ---------------------------------------------------------------------------- + +#ifndef VARINT_H +#define VARINT_H + +#include + +typedef enum { + ERR_BUFFER_TOO_SMALL = -7, + ERR_PARAMETTERS = -6, + OPERATION_COMPLETED = 0, + OPERATION_NEEDS_MORE_DATA = 1 +}var_int_op_code; + +// decodes varint with multiple calls one byte at a time, returns 1 of more data is needed caller should pass +// number of calls already done int count +var_int_op_code decode_unsigned_varint(unsigned char varIntByte, uint64_t* varIntValue, int count); +var_int_op_code decode_signed_varint(unsigned char varIntByte, int64_t* varIntValue, int count); + +// encodes varint to stream, BUFF_SIZE_MAX should containt maxbytes in buf to avoid overwrites +int encode_unsigned_varint(uint64_t value, unsigned char *buf, uint32_t BUFF_SIZE_MAX); +int encode_signed_varint(int64_t value, unsigned char *buf, uint32_t BUFF_SIZE_MAX); + +#endif diff --git a/changelog.md b/changelog.md new file mode 100644 index 0000000..4799318 --- /dev/null +++ b/changelog.md @@ -0,0 +1,38 @@ +# Changelog + +## 2.0.0 +Works with client-lite. + +Key differences from previous version: + +| | Manifest 1.5.2 | Manifest 2.0.0 | +|:----------------------------------|:---------------------------|:----------------------------------------------------------------------------| +| Supported manifest schema version | `v1` | `v1` and `v3` | +| Delta update | Supported | Supported | +| Component update | Not supported | Supported | +| PDMC | Supported 4.5.0 or earlier | `v1` support covers PDMC, `v3` support is only available on Client Lite | +| Client Lite | Supported | Supports both `v1` (by default) and `v3` and can be configured at build time| + +**Changes:** + +- introduce new ASN manifest format `v3` +- added delta-tool as Python module +- introduced [Semantic version](https://semver.org/) format +- add an option to sign candidate image using update private key - + allowing to implement secure boot on a device side +- work with ECDSA raw signatures `(R||S)` - reduce verify code size on + target device +- simplified command line interface + - split between developer and production tools: + - `manifest-tool` - is for production use + - `manifest-dev-tool` - is for developer use only + - `manifest-delta-tool` - is the tool for preparing delta patches +- cleanup developer tool CLI by removing various configuration that + have no practical use at current point +- backward comparability with ASN manifest format v1 is preserved via + dedicated commands: + - `manifest-tool create-v1` + - `manifest-dev-tool update-v1` + - `manifest-dev-tool create-v1` + +# 1.5.2 diff --git a/dev-README.md b/dev-README.md new file mode 100644 index 0000000..c67999b --- /dev/null +++ b/dev-README.md @@ -0,0 +1,89 @@ +# Package Development + +## Pyenv - https://github.com/pyenv/pyenv +`pyenv` helps to manage different Python installations side by side. + +Example: +```shell +$ pyenv install 3.8.0 +$ pyenv install 3.7.5 +$ pyenv install 3.6.9 +$ pyenv install 3.5.7 +$ pyenv local 3.8.0 3.7.5 3.6.9 3.5.7 +$ python --version +Python 3.8.0 +``` +## Editable distribution + +For development it is preferable to install `manifest-tool` package in +"editable mode" (a.k.a "developer mode") by: +```shell +$ pip install -editable . +``` + +## dev_init.sh + +A helper script for bootstrapping development environment. + +Usage: +```shell +$ source dev_init.sh +$ manifest-dev-tool --version +Manifest-Tool version 2.0 +``` + +## pytest + +execute `pytest` command to verify no regression was introduced. +`pytest` will also generate `htmlcov/index.html` that can be opened in a browser for showing test coverage statistics. + +## tox + +`tox` is an automation tool. Details can be found here: +https://tox.readthedocs.io/en/latest/ +`tox` helps to automate testing on different python versions. + +Execute: `tox` command to test all supported Python environments. +Execute `tox -e py38` to test only the python3.8 environment. + +## wheel creation + +```shell +$ pyenv local 3.7.5 +$ python setup.py bdist_wheel +$ pyenv local 3.6.9 +$ python setup.py bdist_wheel +``` +do the same on each platform (Windows, Linux, macOS) per Python +interpreter. + +The resulting wheel packages will be found under `dist` directory. + +> Note: all the packages are created automatically by running `tox` +> command. + +## sdist + +Source distribution - can be done once as it is platform and Python +version agnostic. + +```shell +python setup.py sdist +``` +the resulting archive (`tar.gz`) will be found under `dist` directory + +> Note: all the packages are created automatically by running `tox` +> command. + +## Dependent packages versions +Dependent packages version should be tested with both lower and higher +bound. Tox tests with new virtual env where all the latest versions will +be installed. +When issuing a new release: +- test lower bound versions - if they are still applicable to latest + changes. +- bump the higher bound versions and test against them. + +We must freeze upper bound versions to the version which were tested at +the release creation time. + diff --git a/dev-requirements.txt b/dev-requirements.txt new file mode 100644 index 0000000..9d71a01 --- /dev/null +++ b/dev-requirements.txt @@ -0,0 +1,10 @@ +pytest +pytest-mock +pytest-cov +tox +tox-pyenv +pylint +pycodestyle +coverage +wheel +bandit \ No newline at end of file diff --git a/bin/manifest-tool b/dev_init.sh similarity index 68% rename from bin/manifest-tool rename to dev_init.sh index 01c9787..2fa4855 100755 --- a/bin/manifest-tool +++ b/dev_init.sh @@ -1,7 +1,6 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +#!/bin/bash -ex # ---------------------------------------------------------------------------- -# Copyright 2016 ARM Limited or its affiliates +# Copyright 2019 ARM Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0 # @@ -17,14 +16,15 @@ # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- -import sys -import os -manifesttoolPath = os.path.join(os.path.dirname(os.path.realpath(__file__)),'..') -sys.path.insert(0,manifesttoolPath) -from manifesttool import clidriver -def main(): - return clidriver.main() -if __name__ == "__main__": - sys.exit(main()) +if [[ ! -d venv ]]; then +virtualenv -p python3 venv +fi + +source venv/bin/activate + +pip uninstall manifesttool --yes +pip install --editable . + +pip install -r dev-requirements.txt diff --git a/manifesttool/__init__.py b/manifesttool/__init__.py index f5916dd..15386d3 100644 --- a/manifesttool/__init__.py +++ b/manifesttool/__init__.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates +# Copyright 2019 ARM Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0 # @@ -16,4 +15,5 @@ # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- -__version__ = '1.5.2' + +__version__ = "2.0.0" diff --git a/manifesttool/argparser.py b/manifesttool/argparser.py deleted file mode 100644 index a7ea6da..0000000 --- a/manifesttool/argparser.py +++ /dev/null @@ -1,316 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -import sys, argparse, os -from manifesttool import defaults, __version__ - -class MainArgumentParser(object): - - def __init__(self): - self.parser = self._make_parser() - - def _make_parser(self): - parser = argparse.ArgumentParser(description = 'Create or transform a manifest.' - ' Use {} [command] -h for help on each command.'.format(sys.argv[0])) - - # Add all top-level commands - parser.add_argument('-l', '--log-level', choices=['debug','info','warning','exception'], default='info') - parser.add_argument('--version', action='version', version=__version__, - help='display the version' - ) - subparsers = parser.add_subparsers(dest="action") - subparsers.required = True - create_parser = subparsers.add_parser('create', help='Create a new manifest') - parse_parser = subparsers.add_parser('parse', help='Parse an existing manifest') - verify_parser = subparsers.add_parser('verify', help='Verify an existing manifest') - cert_parser = subparsers.add_parser('cert', help='Create or examine a certificate') - init_parser = subparsers.add_parser('init', help='Set default values for manifests', - description='''Configures default values for manifests. - - The manifest init command requires a certificate. If one is not provided, init will guide the user through - the process of creating a certificate. Currently, the only supported type of created certificate is - self-signed, which should only be used for testing/development purposes. - - When using an existing certificate, the user may supply a script to use in performing signing operations. - This script is to support the use of exsiting Hardware Security Modules, etc.''') - sign_parser = subparsers.add_parser('sign', help='Sign an existing manifest', - description='''Signs an existing manifest with one additional signature. The manifest must first be - validated, so defaults for validation are extracted from .manifest_tool.json when values are not supplied - as arguments to the tool''') - update_parser = subparsers.add_parser('update', help='Work with the Device Management Update service') - - # Options for creating a new manifest - self._addCreateArgs(create_parser) - - # Options for parsing an existing manifest - parse_parser.add_argument('-j','--pretty-json', action='store_true') - parse_parser.add_argument('-e','--encoding', choices=['der'], default='der', - help='Decode created manifest using the provided encoding scheme') - # deprecated as of 2020: - if sys.version_info[0] == 2: - parse_parser.add_argument('-i', '--input-file', metavar='FILE', - help='Specify the input file. stdin by default', - type=argparse.FileType('rb'), default=sys.stdin) - elif sys.version_info[0] >= 3: - parse_parser.add_argument('-i', '--input-file', metavar='FILE', - help='Specify the input file. stdin by default', - type=argparse.FileType('rb'), default=sys.stdin.buffer) - self._add_output_file_arg(parse_parser) - - # Options for verifying an existing manifest - self._addVerifyArgs(verify_parser) - - cert_subparsers = cert_parser.add_subparsers(dest="cert_action") - cert_subparsers.required = True - - cert_create_parser = cert_subparsers.add_parser('create', - help='Create a certificate.\nWARNING: Certificates generated with this tool are self-signed and for testing only.', - description='Create a certificate.\nWARNING: Certificates generated with this tool are self-signed and for testing only.' - ) - # cert_read_parser = cert_subparsers.add_parser('read', help='Create a certificate') - - cert_create_parser.add_argument('-C','--country', help='Country of the subject', required=False) - cert_create_parser.add_argument('-S','--state', help='State or province of the subject', required=False) - cert_create_parser.add_argument('-L','--locality', help='Locality (city or region) of the subject', required=False) - cert_create_parser.add_argument('-O','--organization', help='Subject organization that will hold the certificate', required=False) - cert_create_parser.add_argument('-U','--common-name', help='Common name for the subject organization', required=False) - cert_create_parser.add_argument('-V','--valid-time', help='time for the certificate to be valid, in days, starting now', - type=int, required=True) - cert_create_parser.add_argument('-K','--key-output', help='file to store the private key generated for the new certificate', - type=argparse.FileType('wb'), required=True) - cert_add_parser = cert_subparsers.add_parser('add', - help='Add a certificate to the manifest-tool\'s list of certificates for use in manifest-tool verify.', - description='Adds a certificate to the {} directory.'.format(defaults.certificatePath)) - - cert_add_parser.add_argument('-c', '--certificate', - help='DER-encoded certificate to add to the certificate query directory ({})'.format(defaults.certificatePath), - type=argparse.FileType('rb'), required=True) - - self._add_output_file_arg(cert_create_parser) - - init_parser.add_argument('-c','--certificate', help='Provide an existing certificate to init', - type=argparse.FileType('rb'), required=False) - init_existing_cert_signing = init_parser.add_mutually_exclusive_group(required=False) - init_existing_cert_signing.add_argument('-k','--private-key', - help='Provide a private key file for the certificate provided with -c. ' + - 'This allows the manifest tool to perform manifest signing internally.', - type=argparse.FileType('rb')) - init_existing_cert_signing.add_argument('-s','--signing-tool', - help='Provide a tool that should be used for signing. ' + - 'This allows signing with existing infrastructure. ' + - 'The arguments to the tool are: ' + - ' .', - type=argparse.FileType('rb')) - init_parser.add_argument('--signing-key-id', - help='Provide an identifier for the private key that will be used to sign file for the certificate provided with -c. ' + - 'This allows the manifest tool to perform manifest signing internally.') - - init_vendor_group = init_parser.add_mutually_exclusive_group(required=True) - init_vendor_group.add_argument('-V', '--vendor-id', help='') - init_vendor_group.add_argument('-d', '--vendor-domain', help='') - - init_class_group = init_parser.add_mutually_exclusive_group(required=True) - init_class_group.add_argument('-C', '--class-id', help='') - init_class_group.add_argument('-m', '--model-name', help='') - - init_parser.add_argument('-S', '--server-address', help='Address of the API server for updates') - init_parser.add_argument('-a', '--api-key', help='API Key for the API server') - init_parser.add_argument('-q', '--quiet', help='Do not prompt for certificate fields', action='store_true') - init_parser.add_argument('-f', '--force', action='store_true', - help='Overwrite existing update_default_resources.c') - init_parser.add_argument('--psk', action='store_true', help='initialize this project as a PSK authentication project') - - self._addVerifyArgs(sign_parser, ['input-file']) - sign_source_group = sign_parser.add_mutually_exclusive_group(required=True) - sign_source_group.add_argument('-m', '--manifest', type=argparse.FileType('rb'), default=sys.stdin) - # sign_source_group.add_argument('-u', '--url') - - sign_parser.add_argument('-k', '--private-key', metavar='KEY', - help='Supply a private key, or a shared secret for signing a created manifest', - type=argparse.FileType('rb')) - sign_parser.add_argument('-c','--certificate', - help='Provide an existing certificate to reference in the manifest signature. This must match the private key', - type=argparse.FileType('rb')) - - update_sub_parsers = update_parser.add_subparsers(dest='update_action') - - prepare_parser = update_sub_parsers.add_parser('prepare', help='Prepare an update', - description='''Prepares an update for Pelion Device Management. This uploads the specified payload, creates a manifest - and uploads the manifest.''') - - self._addCreateArgs(prepare_parser, ['output-file']) - prepare_parser.add_argument('-o', '--output-file', metavar='FILE', - help='Specify the output file for the manifest. A temporary file is used by default.', - type=argparse.FileType('wb'), default=None) - - prepare_parser.add_argument('-n', '--payload-name', - help='The reference name for the payload in Pelion Device Management. If no name is specified, then one will be created ' - 'using the file name of the payload and the current timestamp.') - prepare_parser.add_argument('-d', '--payload-description', - help='The description of the payload for use in Pelion Device Management.') - prepare_parser.add_argument('--manifest-name', - help='The reference name for the manifest in Pelion Device Management. If no name is specified, then one will be created ' - 'using the file name of the manifest and the current timestamp.') - prepare_parser.add_argument('--manifest-description', - help='The description of the manifest for use in Pelion Device Management.') - prepare_parser.add_argument('-a', '--api-key', help='API Key for Pelion Device Management') - - update_device_parser = update_sub_parsers.add_parser('device', - help='Update a single device using its LwM2M Device ID', - description='''Update a single device using its LwM2M Device ID. Note that settings may be provided in the - manifest tool configuration file ({}). The API key MUST be provided in the Device Management Client - configuration file.'''.format(defaults.config)) - self._addCreateArgs(update_device_parser, ['output-file']) - - update_device_parser.add_argument('-o', '--output-file', metavar='FILE', - help='Specify the output file for the manifest. A temporary file is used by default.', - type=argparse.FileType('wb'), default=None) - - update_device_parser.add_argument('-n', '--payload-name', - help='The reference name for the payload in Pelion Device Management. If no name is specified, then one will be created ' - 'using the file name of the payload and the current timestamp.') - update_device_parser.add_argument('-d', '--payload-description', - help='The description of the payload for use in Pelion Device Management.') - update_device_parser.add_argument('--manifest-name', - help='The reference name for the manifest in Pelion Device Management. If no name is specified, then one will be created ' - 'using the file name of the manifest and the current timestamp.') - update_device_parser.add_argument('--manifest-description', - help='The description of the manifest for use in Pelion Device Management.') - update_device_parser.add_argument('-D', '--device-id', help='The device ID of the device to update', required=True) - update_device_parser.add_argument('--no-cleanup', action='store_true', - help='''Don't delete the campaign, manifest, and firmware image from Pelion Device Management when done''') - update_device_parser.add_argument('-T', '--timeout', type=int, default=-1, - help='''Set the time delay before the manifest tool aborts the campaign. Use -1 for indefinite (this is the default).''') - update_device_parser.add_argument('-a', '--api-key', help='API Key for Pelion Device Management') - - return parser - - def _add_input_file_arg(self, parser): - parser.add_argument('-i', '--input-file', metavar='FILE', - help='Specify the input file. stdin by default', - type=argparse.FileType('r'), default=sys.stdin) - - def _add_output_file_arg(self, parser): - output_default = sys.stdout - if sys.version_info.major == 3: - output_default = sys.stdout.buffer - parser.add_argument('-o', '--output-file', metavar='FILE', - help='Specify the output file. stdout by default', - type=argparse.FileType('wb'), default=output_default) - def _addCreateArgs(self, parser, exclusions=[]): - parser.add_argument('-v', '--manifest-version', choices=['1'], default='1') - if not 'private-key' in exclusions: - parser.add_argument('-k', '--private-key', metavar='KEY', - help='Supply a private key, or a shared secret for signing a created manifest', - type=argparse.FileType('rb')) - # create_parser.add_argument('-e','--encrypt-payload', choices=['aes-psk']) - # create_parser.add_argument('-s','--payload-secret', metavar='SECRET', - # help='Secret data used for encryption, e.g. a pre-shared key or a private key.\ - # The exact contents is dictated by the encryption method used. The secret may\ - # be base64 encoded or may be a filename.') - if not 'mac' in exclusions: - parser.add_argument('--mac', - help='Use Pre-Shared-Key MAC authentication, with a master key supplied in --private-key. ' - 'A filter ID or Device Unique ID is also required to specify which devices should have TAGs created. ' - 'These can be supplied in --filter-id or --device-urn.\n' - 'The manifest tool will create a PSK for each device based on the master key and the concatenation of three LwM2M values: \n' - ' /10255/0/3 (Vendor ID)\n' - ' /10255/0/4 (Device Class ID)\n' - ' Device URN (Endpoint Client Name)', - action='store_true') - parser.add_argument('--filter-id', help='specify which devices to use.') - parser.add_argument('--device-urn', action='append', - help='Specify devices to target with the update by their URNs (Endpoint Client Name). ' - 'The manifest tool will derive a PSK for the specified device based on the master key and the concatenation of: \n' - ' Vendor ID\n' - ' Device Class ID\n' - ' Device URN\n' - '--device-urn can be used multiple times to specify multiple devices.') - parser.add_argument('--psk-table', help='Specify the file to use to store the PSK table. ' - 'This file is used with the --mac argument in order to specify the output file for the pre-shared keys. ' - 'The table is composed of three columns: device URN, WrappedManifestDigest, and WrappedPayloadKey.', - type=argparse.FileType('wb')) - parser.add_argument('--psk-table-encoding', help='', choices=['protobuf', 'text'], default='text') - if not 'payload-key' in exclusions: - parser.add_argument('--payload-key', help='supply the payload encryption key. This is the key that is used encrypt the payload. ' - 'The payload key is encrypted for each device using a shared secret.') - if not 'payload' in exclusions: - parser.add_argument('-p', '--payload', - help='Supply a local copy of the payload file.' - 'This option overrides any payload file supplied in a `-i` argument.', metavar='FILE', - type=argparse.FileType('rb'), required = False) - if not 'uri' in exclusions: - parser.add_argument('-u', '--uri', - help='Supply the URI of the payload. ' - 'When a payload is uploaded to cloud storage, this is the URL of the payload. ' - 'This option overrides any URI supplied in a `-i` argument.') - parser.add_argument('--url', help='Synonym for `--uri`', dest='uri') - if not 'encoding' in exclusions: - parser.add_argument('-c','--encoding', choices=['der'], default='der', - help='Encode created manifest using the provided encoding scheme') - if not 'hex' in exclusions: - parser.add_argument('-x', '--hex', action='store_true', - help='Output data in hex octets') - if not 'c-file' in exclusions: - parser.add_argument('-C', '--c-file', action='store_true', - help='Output data as a C file') - if not 'input-file' in exclusions: - self._add_input_file_arg(parser) - if not 'output-file' in exclusions: - self._add_output_file_arg(parser) - if not 'payload-format' in exclusions: - parser.add_argument('-f','--payload-format', - choices=['raw-binary', 'bsdiff-stream'], - help='Speficy the payload format. Supported formats are: ' - 'raw-binary (unprocessed binary bytes with no metadata), ' - 'bsdiff-stream (lz4-compressed bsdiff, reorganised for stream ' - 'processing)') - - def _addVerifyArgs(self, verify_parser, exclusions=[]): - if not 'pretty-json' in exclusions: - verify_parser.add_argument('-j','--pretty-json', action='store_true') - if not 'encoding' in exclusions: - verify_parser.add_argument('-e','--encoding', choices=['der'], default='der', - help='Decode created manifest using the provided encoding scheme') - if not 'certificate-directory' in exclusions: - verify_parser.add_argument('-d','--certificate-directory', default=defaults.certificatePath, - help='A directory that contains the certificates necessary to validate a manifest. These should be named with their fingerprint.') - if not 'vendor-id' in exclusions: - verify_parser.add_argument('-V','--vendor-id', dest='vendorId', metavar='VENDORID', - help='Set the vendor UUID that verify should expect.' ) - if not 'class-id' in exclusions: - verify_parser.add_argument('-C','--class-id', dest='classId', metavar='CLASSID', - help='Set the class UUID that verify should expect.' ) - if not 'input-file' in exclusions: - verify_parser.add_argument('-i', '--input-file', metavar='FILE', - help='Specify the input file. stdin by default', - type=argparse.FileType('rb'), default=sys.stdin) - if not 'output-file' in exclusions: - self._add_output_file_arg(verify_parser) - - def _verify_arguments(self): - """Custom logic to ensure valid arguments are passed in""" - # if self.options.action == "create": - # if self.options.encrypt_payload and not self.options.payload_secret: - # self.parser.error('A secret must be supplied with --payload-secret option when the --encrypt-payload option is in use.') - pass - - def parse_args(self, args=None): - self.options = self.parser.parse_args(args) - self._verify_arguments() - return self diff --git a/manifesttool/cert.py b/manifesttool/cert.py deleted file mode 100644 index 67bd195..0000000 --- a/manifesttool/cert.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -from __future__ import print_function -import logging, sys, os -from cryptography import x509 -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives.asymmetric import ec -from six import text_type as text -import datetime -import binascii -from manifesttool import defaults -from manifesttool import utils - -LOG = logging.getLogger(__name__) - -def create(options): - key = ec.generate_private_key(ec.SECP256R1(), default_backend()) - options.key_output.write(key.private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.TraditionalOpenSSL, - encryption_algorithm=serialization.NoEncryption() - )) - # Various details about who we are. For a self-signed certificate the - # subject and issuer are always the same. - subjectList = [] - try: - if options.country: - subjectList += [x509.NameAttribute(x509.oid.NameOID.COUNTRY_NAME, text(options.country))] - if options.state: - subjectList += [x509.NameAttribute(x509.oid.NameOID.STATE_OR_PROVINCE_NAME, text(options.state))] - if options.locality: - subjectList += [x509.NameAttribute(x509.oid.NameOID.LOCALITY_NAME, text(options.locality))] - if options.organization: - subjectList += [x509.NameAttribute(x509.oid.NameOID.ORGANIZATION_NAME, text(options.organization))] - if options.common_name: - subjectList += [x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, text(options.common_name))] - if len(subjectList) == 0: - subjectList += [x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, text('localhost'))] - subject = issuer = x509.Name(subjectList) - except ValueError as e: - LOG.critical('Error creating certificate: {}'.format(e.message)) - fname = options.output_file.name - options.output_file.close() - os.remove(fname) - return 1 - - subjectKey = key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) - subjectKeyIdentifier = utils.sha_hash(subjectKey)[:160//8] # Use RFC7093, Method 1 - - try: - cert = x509.CertificateBuilder().subject_name( - subject - ).issuer_name( - issuer - ).public_key( - key.public_key() - ).serial_number( - x509.random_serial_number() - ).not_valid_before( - datetime.datetime.utcnow() - ).not_valid_after( - datetime.datetime.utcnow() + datetime.timedelta(days=options.valid_time) - ).add_extension( - x509.KeyUsage( - digital_signature = True, - content_commitment = False, - key_encipherment = False, - data_encipherment = False, - key_agreement = False, - key_cert_sign = False, - crl_sign = False, - encipher_only = False, - decipher_only = False), - critical=False - ).add_extension( - x509.SubjectAlternativeName([x509.DNSName(u"localhost")]), - critical=False, - ).add_extension( - x509.ExtendedKeyUsage([x509.oid.ExtendedKeyUsageOID.CODE_SIGNING]), - critical=False, - ).add_extension( - x509.SubjectKeyIdentifier(subjectKeyIdentifier), - critical=False, - # Sign our certificate with our private key - ).sign(key, hashes.SHA256(), default_backend()) - except ValueError as e: - LOG.critical('Error creating certificate: {}'.format(e.message)) - fname = options.output_file.name - options.output_file.close() - os.remove(fname) - return 1 - # Write our certificate out to disk. - options.output_file.write(cert.public_bytes(serialization.Encoding.DER)) - options.output_file.close() - print('[\033[1;93mWARNING\033[1;0m]: Certificates generated with this tool are self-signed and for testing only', - file=sys.stderr) - if options.valid_time < 10 * 365.25: - print('[\033[1;93mWARNING\033[1;0m]: This certificate is valid for {} days. For production,' - 'use certificates with at least 10 years validity.'.format(options.valid_time), - file=sys.stderr) - - return 0 - -def add(options): - if not hasattr(options, 'certificate'): - LOG.critical('Cannot add certificate without certificate') - return 1 - # Load the certificate - cert = x509.load_der_x509_certificate(options.certificate.read(), default_backend()) - # Make sure the certificate uses SHA256. - if not isinstance(cert.signature_hash_algorithm, hashes.SHA256): - LOG.critical("In ({file}): Only SHA256 certificates are supported by the Device Management Update client at this time.".format(file=options.certificate.name)) - return 1 - if not isinstance(cert.public_key().curve, ec.SECP256R1): - LOG.critical("In ({file}): Only secp256r1 (prime256v1) certificates are supported by the Device Management Update client at this time.".format(file=options.certificate.name)) - return 1 - - fp = bytes(cert.fingerprint(hashes.SHA256())) - newCertPath = os.path.join(defaults.certificatePath, binascii.b2a_hex(fp)) - with open(newCertPath, 'wb') as f: - f.write(cert.public_bytes(serialization.Encoding.DER)) - LOG.info('Added certificate as: {}'.format(newCertPath)) - return 0 - -def read(options): - pass - -def main(options): - return { "create": create, - "add": add, - # "read": parse - }[options.cert_action](options) diff --git a/manifesttool/clidriver.py b/manifesttool/clidriver.py deleted file mode 100644 index f0e7609..0000000 --- a/manifesttool/clidriver.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -import logging, sys - -from manifesttool.argparser import MainArgumentParser -from manifesttool import create, parse, verify, cert, init, sign -from manifesttool import update -import colorama -colorama.init() - - -LOG = logging.getLogger(__name__) -LOG_FORMAT='[%(levelname)s] %(asctime)s - %(name)s - %(message)s' - -def main(): - driver = CLIDriver() - return driver.main() - -class CLIDriver(object): - - def __init__(self): - self.options = MainArgumentParser().parse_args().options - - log_level = { - 'debug': logging.DEBUG, - 'info': logging.INFO, - 'warning': logging.WARNING, - 'exception': logging.CRITICAL - }[self.options.log_level] - logging.basicConfig(level=log_level, - format=LOG_FORMAT, - datefmt='%Y-%m-%d %H:%M:%S') - logging.addLevelName( logging.INFO, "\033[1;32m%s\033[1;0m" % logging.getLevelName(logging.INFO)) - logging.addLevelName( logging.WARNING, "\033[1;93m%s\033[1;0m" % logging.getLevelName(logging.WARNING)) - logging.addLevelName( logging.CRITICAL, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.CRITICAL)) - - LOG.debug('CLIDriver created. Arguments parsed and logging setup.') - - def main(self): - rc = { "create": create.main, - "parse": parse.main, - "verify": verify.main, - "cert": cert.main, - "init": init.main, - "update" : update.main, - "sign": sign.main - }[self.options.action](self.options) or 0 - - sys.exit(rc) diff --git a/manifesttool/codec.py b/manifesttool/codec.py deleted file mode 100644 index e12e8dc..0000000 --- a/manifesttool/codec.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -import codecs, uuid, binascii -from pyasn1.codec.native.decoder import decode as native_decode -from pyasn1.codec.native.encoder import encode as native_encode - -def get_component_type(schema): - """Due to quirks in the pyasn1 library, for some schema types the componentType is not - properly set, so we use this convinience method to access the underlying data if required""" - return schema.componentType if (len(schema.componentType) > 0) else schema._componentType - -def obj2asn(value, schema): - """ - Converts python object into the pyasn1 object following the schema provided. The (potentially nested) - object (commenly converted from JSON) will of course have to match the format of the ASN.1 defintion. - - Given the following schema: - - MyStruct SEQUENCE ::= { - id INTEGER, - name UTF8String - } - - Example: - - >>> import schema_definition - >>> from pyasn1.codec.der import encoder - >>> value = JSON.loads('{ "id": 1, "name": "David" }') - >>> - >>> # pyasn1 schema can be generated from ASN.1 definition using asn2py script, here - >>> # exported as schema_definition.py, which we can import as a python module. - >>> asn_obj = obj2asn(value, schema_definition.MyStruct()) - >>> - >>> # We can now encode this data to whatever format we want - >>> der_bytes = encoder.encode(asn_obj) - """ - return native_decode(value, schema) - -def asn2obj(asn, numericEnum=False): - """ - Decodes ASN objects into Python object structures (array or dictionary). See - opposing function `obj2asn` for the encoding logic. - - This is commonly called for when you have a pyasn1 object (e.g. as a result - of running as pyasn1 decode from raw bytes) and you want to output into JSON - or similar. - - Example, given the same schema as defined in `obj2asn`: - - >>> from pyasn1.codec.der import decoder - >>> import schema_definition - >>> import json - >>> raw_bytes = b"..." - >>> asn_obj = decoder.decode(raw_bytes, schema_definition.MyStruct()) - >>> print json.dumps(asn2obj(asn_obj), indent=4) - { - "id": 1, - "name": "David" - } - """ - - if asn.__class__.__name__ == 'Any': - return asn.asOctets() - - # If type_id is not set, we have a primitive type - if not asn.typeId: - # If the type has base type which is UTF8String, we use the string - # representation of these bytes - and not the raw representation as - # value. Might be a better way of checking if it's a string class, but - # this works fine. - if 'UTF8String' in [b.__name__ for b in asn.__class__.__bases__] or \ - asn.__class__.__name__ == 'UTF8String': - if isinstance(asn._value, bytes): - return asn._value.decode(asn._encoding) - return str(asn._value) - - # Translate the UUID type into URN format (RFC-4122) - if asn.__class__.__name__ == 'UUID': - if len(asn._value) != 16: - return binascii.b2a_hex(asn.asOctets()) - else: - return str(uuid.UUID(bytes=asn._value)) - - # The type OBJECT IDENTIFIER becomes a tuple type, so we - # decode it into a "." delimited string - if isinstance(asn._value, tuple): - return '.'.join(map(str, asn._value)) - - # The ASN type Boolean becomes 1/0, but we would like to translate - # to Python booleans. - if asn.__class__.__name__ == 'Boolean': - return bool(asn._value) - - if asn.__class__.__name__ == 'Enumerated': - if numericEnum: - return int(asn._value) - else: - return asn.getNamedValues().getName(asn) - # If we have bytes, we encode into hex representation. Hacky, but we - # need something JSON serializable. - if isinstance(asn._value, bytes): - return codecs.encode(asn._value, 'hex').decode(asn._encoding) - - return asn._value - - # If type_id is 1 or 2 we have a Sequence/SetOf type (i.e. an array) - elif asn.typeId <= 2: - return [asn2obj(e, numericEnum) for e in asn._componentValues] - - # If not primitive nor array, we have a Sequence-like type and we handle - # this as a dictionary. We iterate through each key where the value is - # set (i.e. ignoring empty optional fields) and recursivly get the decoded - # value block. - j = {} - if hasattr(asn, '_componentValues'): - for idx, v in enumerate(asn._componentValues): - if v is None or (hasattr(v,'__len__') and len(v) is 0): continue - j[asn.getNameByPosition(idx)] = asn2obj(v,numericEnum) - return j - -def asn2obj_native(asn): - """ - Decodes ASN objects into Python object structures (array or dictionary). See - opposing function `obj2asn` for the encoding logic. - - This is commonly called for when you have a pyasn1 object (e.g. as a result - of running as pyasn1 decode from raw bytes) and you want to output into JSON - or similar. - - Example, given the same schema as defined in `obj2asn`: - - >>> from pyasn1.codec.der import decoder - >>> import schema_definition - >>> import json - >>> raw_bytes = b"..." - >>> asn_obj = decoder.decode(raw_bytes, schema_definition.MyStruct()) - >>> print json.dumps(asn2obj(asn_obj), indent=4) - { - "id": 1, - "name": "David" - } - """ - return native_encode(asn) - -def bin2obj(value, schema, decoder, numericEnum = False): - decoded_asn = decoder.decode(value, schema)[0] - return asn2obj(decoded_asn, numericEnum) - -def bin2obj_native(value, schema, decoder): - decoded_asn = decoder.decode(value, schema)[0] - return asn2obj_native(decoded_asn) diff --git a/manifesttool/create.py b/manifesttool/create.py deleted file mode 100644 index 4336ecf..0000000 --- a/manifesttool/create.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -from manifesttool.v1.create import main as create_v1 -import os -import sys -import json -from manifesttool import defaults -import logging, sys -LOG = logging.getLogger(__name__) - -def main(options): - - # Read options from manifest input file/ - # if (options.input_file.isatty()): - # LOG.info("Reading data from from active TTY... Terminate input with ^D") - manifestInput = { - 'applyImmediately' : True - } - - try: - if os.path.exists(defaults.config): - with open(defaults.config) as f: - manifestInput.update(json.load(f)) - if not options.input_file.isatty(): - content = options.input_file.read() - if content and len(content) >= 2: #The minimum size of a JSON file is 2: '{}' - manifestInput.update(json.loads(content)) - except ValueError as e: - LOG.critical("JSON Decode Error: {}".format(e)) - sys.exit(1) - - create = { - '1' : create_v1 - }.get(options.manifest_version) - - return create(options, manifestInput) diff --git a/manifesttool/v1/__init__.py b/manifesttool/delta_tool/__init__.py similarity index 91% rename from manifesttool/v1/__init__.py rename to manifesttool/delta_tool/__init__.py index a673de6..0ef1083 100644 --- a/manifesttool/v1/__init__.py +++ b/manifesttool/delta_tool/__init__.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- -# Copyright 2017 ARM Limited or its affiliates +# Copyright 2019 ARM Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0 # diff --git a/manifesttool/delta_tool/delta_tool.py b/manifesttool/delta_tool/delta_tool.py new file mode 100644 index 0000000..08e0d86 --- /dev/null +++ b/manifesttool/delta_tool/delta_tool.py @@ -0,0 +1,275 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import argparse +import base64 +import hashlib +import logging +import re +import sys +from mmap import mmap, ACCESS_READ +from pathlib import Path + +import yaml + +from manifesttool import __version__ +from manifesttool import armbsdiff + +logger = logging.getLogger("manifest-delta-tool") + + +def _existing_file_path_factory(value): + prospective = Path(value) + if not prospective.is_file(): + raise argparse.ArgumentTypeError( + 'File {} is not found'.format(value) + ) + return prospective + + +def _block_size_factory(value): + prospective = None + try: + prospective = int(value) + except ValueError: + pass + if not prospective or prospective < 128: + raise argparse.ArgumentTypeError( + "{} is invalid - must be at least 128".format(value)) + return prospective + + +def digest_file(file_path: Path): + read_block_size = 65536 + with file_path.open('rb') as fh: + hash_ctx = hashlib.sha256() + buf = fh.read(read_block_size) + while buf: + hash_ctx.update(buf) + buf = fh.read(read_block_size) + file_len = fh.tell() + return base64.b64encode(hash_ctx.digest()), file_len + + +def size_check(new_size, delta_size, threshold): + """ + Assert new fw image is smaller than delta file + + :param new_size: full new FW image size + :param delta_size: delta file size + :param threshold: size difference threshold for aborting the generation. + in case evaluates to False - size check will be aborted. + """ + + diff = 100 * float(delta_size) / float(new_size) + + if threshold and diff >= threshold: + raise AssertionError( + 'Difference with delta image and update image is more than ' + '{} percent! Percentage is: {:.2f}'.format(threshold, diff)) + + +def get_version_string_from_bin_file(fname: Path): + with fname.open('rb') as fh: + with mmap(fh.fileno(), 0, access=ACCESS_READ) as my_mmap: + match = re.search(b'(PELION/BSDIFF\\d{3})', my_mmap) + if not match: + raise AssertionError("Version details not found") + return match.group(0).decode('utf-8') + + +def check_bsdiff_bspatch_versions(original_image_path: Path): + bsdiff_version = armbsdiff.get_version() + logger.info("Current tool version %s", bsdiff_version) + bspatch_version = get_version_string_from_bin_file(original_image_path) + + if bsdiff_version != bspatch_version: + logger.error( + 'Bspatch version in {} is incomatible with this version ' + 'of delta-tool.') + + logger.error( + 'Original image version is: %s', + bspatch_version.decode("utf-8").split('/')[1] + ) + + logger.error( + 'Current bsdiff version is: %s', + bsdiff_version.decode("utf-8").split('/')[1] + ) + + raise AssertionError('bsdiff/bspatch version mismatch') + + +def generate_delta( + orig_fw: Path, + new_fw: Path, + output_delta_file: Path, + block_size, + threshold +): + check_bsdiff_bspatch_versions(orig_fw) + + original_digest, _ = digest_file(orig_fw) + new_digest, new_size = digest_file(new_fw) + + if original_digest == new_digest: + logger.warning('New and old file are binary same. This will generate ' + 'delta that will not change the original image. ' + 'This is probably a mistake') + + try: + armbsdiff.generate( + orig_fw.as_posix(), + new_fw.as_posix(), + output_delta_file.as_posix(), + block_size + ) + + _, delta_size = digest_file(output_delta_file) + + size_check(new_size, delta_size, threshold) + except AssertionError: + if output_delta_file.is_file(): + output_delta_file.unlink() + raise + + delta_cfg_file = output_delta_file.with_suffix('.yaml') + config = { + 'installed-digest': new_digest, + 'installed-size': new_size, + 'precursor-digest': original_digest + } + with delta_cfg_file.open('wt') as fh: + yaml.dump(config, fh) + + +def get_parser(): + parser = argparse.ArgumentParser( + description='Tool for generating delta-updates to be used with ' + 'Pelion-FOTA', + add_help=False + ) + required = parser.add_argument_group('required arguments') + optional = parser.add_argument_group('optional arguments') + + required.add_argument( + '-c', '--current-fw', + type=_existing_file_path_factory, + help='Currently installed on device firmware image for delta update ' + 'calculation.', + required=True + ) + required.add_argument( + '-n', '--new-fw', + type=_existing_file_path_factory, + help='New firmware image to be installed on device.', + required=True + ) + + required.add_argument( + '-o', '--output', + type=Path, + help='Output delta file name. Note additional configuration file with ' + 'same name but with different extension will be generated. ' + 'Both files are required by the manifest-tool. Only the ' + 'output file - specified by this argument should be uploaded ' + 'to Pelion storage.', + required=True + ) + + optional.add_argument( + '-b', '--block-size', + type=_block_size_factory, + help='Compression block size to pass to arm-bsdiff engine.' + 'Greater block size will provide better compression, but ' + 'requires more memory on device side.' + ' Default is 512. Minimum is 128. ' + ' NOTE: This value MUST be aligned with network (COAP/HTTP) ' + 'buffer size used for download', + default=512 + ) + + size_group = optional.add_mutually_exclusive_group() + + # must be first in a group for default value to be set properly + size_group.add_argument( + '-t', '--threshold', + type=int, + choices=range(30, 100, 10), + default=60, + help='A threshold in percents that will trigger a warning while ' + 'comparing patch files size to the new FW size.' + ) + size_group.add_argument( + '--skip-size-check', + action='store_false', + dest='threshold', + help='Skip size validations after delta update generation.' + ) + + optional.add_argument( + '--debug', + action='store_true', + help='Show exception info on error.' + ) + optional.add_argument( + '--version', + action='version', + version='Manifest-Tool version {}'.format(__version__) + + ) + + optional.add_argument( + '-h', + '--help', + action='help', + help='show this help message and exit' + ) + + return parser + + +def entry_point(argv=sys.argv[1:]): # pylint: disable=dangerous-default-value + parser = get_parser() + args = parser.parse_args(argv) + + logging.basicConfig( + stream=sys.stdout, + format='%(asctime)s %(levelname)s %(message)s', + level=logging.DEBUG + ) + + try: + generate_delta( + orig_fw=args.current_fw, + new_fw=args.new_fw, + output_delta_file=args.output, + block_size=args.block_size, + threshold=args.threshold + ) + except Exception as ex: # pylint: disable=broad-except + logger.error( + str(ex), + exc_info=args.debug + ) + return 1 + return 0 + + +if __name__ == '__main__': + raise SystemExit(entry_point()) diff --git a/manifesttool/errorhandler.py b/manifesttool/dev_tool/__init__.py similarity index 86% rename from manifesttool/errorhandler.py rename to manifesttool/dev_tool/__init__.py index 7f565d6..0ef1083 100644 --- a/manifesttool/errorhandler.py +++ b/manifesttool/dev_tool/__init__.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- -# Copyright 2016 ARM Limited or its affiliates +# Copyright 2019 ARM Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0 # @@ -16,6 +15,3 @@ # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- - -class InvalidObject(Exception): - pass diff --git a/manifesttool/dev_tool/actions/__init__.py b/manifesttool/dev_tool/actions/__init__.py new file mode 100644 index 0000000..0ef1083 --- /dev/null +++ b/manifesttool/dev_tool/actions/__init__.py @@ -0,0 +1,17 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- diff --git a/manifesttool/dev_tool/actions/code_template.txt b/manifesttool/dev_tool/actions/code_template.txt new file mode 100644 index 0000000..c9263bb --- /dev/null +++ b/manifesttool/dev_tool/actions/code_template.txt @@ -0,0 +1,53 @@ +// ---------------------------------------------------------------------------- +// Copyright 2019 ARM Limited or its affiliates +// +// 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. +// ---------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Autogenerated file - do not edit +// +// generated on: {timestamp} +// generated by: {tool} +// tool version: {version} +//----------------------------------------------------------------------------- + +#include + +const uint8_t arm_uc_vendor_id[] = {{ + {vendor_id} +}}; +const uint16_t arm_uc_vendor_id_size = sizeof(arm_uc_vendor_id); + +const uint8_t arm_uc_class_id[] = {{ + {class_id} +}}; +const uint16_t arm_uc_class_id_size = sizeof(arm_uc_class_id); + +// TODO: remove it when no longer used +// This value is here for backwards compatability purposes - it is not used +const uint8_t arm_uc_default_fingerprint[] = {{ + 0 +}}; +const uint16_t arm_uc_default_fingerprint_size = sizeof(arm_uc_default_fingerprint); + +const uint8_t arm_uc_default_certificate[] = {{ + {cert} +}}; +const uint16_t arm_uc_default_certificate_size = sizeof(arm_uc_default_certificate); + +const uint8_t arm_uc_update_public_key[] = {{ + {update_pub_key} +}}; diff --git a/manifesttool/dev_tool/actions/create.py b/manifesttool/dev_tool/actions/create.py new file mode 100644 index 0000000..f3a1543 --- /dev/null +++ b/manifesttool/dev_tool/actions/create.py @@ -0,0 +1,219 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import argparse +import logging +import time +from pathlib import Path +from typing import Type + +import yaml + +from manifesttool.dev_tool import defaults +from manifesttool.mtool.actions import existing_file_path_arg_factory +from manifesttool.mtool.actions import non_negative_int_arg_factory +from manifesttool.mtool.actions import semantic_version_arg_factory +from manifesttool.mtool.actions.create import CreateAction +from manifesttool.mtool.asn1 import ManifestAsnCodecBase +from manifesttool.mtool.payload_format import PayloadFormat + +logger = logging.getLogger('manifest-dev-tool-create') + + +def register_parser(parser: argparse.ArgumentParser, schema_version: str): + + required = parser.add_argument_group('required arguments') + optional = parser.add_argument_group('optional arguments') + + required.add_argument( + '-u', '--payload-url', + help='Payload URL as seen by device.', + required=True + ) + + required.add_argument( + '-p', '--payload-path', + help='Payload file local path - for digest calculation.', + type=existing_file_path_arg_factory, + required=True + ) + + required.add_argument( + '-o', '--output', + help='Output manifest.', + type=argparse.FileType('wb'), + required=True + ) + if schema_version == 'v1': + optional.add_argument( + '-v', '--fw-version', + type=non_negative_int_arg_factory, + help='FW version to be set in manifest. ' + '[Default: current timestamp]', + default=int(time.time()) + ) + else: + optional.add_argument( + '-v', '--fw-version', + type=semantic_version_arg_factory, + help='FW version to be set in manifest in Semantic ' + 'Versioning Specification format.' + ) + optional.add_argument( + '--component-name', + default='MAIN', + metavar='NAME', + help='Component name to be udpated. Must correspond to existing ' + 'components name on targeted devices' + ) + optional.add_argument( + '-m', '--sign-image', + action='store_true', + help='Sign image. Should be used when bootloader on a device ' + 'expects signed FW image.' + ) + optional.add_argument( + '-r', '--priority', + type=non_negative_int_arg_factory, + help='Update priority >=0. [Default: 0]', + metavar='INT', + default=0 + ) + + optional.add_argument( + '-d', '--vendor-data', + help='Vendor custom data file - to be passed to a device.', + type=existing_file_path_arg_factory + ) + + optional.add_argument( + '--cache-dir', + help='Tool cache directory. ' + 'Must match the directory used by "init" command', + type=Path, + default=defaults.BASE_PATH + ) + + optional.add_argument( + '-h', + '--help', + action='help', + help='show this help message and exit' + ) + + +def create_dev_manifest( + dev_cfg: dict, + manifest_version: Type[ManifestAsnCodecBase], + vendor_data_path: Path, + payload_path: Path, + payload_url: str, + priority: int, + fw_version: str, + sign_image: bool, + component: str +): + + key_file = Path(dev_cfg['key_file']) + if not key_file.is_file(): + raise AssertionError('{} not found'.format(key_file.as_posix())) + key_data = key_file.read_bytes() + + payload_file = payload_path + delta_meta_file = payload_file.with_suffix('.yaml') + + if delta_meta_file.is_file(): + payload_format = PayloadFormat.PATCH + else: + payload_format = PayloadFormat.RAW + + input_cfg = { + 'vendor': { + 'vendor-id': dev_cfg['vendor-id'] + }, + 'device': { + 'class-id': dev_cfg['class-id'] + }, + 'priority': priority, + 'payload': { + 'url': payload_url, + 'file-path': payload_path.as_posix(), + 'format': payload_format.value + } + } + + if manifest_version.get_name() != 'v1': + input_cfg['sign-image'] = sign_image + input_cfg['component'] = component + + if vendor_data_path: + input_cfg['vendor']['custom-data-path'] = vendor_data_path.as_posix() + + manifest_bin = CreateAction.do_create( + pem_key_data=key_data, + input_cfg=input_cfg, + fw_version=fw_version, + update_certificate=Path(dev_cfg['certificate']), + asn1_codec_class=manifest_version + ) + return manifest_bin + +def bump_minor(sem_ver: str): + major, minor, split = sem_ver.split('.') + split = str(int(split) + 1) + return '{}.{}.{}'.format(major, minor, split) + +def entry_point( + args, + manifest_version: Type[ManifestAsnCodecBase] +): + cache_dir = args.cache_dir + + if not cache_dir.is_dir(): + raise AssertionError( + 'Tool cache directory is missing. ' + 'Execute "init" command to create it.') + + with (cache_dir / defaults.DEV_CFG).open('rt') as fh: + dev_cfg = yaml.safe_load(fh) + + cache_fw_version_file = cache_dir / defaults.UPDATE_VERSION + fw_version = args.fw_version + if 'v1' not in manifest_version.get_name(): + if not fw_version: + fw_version = cache_fw_version_file.read_text() + fw_version = bump_minor(fw_version) + cache_fw_version_file.write_text(fw_version) + logger.info('FW version: %s', fw_version) + else: + assert fw_version is not None + logger.info('FW version: %d', fw_version) + + manifest_bin = create_dev_manifest( + dev_cfg=dev_cfg, + manifest_version=manifest_version, + vendor_data_path=args.vendor_data, + payload_path=args.payload_path, + payload_url=args.payload_url, + priority=args.priority, + fw_version=fw_version, + sign_image=getattr(args, 'sign_image', False), + component=getattr(args, 'component_name', None) + ) + + with args.output as fh: + fh.write(manifest_bin) diff --git a/manifesttool/dev_tool/actions/init.py b/manifesttool/dev_tool/actions/init.py new file mode 100644 index 0000000..ca6e149 --- /dev/null +++ b/manifesttool/dev_tool/actions/init.py @@ -0,0 +1,379 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import argparse +import datetime +import logging +import re +import time +import uuid +from pathlib import Path + +import yaml +from cryptography import x509 +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec + +from manifesttool import __version__ +from manifesttool.dev_tool import defaults +from manifesttool.mtool import ecdsa_helper + +SCRIPT_DIR = Path(__file__).resolve().parent + +logger = logging.getLogger('manifest-dev-tool-init') + + +def _domain_factory(domain): + if not re.match(r'^\S+\.\S+$', domain): + raise argparse.ArgumentTypeError( + 'invalid vendor domain - {}'.format(domain)) + return domain + + +def register_parser(parser: argparse.ArgumentParser): + parser.add_argument( + '-f', '--force', + action='store_true', + help='Overwrite credentials and configuration files if found. ' + '[Default: False]' + ) + + parser.add_argument( + '--cache-dir', + help='Cache directory for preserving the state between "init" ' + 'and "update" or "create" command invocations. ' + '[Default: {}]'.format(defaults.BASE_PATH), + type=Path, + default=defaults.BASE_PATH + ) + + service = parser.add_argument_group( + 'optional arguments (Pelion Device Management service configuration)') + if defaults.PELION_GW: + service.add_argument( + '-p', '--gw-preset', + help='API GW preset name specify GW URL and API key', + choices=defaults.PELION_GW.keys() + ) + service.add_argument( + '-a', '--api-key', + help='API key for for accessing Pelion Device Management service.' + ) + service.add_argument( + '-u', '--api-url', + help='Pelion Device Management API gateway URL. ' + ) + + parser.add_argument( + '-g', '--generated-resource', + help='Generated update resource C file. ' + '[Default: {}]'.format(defaults.UPDATE_RESOURCE_C), + type=Path, + default=defaults.UPDATE_RESOURCE_C + ) + + +def chunks(arr, num_of_elements): + for i in range(0, len(arr), num_of_elements): + yield arr[i:i + num_of_elements] + + +def format_rows(arr): + for _slice in chunks(arr, 8): + yield ', '.join(['0x{:02X}'.format(x) for x in _slice]) + + +def pretty_print(arr): + return ',\n '.join(list(format_rows(arr))) + + +def generate_update_default_resources_c( + c_source: Path, + vendor_id: uuid.UUID, + class_id: uuid.UUID, + private_key_file: Path, + certificate_file: Path, + do_overwrite: bool +): + """ + Generate update resources C source file for developer convenience. + + :param c_source: generated C source file + :param vendor_id: vendor UUID + :param class_id: class UUID + :param private_key_file: private key file + :param certificate_file: update certificate file + :param do_overwrite: do overwrite existing file + """ + + if c_source.is_file() and not do_overwrite: + logger.info('%s - exists', c_source) + return + + vendor_id_str = pretty_print(vendor_id.bytes) + class_id_str = pretty_print(class_id.bytes) + + cert_data = certificate_file.read_bytes() + + cert_str = pretty_print(cert_data) + + template = (SCRIPT_DIR / 'code_template.txt').read_text() + + public_key = ecdsa_helper.public_key_from_private( + private_key_file.read_bytes()) + public_key_bytes = ecdsa_helper.public_key_to_bytes(public_key) + update_public_key_str = pretty_print(public_key_bytes) + + c_source.write_text( + template.format( + vendor_id=vendor_id_str, + class_id=class_id_str, + cert=cert_str, + timestamp=time.strftime("%Y-%m-%d %H:%M:%S %Z"), + tool='manifest-dev-tool init', + version=__version__, + update_pub_key=update_public_key_str + ) + ) + logger.info('generated update source %s', c_source) + + +def generate_credentials( + key_file, + certificate_file, + do_overwrite, + cred_valid_time +): + """ + Generate developer credentials + + :param key_file: Path - .pem signing key file + :param certificate_file: Path - .der public key certificate file + :param do_overwrite: bool - if True - overwrite existing credentials + :param cred_valid_time: int - x.509 certificate validity period + :return True when credentials were changed or generated, False otherwise + """ + + if not do_overwrite: + if key_file.is_file() and certificate_file.is_file(): + logger.info('credentials exists') + return False + + if key_file.is_file() != certificate_file.is_file(): + raise AssertionError( + 'Illegal state key pair is incomplete - execute again with ' + 'force flag. \n' + '\t{k_file} - {k_status}\n' + '\t{c_file} - {c_status}'.format( + k_file=key_file.as_posix(), + k_status='ok' if key_file.is_file() else 'missing', + c_file=certificate_file.as_posix(), + c_status='ok' if certificate_file.is_file() else 'missing' + ) + ) + try: + logger.info('generating dev-credentials') + key = ec.generate_private_key(ec.SECP256R1(), default_backend()) + + # For a self-signed certificate the + # subject and issuer are always the same. + subject_list = [ + x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, 'localhost')] + + subject = issuer = x509.Name(subject_list) + + subject_key = key.public_key().public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo + ) + hash_ctx = hashes.Hash(hashes.SHA256(), backend=default_backend()) + hash_ctx.update(subject_key) + key_digest = hash_ctx.finalize() + + subject_key_identifier = key_digest[:160 // 8] # Use RFC7093, Method 1 + + cert = x509.CertificateBuilder().subject_name( + subject + ).issuer_name( + issuer + ).public_key( + key.public_key() + ).serial_number( + x509.random_serial_number() + ).not_valid_before( + datetime.datetime.utcnow() + ).not_valid_after( + datetime.datetime.utcnow() + datetime.timedelta( + days=cred_valid_time) + ).add_extension( + x509.KeyUsage( + digital_signature=True, + content_commitment=False, + key_encipherment=False, + data_encipherment=False, + key_agreement=False, + key_cert_sign=False, + crl_sign=False, + encipher_only=False, + decipher_only=False), + critical=False + ).add_extension( + x509.SubjectAlternativeName([x509.DNSName(u"localhost")]), + critical=False, + ).add_extension( + x509.ExtendedKeyUsage([x509.oid.ExtendedKeyUsageOID.CODE_SIGNING]), + critical=False, + ).add_extension( + x509.SubjectKeyIdentifier(subject_key_identifier), + critical=False, + # Sign our certificate with our private key + ).sign(key, hashes.SHA256(), default_backend()) + + key_file.parent.mkdir(parents=True, exist_ok=True) + key_file.write_bytes( + key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.TraditionalOpenSSL, + encryption_algorithm=serialization.NoEncryption() + ) + ) + logger.info('created %s', key_file) + + certificate_file.parent.mkdir(parents=True, exist_ok=True) + certificate_file.write_bytes( + cert.public_bytes(serialization.Encoding.DER)) + + logger.info('created %s', certificate_file) + + logger.info('dev-credentials - generated') + + except ValueError: + logger.error('failed to generate dev-credentials') + + if key_file.is_file(): + key_file.unlink() + if certificate_file.is_file(): + certificate_file.unlink() + raise + return True + + +def generate_developer_config( + key_file: Path, + certificate_file: Path, + config, + do_overwrite +): + if config.is_file() and not do_overwrite: + logger.info('developer config exists') + with config.open() as fh: + cfg_data = yaml.safe_load(fh) + return ( + False, + uuid.UUID(cfg_data['vendor-id']), + uuid.UUID(cfg_data['class-id']) + ) + + vendor_id = uuid.uuid4() + class_id = uuid.uuid4() + + cfg_data = { + 'key_file': key_file.as_posix(), + 'certificate': certificate_file.as_posix(), + 'class-id': class_id.bytes.hex(), + 'vendor-id': vendor_id.bytes.hex(), + } + + config.parent.mkdir(parents=True, exist_ok=True) + with config.open('wt') as fh: + yaml.dump(cfg_data, fh) + + logger.info('generated developer config file %s', config) + return True, vendor_id, class_id + + +def generate_service_config(api_key: str, api_url: str, api_config_path: Path): + cfg = dict() + + if api_key is None and api_url is None: + return + + if api_config_path.is_file(): + with api_config_path.open('rt') as fh: + cfg = yaml.safe_load(fh) + + if api_key: + cfg['api_key'] = api_key + + if api_url: + cfg['host'] = api_url + + with api_config_path.open('wt') as fh: + yaml.safe_dump(cfg, fh) + + +def entry_point(args): + + cache_dir = args.cache_dir + cache_dir.mkdir(parents=True, exist_ok=True) + + is_credentials_updated = generate_credentials( + key_file=cache_dir / defaults.UPDATE_PRIVATE_KEY, + certificate_file=cache_dir / defaults.UPDATE_PUBLIC_KEY_CERT, + do_overwrite=args.force, + cred_valid_time=365 * 20 # years + ) + + is_cfg_updated, vendor_id, class_id = generate_developer_config( + key_file=cache_dir / defaults.UPDATE_PRIVATE_KEY, + certificate_file=cache_dir / defaults.UPDATE_PUBLIC_KEY_CERT, + config=cache_dir / defaults.DEV_CFG, + do_overwrite=args.force + ) + + generate_update_default_resources_c( + c_source=args.generated_resource, + vendor_id=vendor_id, + class_id=class_id, + private_key_file=cache_dir / defaults.UPDATE_PRIVATE_KEY, + certificate_file=cache_dir / defaults.UPDATE_PUBLIC_KEY_CERT, + do_overwrite=is_credentials_updated or is_cfg_updated + ) + api_key = args.api_key + if not api_key and hasattr(args, 'gw_preset') and args.gw_preset: + api_key = defaults.PELION_GW[args.gw_preset].get('api_key') + + api_url = args.api_url + if not api_url and hasattr(args, 'gw_preset') and args.gw_preset: + api_url = defaults.PELION_GW[args.gw_preset].get('host') + + generate_service_config( + api_key=api_key, + api_url=api_url, + api_config_path=cache_dir / defaults.CLOUD_CFG + ) + + cache_fw_version_file = cache_dir / defaults.UPDATE_VERSION + if not cache_fw_version_file.is_file() or args.force: + cache_fw_version_file.write_text('0.0.1') + + (cache_dir / defaults.DEV_README).write_text( + 'Files in this directory are autogenerated by "manifest-dev-tool init"' + ' tool for internal use only.\nDo not modify.\n' + ) diff --git a/manifesttool/dev_tool/actions/update.py b/manifesttool/dev_tool/actions/update.py new file mode 100644 index 0000000..51cfcbd --- /dev/null +++ b/manifesttool/dev_tool/actions/update.py @@ -0,0 +1,384 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import argparse +import logging +import time +from pathlib import Path +from typing import Type + +import urllib3 +import yaml +from mbed_cloud.exceptions import CloudApiException +from mbed_cloud.update import UpdateAPI + +from manifesttool.dev_tool import defaults +from manifesttool.dev_tool.actions.create import bump_minor +from manifesttool.dev_tool.actions.create import create_dev_manifest +from manifesttool.mtool.actions import existing_file_path_arg_factory +from manifesttool.mtool.actions import non_negative_int_arg_factory +from manifesttool.mtool.actions import semantic_version_arg_factory +from manifesttool.mtool.asn1 import ManifestAsnCodecBase + +logger = logging.getLogger('manifest-dev-tool-update') + +# The update API has a maximum name length of 128, but this is not queryable. +MAX_NAME_LEN = 128 + +STOP_STATES = { + 'autostopped', + 'conflict', + 'expired', + 'manifestremoved', + 'quotaallocationfailed', + 'userstopped' +} + + +def register_parser(parser: argparse.ArgumentParser, schema_version: str): + + required = parser.add_argument_group('required arguments') + optional = parser.add_argument_group('optional arguments') + + required.add_argument( + '-p', '--payload-path', + help='Payload local path - for digest calculation.', + type=existing_file_path_arg_factory, + required=True + ) + + if schema_version == 'v1': + optional.add_argument( + '-v', '--fw-version', + type=non_negative_int_arg_factory, + help='FW version to be set in manifest. ' + '[Default: current timestamp]', + default=int(time.time()) + ) + else: + optional.add_argument( + '-v', '--fw-version', + type=semantic_version_arg_factory, + help='FW version to be set in manifest in Semantic ' + 'Versioning Specification format.' + ) + optional.add_argument( + '--component-name', + default='MAIN', + metavar='NAME', + help='Component name to be udpated. Must correspond to existing ' + 'components name on targeted devices' + ) + optional.add_argument( + '-m', '--sign-image', + action='store_true', + help='Sign image. Should be used when bootloader on a device ' + 'expects signed FW image.' + ) + + optional.add_argument( + '-r', '--priority', + type=non_negative_int_arg_factory, + help='Update priority >=0. [Default: 0]', + metavar='INT', + default=0 + ) + + optional.add_argument( + '-d', '--vendor-data', + help='Vendor custom data - to be passed to a device.', + type=existing_file_path_arg_factory + ) + + pdm_group = parser.add_argument_group('optional PDM portal arguments') + + pdm_group.add_argument( + '-i', '--device-id', + help='Device ID for for targeting a specific device in ' + 'update campaign filter.' + ) + + pdm_group.add_argument( + '-s', '--start-campaign', + action='store_true', + help='Start campaign automatically.' + ) + pdm_group.add_argument( + '-w', '--wait-for-completion', + dest='wait', + action='store_true', + help='Wait for campaign to finish and cleanup created resources.' + ) + pdm_group.add_argument( + '-t', '--timeout', + type=non_negative_int_arg_factory, + help='Timeout in seconds. ' + 'Only relevant in case --wait-for-completion was provided. ' + '[Default: 360sec]', + default=360 + ) + pdm_group.add_argument( + '-n', '--no-cleanup', + action='store_true', + help='Skip created service resources cleanup. ' + 'Only relevant in case --wait-for-completion was provided.' + ) + + optional.add_argument( + '--cache-dir', + help='Tool cache directory. ' + 'Must match the directory used by "init" command', + type=Path, + default=defaults.BASE_PATH + ) + + optional.add_argument( + '-h', + '--help', + action='help', + help='show this help message and exit' + ) + +def _upload_manifest(api, manifest_name, manifest_path): + try: + manifest = api.add_firmware_manifest( + name=manifest_name, + datafile=manifest_path.as_posix()) + except CloudApiException: + logger.error('Manifest upload failed') + raise + + logger.info('Uploaded Manifest ID: %s', manifest.id) + return manifest + + +def _create_campaign( + api, + campaign_name, + manifest_cloud, + vendor_id, + class_id, + device_id +): + try: + device_filter = { + 'device_class': {'$eq': class_id}, + 'vendor_id': {'$eq': vendor_id}, + } + if device_id: + device_filter['id'] = {'$eq': device_id} + campaign = api.add_campaign( + name=campaign_name, + manifest_id=manifest_cloud.id, + device_filter=device_filter, + ) + except CloudApiException: + logger.error('Campaign creation failed') + raise + logger.info('Campaign successfully created ID: %s', campaign.id) + logger.info('Current state: %s', campaign.state) + logger.debug('Filter result: %s', campaign.device_filter) + return campaign + + +def _start_campaign(api, campaign_cloud): + try: + api.start_campaign(campaign_cloud) + except CloudApiException: + logger.error('Starting campaign failed') + raise + logger.info('Started Campaign ID: %s', campaign_cloud.id) + + +def _wait(api, existing_campaign, timeout): + try: + old_state = api.get_campaign(existing_campaign.id).state + logger.info("Campaign state: %s", old_state) + current_time = time.time() + while time.time() < current_time + timeout: + campaign = api.get_campaign(existing_campaign.id) + if old_state != campaign.state: + logger.info("Campaign state: %s", campaign.state) + old_state = campaign.state + if campaign.state in STOP_STATES: + logger.info( + "Campaign is finished in state: %s", campaign.state) + return + time.sleep(1) + logger.error('Campaign timed out') + raise AssertionError('Campaign timed out') + except KeyboardInterrupt: + logger.error('Aborted by user...') + return + except CloudApiException: + logger.error('Failed to retrieve campaign status') + raise + + +def update( + payload_path: Path, + dev_cfg: dict, + manifest_version: Type[ManifestAsnCodecBase], + priority: int, + vendor_data: Path, + device_id: str, + do_wait: bool, + do_start: bool, + timeout: int, + skip_cleanup: bool, + service_config: Path, + fw_version: str, + sign_image: bool, + component: str +): + config = None + if service_config.is_file(): + with service_config.open('rt') as fh: + config = yaml.safe_load(fh) + + api = UpdateAPI(config) + manifest_path = None + payload_cloud = None + manifest_cloud = None + campaign_cloud = None + try: + timestamp = time.strftime('%Y_%m_%d-%H_%M_%S') + payload_cloud = _upload_payload( + api, + payload_name='{timestamp}-{filename}'.format( + filename=payload_path.name, + timestamp=timestamp), + payload_path=payload_path + ) + + manifest_data = create_dev_manifest( + dev_cfg=dev_cfg, + manifest_version=manifest_version, + vendor_data_path=vendor_data, + payload_path=payload_path, + payload_url=payload_cloud.url, + priority=priority, + fw_version=fw_version, + sign_image=sign_image, + component=component + ) + + manifest_name = 'manifest-{timestamp}-{filename}'.format( + filename=payload_path.name, + timestamp=timestamp) + manifest_path = payload_path.parent / manifest_name + + manifest_path.write_bytes(manifest_data) + + manifest_cloud = _upload_manifest(api, manifest_name, manifest_path) + + campaign_name = 'campaign-{timestamp}-{filename}'.format( + filename=payload_path.name, + timestamp=timestamp) + + campaign_cloud = _create_campaign( + api, + campaign_name, + manifest_cloud, + dev_cfg['vendor-id'], + dev_cfg['class-id'], + device_id + ) + + if do_start: + _start_campaign(api, campaign_cloud) + + if do_wait: + _wait(api, campaign_cloud, timeout) + + finally: + if not skip_cleanup and do_wait: + try: + logger.info('Cleaning up resources.') + if campaign_cloud: + logger.info('Deleting campaign %s', campaign_cloud.id) + api.delete_campaign(campaign_cloud.id) + if manifest_cloud: + logger.info('Deleting FW manifest %s', manifest_cloud.id) + api.delete_firmware_manifest(manifest_cloud.id) + if payload_cloud: + logger.info('Deleting FW image %s', payload_cloud.id) + api.delete_firmware_image(payload_cloud.id) + if manifest_path and manifest_path.is_file(): + manifest_path.unlink() + except CloudApiException: + logger.error('Failed to cleanup resources') + + +def _upload_payload(api, payload_name, payload_path): + try: + logger.info('Uploading FW payload %s', payload_path.as_posix()) + payload = api.add_firmware_image( + name=payload_name, + datafile=payload_path.as_posix() + ) + except (CloudApiException, urllib3.exceptions.MaxRetryError): + logger.error('Payload upload failed') + logger.error('Failed to establish connection to API-GW') + logger.error('Check API server URL "%s"', api.config["host"]) + raise + logger.info('Uploaded FW payload %s', payload.url) + return payload + + +def entry_point( + args, + manifest_version: Type[ManifestAsnCodecBase] +): + + cache_dir = args.cache_dir + + if not cache_dir.is_dir(): + raise AssertionError('Tool cache directory is missing. ' + 'Execute "init" command to create it.') + + with (cache_dir / defaults.DEV_CFG).open('rt') as fh: + dev_cfg = yaml.safe_load(fh) + + cache_fw_version_file = cache_dir / defaults.UPDATE_VERSION + fw_version = args.fw_version + if 'v1' not in manifest_version.get_name(): + if not fw_version: + fw_version = cache_fw_version_file.read_text() + fw_version = bump_minor(fw_version) + cache_fw_version_file.write_text(fw_version) + logger.info('FW version: %s', fw_version) + else: + assert fw_version is not None + logger.info('FW version: %d', fw_version) + + update( + payload_path=args.payload_path, + dev_cfg=dev_cfg, + manifest_version=manifest_version, + priority=args.priority, + vendor_data=args.vendor_data, + device_id=args.device_id, + do_start=args.start_campaign or args.wait, + do_wait=args.wait, + timeout=args.timeout, + skip_cleanup=args.no_cleanup, + service_config=cache_dir / defaults.CLOUD_CFG, + fw_version=fw_version, + sign_image=getattr(args, 'sign_image', False), + component=getattr(args, 'component_name', None) + ) diff --git a/manifesttool/dev_tool/defaults.py b/manifesttool/dev_tool/defaults.py new file mode 100644 index 0000000..a6bc957 --- /dev/null +++ b/manifesttool/dev_tool/defaults.py @@ -0,0 +1,35 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +from pathlib import Path + +import yaml +BASE_PATH = Path('.manifest-dev-tool') +UPDATE_PUBLIC_KEY_CERT = 'dev.cert.der' +UPDATE_PRIVATE_KEY = 'dev.key.pem' +DEV_CFG = 'dev.cfg.yaml' +UPDATE_RESOURCE_C = 'update_default_resources.c' +CLOUD_CFG = 'dev.cloud_cfg.yaml' +DEV_README = 'README.txt' +API_GW = 'https://api.us-east-1.mbedcloud.com' +UPDATE_VERSION = 'update.version.txt' + +PELION_GW_PATH = Path.home() / '.pelion-dev-presets.yaml' +PELION_GW = None +if PELION_GW_PATH.is_file(): + with PELION_GW_PATH.open('rb') as fh: + PELION_GW = yaml.safe_load(fh) diff --git a/manifesttool/dev_tool/dev_tool.py b/manifesttool/dev_tool/dev_tool.py new file mode 100644 index 0000000..ee18a3c --- /dev/null +++ b/manifesttool/dev_tool/dev_tool.py @@ -0,0 +1,144 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +import argparse +import enum +import logging +import sys + +from manifesttool import __version__ +from manifesttool.dev_tool.actions import create +from manifesttool.dev_tool.actions import init, update +from manifesttool.mtool.asn1.v1 import ManifestAsnCodecV1 +from manifesttool.mtool.asn1.v3 import ManifestAsnCodecV3 + +logger = logging.getLogger('manifest-dev-tool') + + +class DevActions(enum.Enum): + INIT = 'init' + + CREATE = 'create' + CREATE_V1 = 'create-v1' + + UPDATE = 'update' + UPDATE_V1 = 'update-v1' + + +def get_parser(): + parser = argparse.ArgumentParser( + description='FOTA developer flow helper' + ) + + actions_parser = parser.add_subparsers(dest='action') + actions_parser.required = True + + init_parser = actions_parser.add_parser( + DevActions.INIT.value, + help='Create a Pelion Device management update certificate.' + ) + init.register_parser(init_parser) + + create_parser = actions_parser.add_parser( + DevActions.CREATE.value, + help='Helper tool for creating a manifest using manifest schema ' + 'version v3.', + add_help=False + ) + create.register_parser(create_parser, ManifestAsnCodecV3.get_name()) + + create_parser = actions_parser.add_parser( + DevActions.CREATE_V1.value, + help='Helper tool for creating a manifest using manifest schema ' + 'version v1.', + add_help=False + ) + create.register_parser(create_parser, ManifestAsnCodecV1.get_name()) + + update_parser = actions_parser.add_parser( + DevActions.UPDATE.value, + help='Perform Pelion Device management update operations using ' + 'manifest schema version v3.', + add_help=False + ) + update.register_parser(update_parser, ManifestAsnCodecV3.get_name()) + + update_parser = actions_parser.add_parser( + DevActions.UPDATE_V1.value, + help='Perform Pelion Device management update operations using ' + 'manifest schema version v1', + add_help=False + ) + update.register_parser(update_parser, ManifestAsnCodecV1.get_name()) + + parser.add_argument( + '--debug', + action='store_true', + help='Show exception info on error.' + ) + + parser.add_argument( + '--version', + action='version', + version='Manifest-Tool version {}'.format(__version__) + + ) + + return parser + + +def entry_point(argv=sys.argv[1:]): # pylint: disable=dangerous-default-value + parser = get_parser() + args = parser.parse_args(argv) + + logging.basicConfig( + stream=sys.stdout, + format='%(asctime)s %(levelname)s %(message)s', + level=logging.DEBUG if args.debug else logging.INFO + ) + try: + action = DevActions(args.action) + + if action == DevActions.INIT: + init.entry_point(args) + # --------------------------------------------------------------------- + elif action == DevActions.CREATE: + create.entry_point(args, ManifestAsnCodecV3) + elif action == DevActions.CREATE_V1: + create.entry_point(args, ManifestAsnCodecV1) + # --------------------------------------------------------------------- + elif action == DevActions.UPDATE: + update.entry_point(args, ManifestAsnCodecV3) + elif action == DevActions.UPDATE_V1: + update.entry_point(args, ManifestAsnCodecV1) + # --------------------------------------------------------------------- + else: + raise AssertionError('unknown action') + except Exception as ex: # pylint: disable=broad-except + if args.debug: + raise + logger.error( + str(ex), + exc_info=args.debug + ) + return 1 + return 0 + + +if __name__ == '__main__': + raise SystemExit(entry_point()) diff --git a/manifesttool/init.py b/manifesttool/init.py deleted file mode 100644 index 33ed914..0000000 --- a/manifesttool/init.py +++ /dev/null @@ -1,344 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -from __future__ import print_function, division -from builtins import input, bytes, chr -import os, sys, json, logging, uuid, re -import binascii -from manifesttool import defaults, cert, utils, templates -from manifesttool.argparser import MainArgumentParser -from cryptography import x509 -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.backends import default_backend - -LOG = logging.getLogger(__name__) - -def writeUpdateDefaults(options): - if os.path.isfile(defaults.updateResources) and not (hasattr(options, 'force') and options.force): - LOG.warning('{} already exists, not overwriting. Use --force to write anyway.'.format(defaults.updateResources)) - return - with open(defaults.updateResources, 'w') as defaultResources: - # Format the device UUIDs - vendorId = ', '.join(['0x%x' % x for x in bytes(uuid.UUID(options.vendor_id).bytes)]) - classId = ', '.join(['0x%x' % x for x in bytes(uuid.UUID(options.class_id).bytes)]) - - certFp = '' - cert = '' - str_ski = '' - # Read the certificate - if not hasattr(options, 'psk') or not options.psk: - options.certificate.seek(0) - cstr = options.certificate.read() - try: - # Load the certificate. - certObj = x509.load_der_x509_certificate( - cstr, - default_backend() - ) - except ValueError as e: - raise ValueError('Error loading {}: {}'.format(options.certificate.name, e.message)) - # Calculate the certificate fingerprint - c_hash = certObj.fingerprint(hashes.SHA256()) - # Format the certificate fingerprint - certFp = ', '.join(['0x%x' % x for x in bytes(c_hash[:16])]) + ',\n ' + ', '.join(['0x%x' % x for x in bytes(c_hash[16:])]) - - # Calculate the subjectKeyIdentifier - try: - c_ski = certObj.extensions.get_extension_for_oid(x509.oid.ExtensionOID.SUBJECT_KEY_IDENTIFIER).value.digest - str_ski = ', '.join(['0x%x' % x for x in bytes(c_ski[:16])]) + ',\n ' + ', '.join(['0x%x' % x for x in bytes(c_ski[16:])]) - except x509.ExtensionNotFound as e: - LOG.warning('No Subject Key Identifier present in certificate') - - # Format the certificate - CByteArray = [ '0x%x'% x for x in bytes(cstr)] - CLineList = [ ', '.join(CByteArray[i:i+16]) for i in range(0,len(CByteArray),16)] - cert = ',\n '.join(CLineList) - - defaultResources.write(templates.UpdateDefaultResources.format( - vendorId = vendorId, - classId = classId, - certFp = certFp, - ski = str_ski, - cert = cert, - psk = ', '.join(['0x%x'%x for x in bytes(options.psk)]), - pskId = ', '.join(['0x%x'%x for x in bytes(options.psk_id)]) - )) - LOG.info('Wrote default resource values to {}'.format(defaults.updateResources)) - -def mkCert(options): - cmd = ['cert', 'create', '-o', defaults.certificate, '-K', defaults.certificateKey] - - country = '' - state = '' - locality = '' - organization = '' - commonName = '' - if hasattr(options, 'vendor_domain') and options.vendor_domain: - commonName = options.vendor_domain - validity = defaults.certificateDuration - - if not options.quiet: - print('A certificate has not been provided to init, and no certificate is provided in {cert}'.format( - cert=defaults.certificate)) - print('Init will now guide you through the creation of a certificate.') - print() - print('This process will create a self-signed certificate, which is not suitable for production use.') - print() - print('In the terminology used by certificates, the "subject" means the holder of the private key that matches a certificate.') - country = input('In which country is the subject located? ').strip() - state = input('In which state or province is the subject located? ').strip() - locality = input('In which city or region is the subject located? ').strip() - organization = input('What is the name of the subject organization? ').strip() - commonName = '' - if hasattr(options, 'vendor_domain') and options.vendor_domain: - commonName = input('What is the common name of the subject organization? [{}]'.format(options.vendor_domain)).strip() or options.vendor_domain - else: - commonName = input('What is the common name of the subject organization? ') - validity = input('How long (in days) should the certificate be valid? [{}]'.format(defaults.certificateDuration)).strip() or defaults.certificateDuration - - try: - os.makedirs(defaults.certificatePath) - except os.error: - # It is okay if the directory already exists. If something else went wrong, we'll find out when the - # create occurs - pass - - cmd = ['cert', 'create', '-o', defaults.certificate, '-K', defaults.certificateKey, - '-V', str(validity)] - if country: - cmd += ['-C', country] - if state: - cmd += ['-S', state] - if locality: - cmd += ['-L', locality] - if organization: - cmd += ['-O', organization] - if commonName: - cmd += ['-U', commonName] - cert_opts = MainArgumentParser().parse_args(cmd).options - rc = cert.main(cert_opts) - if rc: - sys.exit(1) - options.certificate = open(defaults.certificate, 'rb') - LOG.info('Certificate written to {}'.format(defaults.certificate)) - options.private_key = open(defaults.certificateKey, 'rb') - LOG.info('Private key written to {}'.format(defaults.certificateKey)) - -def checkURN(deviceURN): - URNsplit = deviceURN.split(':') - if len(URNsplit) < 3 or URNsplit[0] != 'urn': - raise ValueError('PSK Identity does not appear to be a valid URN: {!r}'.format(deviceURN)) - if URNsplit[1] not in ['dev', 'uuid', 'imei', 'esn', 'meid', 'imei-msisdn', 'imei-imsi']: - raise ValueError('{!r} is not a recommended URN class for PSK identities') - if URNsplit[1] == 'dev' and URNsplit[2] != 'ops': - raise ValueError('ops-type URNs are recommended dev-class URNs for PSK identities') - -def findDevCertFiles(textPattern, directorySearchPaths, searchExtension): - IdentityFiles = [] - AllSourceFiles = [] - for path in directorySearchPaths: - if os.path.isdir(path): - for file in os.listdir(path): - if file.endswith(searchExtension): - AllSourceFiles.append(os.path.join(path,file)) - for file in AllSourceFiles: - with open(file, 'rt') as fd: - for line in fd: - if textPattern in line: - IdentityFiles.append(file) - if len(IdentityFiles) > 1: - raise ValueError('Multiple Endpoint Name definitions found!') - sys.exit(1) - else: - if len(IdentityFiles) == 1: - return IdentityFiles[0] - else: - return '' - - -def main(options): - - settings = {} - # Check if a settings file exists - if os.path.isfile(defaults.config): - # load default settings - with open(defaults.config,'r') as f: - settings = json.load(f) - # Populate a default list of PSKIdentities - PSKIdentities = settings.get('deviceURNs', []) - - if hasattr(options, 'vendor_domain') and options.vendor_domain: - domainParts = options.vendor_domain.split('.') - minPart = min(domainParts) - if len(domainParts) < 2 or len(minPart) < 1: - LOG.critical('"{0}" is not a valid domain name.'.format(options.vendor_domain)) - return 1 - options.vendor_id = str(uuid.uuid5(uuid.NAMESPACE_DNS, options.vendor_domain)) - vendorId = uuid.UUID(options.vendor_id) - - if hasattr(options, 'model_name') and options.model_name: - options.class_id = str(uuid.uuid5(vendorId, options.model_name)) - classId = uuid.UUID(options.class_id) - - if hasattr(options, 'psk') and options.psk: - # Attempt to read the device endpoint name out of mbed_cloud_dev_credentials.c - deviceURN = None - try: - dev_credential_dirs = ['.','source'] - dev_cred_file_name = findDevCertFiles('MBED_CLOUD_DEV_BOOTSTRAP_ENDPOINT_NAME', dev_credential_dirs, '.c') - with open(dev_cred_file_name, 'rt') as fd: - URNLine = None - for line in fd: - if 'MBED_CLOUD_DEV_BOOTSTRAP_ENDPOINT_NAME' in line: - URNLine = line - break - if URNLine: - m = re.search('const\s+char\s+MBED_CLOUD_DEV_BOOTSTRAP_ENDPOINT_NAME\\[\\]\s*=\s*"([^"]*)";', URNLine) - if m: - deviceURN = m.group(1) - except IOError: - # Handle missing file - pass - # A device URN is mandatory for psk init. The URN can come from either - # the list in .manifest_tool.json or from the command-line. It is - # debatable whether init should be used if the .manifest_tool.json is - # already populated, since the purpose of manifest-tool init is to fill - # in .manifest_tool.json. - if not deviceURN and len(PSKIdentities) == 0: - LOG.critical('An endpoint name must be populated in mbed_cloud_dev_credentials.c') - return 1 - if deviceURN == '0': - LOG.critical('An endpoint name in mbed_cloud_dev_credentials.c must be initialized (not \'0\') and must be different for each device.') - return 1 - if deviceURN in PSKIdentities: - LOG.warning('Device URN %r already exists in .manifest-tool.json. Is it unique?', deviceURN) - - try: - checkURN(deviceURN) - except ValueError as e: - LOG.warning('%s', str(e)) - - # Append the device URN extracted from the credentials file to the current list - PSKIdentities.append(deviceURN) - # Install the device URN extracted from the credentials file into the options object for - # use in generating template files - options.device_urn = deviceURN - masterKey = None - masterKeyRequired = not hasattr(options, 'master_key') or not options.master_key - if masterKeyRequired: - try: - # Open and store to master_key since this matches what argparse is doing - options.master_key = open(defaults.pskMasterKey, 'rb') - masterKeyRequired = False - if options.force: - LOG.warning("Using existing master key in %r. Not generating a new master key.", - defaults.pskMasterKey) - except: - masterKeyRequired = True - - if masterKeyRequired: - LOG.info('Generating a new 256-bit master key') - masterKey = os.urandom(256//8) - masterKeyName = defaults.pskMasterKey - try: - os.makedirs(defaults.certificatePath) - except os.error: - # It is okay if the directory already exists. If something else went wrong, we'll find out when the - # create occurs - pass - # Open and store to master_key since this matches what argparse is doing - options.master_key = open(masterKeyName,'wb') - LOG.info('Storing master key to %r', options.master_key.name) - options.master_key.write(masterKey) - options.master_key.flush() - options.master_key.seek(0) - else: - LOG.info('Reading master key out of {}'.format(options.master_key.name)) - masterKey = options.master_key.read() - - # Generate the device PSK - shaMaster = hashes.Hash(hashes.SHA256(), default_backend()) - shaMaster.update(masterKey) - options.psk_id = shaMaster.finalize() - psk_hkdf = utils.getDevicePSK_HKDF('none-psk-aes-128-ccm-sha256', masterKey, vendorId.bytes, classId.bytes, b'Authentication') - options.psk = psk_hkdf.derive(bytes(options.device_urn, 'utf-8')) - - else: - cert_required = True - options.psk_id = bytes('', 'utf-8') - options.psk = bytes('', 'utf-8') - options.device_urn = '' - if options.certificate: - cert_required = False - elif hasattr(options,'force') and options.force: - cert_required = True - else: - try: - options.certificate = open(defaults.certificate,'rb') - options.private_key = open(defaults.certificateKey, 'rb') - cert_required = False - except: - cert_required = True - - if cert_required: - mkCert(options) - # Write the settings - - settings = { - 'classId' : str(classId), - 'vendorId' : str(vendorId), - 'vendorDomain' : options.vendor_domain, - 'modelName' : options.model_name, - 'deviceURNs' : list(set(PSKIdentities)) - } - - if hasattr(options, 'psk') and options.psk: - settings['psk-master-key'] = options.master_key.name - elif hasattr(options, 'signing_tool') and options.signing_tool: - settings['signing-tool'] = options.signing_tool.name - if not hasattr(options, 'signing_key_id') or not options.signing_key_id: - LOG.critical('Signing key ID is required with signing tool.') - return 1 - settings['signing-key-id'] = options.signing_key_id - settings['default-certificates'] = [ {'file':options.certificate.name}] - else: - settings['private-key'] = options.private_key.name - settings['default-certificates'] = [ {'file':options.certificate.name}] - - with open(defaults.config, 'w') as f: - f.write(json.dumps(settings, sort_keys=True, indent=4)) - LOG.info('Default settings written to {}'.format(defaults.config)) - - try: - writeUpdateDefaults(options) - except ValueError as e: - LOG.critical('Error setting defaults: {}'.format(e.message)) - return 1 - - cloud_settings = {} - if hasattr(options, 'server_address') and options.server_address: - cloud_settings['host'] = options.server_address - if hasattr(options, 'api_key') and options.api_key: - cloud_settings['api_key'] = options.api_key - - if cloud_settings: - with open(defaults.cloud_config, 'w') as f: - f.write(json.dumps(cloud_settings, sort_keys=True, indent=4)) - LOG.info('Cloud settings written to {}'.format(defaults.cloud_config)) - - return 0 diff --git a/manifesttool/keytable.proto b/manifesttool/keytable.proto deleted file mode 100644 index 854dd1f..0000000 --- a/manifesttool/keytable.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; - -package pskManifest; -message DeviceEntry { - string urn = 1; - bytes opaque = 2; -}; -message KeyTable { - repeated DeviceEntry entries = 1; -} diff --git a/manifesttool/keytable_pb2.py b/manifesttool/keytable_pb2.py deleted file mode 100644 index b442d13..0000000 --- a/manifesttool/keytable_pb2.py +++ /dev/null @@ -1,116 +0,0 @@ -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: keytable.proto - -import sys -_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database -from google.protobuf import descriptor_pb2 -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - - - -DESCRIPTOR = _descriptor.FileDescriptor( - name='keytable.proto', - package='pskManifest', - syntax='proto3', - serialized_pb=_b('\n\x0ekeytable.proto\x12\x0bpskManifest\"*\n\x0b\x44\x65viceEntry\x12\x0b\n\x03urn\x18\x01 \x01(\t\x12\x0e\n\x06opaque\x18\x02 \x01(\x0c\"5\n\x08KeyTable\x12)\n\x07\x65ntries\x18\x01 \x03(\x0b\x32\x18.pskManifest.DeviceEntryb\x06proto3') -) - - - - -_DEVICEENTRY = _descriptor.Descriptor( - name='DeviceEntry', - full_name='pskManifest.DeviceEntry', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='urn', full_name='pskManifest.DeviceEntry.urn', index=0, - number=1, type=9, cpp_type=9, label=1, - has_default_value=False, default_value=_b("").decode('utf-8'), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - _descriptor.FieldDescriptor( - name='opaque', full_name='pskManifest.DeviceEntry.opaque', index=1, - number=2, type=12, cpp_type=9, label=1, - has_default_value=False, default_value=_b(""), - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=31, - serialized_end=73, -) - - -_KEYTABLE = _descriptor.Descriptor( - name='KeyTable', - full_name='pskManifest.KeyTable', - filename=None, - file=DESCRIPTOR, - containing_type=None, - fields=[ - _descriptor.FieldDescriptor( - name='entries', full_name='pskManifest.KeyTable.entries', index=0, - number=1, type=11, cpp_type=10, label=3, - has_default_value=False, default_value=[], - message_type=None, enum_type=None, containing_type=None, - is_extension=False, extension_scope=None, - options=None, file=DESCRIPTOR), - ], - extensions=[ - ], - nested_types=[], - enum_types=[ - ], - options=None, - is_extendable=False, - syntax='proto3', - extension_ranges=[], - oneofs=[ - ], - serialized_start=75, - serialized_end=128, -) - -_KEYTABLE.fields_by_name['entries'].message_type = _DEVICEENTRY -DESCRIPTOR.message_types_by_name['DeviceEntry'] = _DEVICEENTRY -DESCRIPTOR.message_types_by_name['KeyTable'] = _KEYTABLE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -DeviceEntry = _reflection.GeneratedProtocolMessageType('DeviceEntry', (_message.Message,), dict( - DESCRIPTOR = _DEVICEENTRY, - __module__ = 'keytable_pb2' - # @@protoc_insertion_point(class_scope:pskManifest.DeviceEntry) - )) -_sym_db.RegisterMessage(DeviceEntry) - -KeyTable = _reflection.GeneratedProtocolMessageType('KeyTable', (_message.Message,), dict( - DESCRIPTOR = _KEYTABLE, - __module__ = 'keytable_pb2' - # @@protoc_insertion_point(class_scope:pskManifest.KeyTable) - )) -_sym_db.RegisterMessage(KeyTable) - - -# @@protoc_insertion_point(module_scope) diff --git a/manifesttool/mtool/__init__.py b/manifesttool/mtool/__init__.py new file mode 100644 index 0000000..0ef1083 --- /dev/null +++ b/manifesttool/mtool/__init__.py @@ -0,0 +1,17 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- diff --git a/manifesttool/mtool/actions/__init__.py b/manifesttool/mtool/actions/__init__.py new file mode 100644 index 0000000..bdf5df5 --- /dev/null +++ b/manifesttool/mtool/actions/__init__.py @@ -0,0 +1,68 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import argparse +import re +from pathlib import Path +from typing import List + + +def non_negative_int_arg_factory(value: str) -> int: + """ + Construct non negative integer value for an argument + :param value: input string + :return: integer value + """ + prospective = None + try: + prospective = int(value) + except ValueError: + pass + if prospective is None or prospective < 0: + raise argparse.ArgumentTypeError( + '"{}" is an invalid non-negative integer value'.format(value)) + return prospective + + +def semantic_version_arg_factory(value) -> str: + """ + Construct major, minor, split tuple for an argument + :param value: input string + :return: str + """ + nibble = '([0-9]|[1-9][0-9]{0,2})' + pattern = r'\.'.join([nibble, nibble, nibble]) + match = re.match(pattern, value) + if not match: + raise argparse.ArgumentTypeError( + '{} is an invalid SemVer. Expecting following pattern {}'.format( + value, pattern)) + return value + + +def existing_file_path_arg_factory(value): + """ + Construct Path to an existing file for an argument + :param value: input string + :return: major, minor, split tuple + """ + prospective = Path(value) + if not prospective.is_file(): + raise argparse.ArgumentTypeError( + 'File "{}" is not found'.format(value) + ) + return prospective diff --git a/manifesttool/mtool/actions/create.py b/manifesttool/mtool/actions/create.py new file mode 100644 index 0000000..9e0f23a --- /dev/null +++ b/manifesttool/mtool/actions/create.py @@ -0,0 +1,161 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +import argparse +import logging +import time +from pathlib import Path +from typing import Type + +import jsonschema +import yaml + +from manifesttool.mtool.actions import existing_file_path_arg_factory +from manifesttool.mtool.actions import non_negative_int_arg_factory +from manifesttool.mtool.actions import semantic_version_arg_factory +from manifesttool.mtool.asn1 import ManifestAsnCodecBase +from manifesttool.mtool.asn1.v1 import ManifestAsnCodecV1 +from manifesttool.mtool import ecdsa_helper + +MTOOL_PATH = Path(__file__).resolve().parent.parent + + +class CreateAction: + + logger = logging.getLogger('manifest-tool-create') + + @staticmethod + def register_parser_args( + parser: argparse.ArgumentParser, schema_version: str): + required = parser.add_argument_group('required arguments') + optional = parser.add_argument_group('optional arguments') + + required.add_argument( + '-c', + '--config', + help='Manifest tool configuration file.', + metavar='YAML', + type=argparse.FileType('rb'), + required=True + ) + + required.add_argument( + '-k', + '--key', + help='Signing key in PEM format.', + metavar='KEY', + type=argparse.FileType('rb'), + required=True + ) + + required.add_argument( + '-o', + '--output', + help='Output manifest.', + type=argparse.FileType('wb'), + required=True + ) + if schema_version == 'v1': + optional.add_argument( + '-v', '--fw-version', + type=non_negative_int_arg_factory, + help='FW version to be set in manifest. ' + '[Default: current timestamp]', + default=int(time.time()) + ) + required.add_argument( + '--update-certificate', + type=existing_file_path_arg_factory, + help='Update Certificate file path.', + required=True + ) + else: + required.add_argument( + '-v', '--fw-version', + type=semantic_version_arg_factory, + help='FW version to be set in manifest in Semantic ' + 'Versioning Specification format.', + required=True + ) + + optional.add_argument( + '-h', + '--help', + action='help', + help='show this help message and exit' + ) + + @staticmethod + def do_create( + pem_key_data: bytes, + input_cfg: dict, + fw_version, + update_certificate: Path, + asn1_codec_class: Type[ManifestAsnCodecBase] + ) -> bytes: + assert fw_version is not None + + codec = asn1_codec_class() + + raw_signature = True + if isinstance(codec, ManifestAsnCodecV1): + raw_signature = False + cert_data = update_certificate.read_bytes() + codec.set_update_certificate(cert_data) + installed_digest = codec.process_input_config(fw_version, input_cfg) + + if input_cfg.get('sign-image'): + if isinstance(codec, ManifestAsnCodecV1): + raise AssertionError( + 'sign-image is unexpected for manifest schema v1') + signature = ecdsa_helper.ecdsa_sign_prehashed( + installed_digest, pem_key_data) + codec.set_image_signature( + ecdsa_helper.signature_der_to_raw(signature) + ) + else: + codec.set_image_signature(bytes()) + + der_manifest = codec.get_signed_data() + + signature = ecdsa_helper.ecdsa_sign(der_manifest, pem_key_data) + if raw_signature: + signature = ecdsa_helper.signature_der_to_raw(signature) + return codec.get_der_signed_resource(signature) + + @classmethod + def entry_point( + cls, + args: argparse.Namespace, + asn1_codec: Type[ManifestAsnCodecBase] + ) -> None: + input_cfg = yaml.safe_load(args.config) + schema_path = MTOOL_PATH / 'manifest-input-schema.json' + with schema_path.open('rb') as fh: + input_schema = yaml.safe_load(fh) + jsonschema.validate(input_cfg, input_schema) + + manifest_bin = cls.do_create( + pem_key_data=args.key.read(), + input_cfg=input_cfg, + fw_version=args.fw_version, + update_certificate=getattr(args, 'update_certificate', None), + asn1_codec_class=asn1_codec + ) + with args.output as fh: + fh.write(manifest_bin) diff --git a/manifesttool/mtool/actions/parse.py b/manifesttool/mtool/actions/parse.py new file mode 100644 index 0000000..ba8c9be --- /dev/null +++ b/manifesttool/mtool/actions/parse.py @@ -0,0 +1,140 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +import argparse +import binascii +import collections +import logging +from typing import Optional + +import yaml +from pyasn1.error import PyAsn1Error + +from manifesttool.mtool import ecdsa_helper +from manifesttool.mtool.asn1 import ManifestVersion + + +def bytes_representer(dumper: yaml.Dumper, obj): + try: + return dumper.represent_str(obj.decode('utf-8')) + except UnicodeError: + return dumper.represent_str(binascii.hexlify(obj).decode('utf-8')) + + +def ordered_dict_representer(dumper, data): + return dumper.represent_dict(data.items()) + + +yaml.Dumper.add_representer(collections.OrderedDict, ordered_dict_representer) +yaml.Dumper.add_representer(bytes, bytes_representer) + +class ParseAction: + + logger = logging.getLogger('manifest-tool-parse') + + @staticmethod + def register_parser_args(parser): + required = parser.add_argument_group('required arguments') + optional = parser.add_argument_group('optional arguments') + + required.add_argument( + 'manifest', + help='Manifest file.', + type=argparse.FileType('rb') + ) + + key_or_cert_group = optional.add_mutually_exclusive_group() + key_or_cert_group.add_argument( + '-c', '--certificate', + help='Certificate holding signing public key. ' + 'If provided certificate signature will be validated.', + type=argparse.FileType('rb') + ) + key_or_cert_group.add_argument( + '-p', '--public-key', + help='Public key in uncompressed point format (X9.62). ' + 'If provided certificate signature will be validated.', + type=argparse.FileType('rb') + ) + key_or_cert_group.add_argument( + '-k', '--private-key', + help='Private key PEM file. ' + 'If provided certificate signature will be validated.', + type=argparse.FileType('rb') + ) + + optional.add_argument( + '-h', + '--help', + action='help', + help='show this help message and exit' + ) + + # pylint: disable=too-many-branches + @classmethod + def do_parse( + cls, + manifest_data: bytes, + certificate_data: Optional[bytes], + public_key_data: Optional[bytes], + private_key_data: Optional[bytes] + ): + dom = None + + public_key = None + if private_key_data: + public_key = ecdsa_helper.public_key_from_private(private_key_data) + elif certificate_data: + try: + public_key = ecdsa_helper.public_key_from_certificate( + certificate_data) + except ValueError as ex: + raise AssertionError('Malformed certificate') from ex + elif public_key_data: + public_key = ecdsa_helper.public_key_from_bytes(public_key_data) + + for codec_class in ManifestVersion.list_codecs(): + try: + dom = codec_class.decode( + manifest_data, public_key) + break + except PyAsn1Error: + continue + if not dom: + raise AssertionError('Malformed manifest') + + logging.info( + '\n----- Manifest dump start -----\n' + '%s----- Manifest dump end -----', + yaml.dump(dom) + + ) + + @classmethod + def entry_point(cls, args): + cert_data = args.certificate.read() if args.certificate else None + public_key = args.public_key.read() if args.public_key else None + private_key = args.private_key.read() if args.private_key else None + manifest_data = args.manifest.read() + + cls.do_parse( + manifest_data=manifest_data, + certificate_data=cert_data, + public_key_data=public_key, + private_key_data=private_key + ) diff --git a/manifesttool/mtool/actions/public_key.py b/manifesttool/mtool/actions/public_key.py new file mode 100644 index 0000000..3d190a4 --- /dev/null +++ b/manifesttool/mtool/actions/public_key.py @@ -0,0 +1,49 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import argparse +from pathlib import Path + +from manifesttool.mtool import ecdsa_helper +from manifesttool.mtool.actions import existing_file_path_arg_factory + + +class PublicKeyAction: + @staticmethod + def register_parser_args(parser: argparse.ArgumentParser): + parser.add_argument( + 'key', + help='Private key PEM file', + type=existing_file_path_arg_factory + ) + + parser.add_argument( + '-o', '--out', + help='Output public key in uncompressed point format (X9.62)', + type=Path + ) + + @classmethod + def get_key(cls, private_key_bytes: bytes): + public_key = ecdsa_helper.public_key_from_private(private_key_bytes) + public_key_bytes = ecdsa_helper.public_key_to_bytes(public_key) + return public_key_bytes + + @classmethod + def entry_point(cls, args): + private_key_bytes = cls.get_key(args.key.read_bytes()) + args.out.write_bytes(private_key_bytes) diff --git a/manifesttool/mtool/actions/schema.py b/manifesttool/mtool/actions/schema.py new file mode 100644 index 0000000..3842571 --- /dev/null +++ b/manifesttool/mtool/actions/schema.py @@ -0,0 +1,35 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +from pathlib import Path + +MTOOL_PATH = Path(__file__).resolve().parent.parent + + +class PrintSchemaAction: + @staticmethod + def print_schema(): + schema_file = MTOOL_PATH / 'manifest-input-schema.json' + print(schema_file.read_text()) + + @staticmethod + def register_parser_args(parser): + pass + + @classmethod + def entry_point(cls, _): + cls.print_schema() diff --git a/manifesttool/mtool/asn1/__init__.py b/manifesttool/mtool/asn1/__init__.py new file mode 100644 index 0000000..83d32e2 --- /dev/null +++ b/manifesttool/mtool/asn1/__init__.py @@ -0,0 +1,58 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import argparse +import collections +from typing import Type + +from manifesttool.mtool.asn1 import v3, v1 +from manifesttool.mtool.asn1.manifest_codec import ManifestAsnCodecBase + + +class ManifestVersion: + VERSIONS = collections.OrderedDict( + [ + (v3.ManifestAsnCodecV3.get_name(), v3.ManifestAsnCodecV3), + (v1.ManifestAsnCodecV1.get_name(), v1.ManifestAsnCodecV1) + ] + ) + + @classmethod + def list_names(cls): + return cls.VERSIONS.keys() + + @classmethod + def list_codecs(cls): + return cls.VERSIONS.values() + + @classmethod + def from_string(cls, _str: str) -> Type[ManifestAsnCodecBase]: + return cls.VERSIONS[_str] + + @classmethod + def get_default(cls) -> Type[ManifestAsnCodecBase]: + return next(iter(cls.VERSIONS.values())) + +# pylint: disable=too-few-public-methods +class StoreManifestVersion(argparse.Action): + def __call__(self, parser, namespace, values, option_string=None): + prospective = values + try: + setattr(namespace, self.dest, + ManifestVersion.from_string(prospective)) + except KeyError: + raise argparse.ArgumentTypeError('invalid manifest schema version') diff --git a/manifesttool/defaults.py b/manifesttool/mtool/asn1/generate-python-schema.sh old mode 100644 new mode 100755 similarity index 57% rename from manifesttool/defaults.py rename to manifesttool/mtool/asn1/generate-python-schema.sh index c51b940..59de214 --- a/manifesttool/defaults.py +++ b/manifesttool/mtool/asn1/generate-python-schema.sh @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- +#!/usr/bin/env bash -e # ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates +# Copyright 2019 ARM Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0 # @@ -16,12 +16,16 @@ # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- -import os -certificatePath = '.update-certificates' -certificate = os.path.join(certificatePath,'default.der') -certificateKey = os.path.join(certificatePath,'default.key.pem') -certificateDuration = 90 -pskMasterKey = os.path.join(certificatePath,'default.master.psk') -config = '.manifest_tool.json' -cloud_config = '.mbed_cloud_config.json' -updateResources = 'update_default_resources.c' + +generate() { + local input=$1 + local output=$2 + echo "asn1ate $input > $output" + echo "# ----------------------------------------------------------------------------" > $output + cat ../../../LICENSE | sed 's/^/# /' >> $output + echo "# ----------------------------------------------------------------------------" >> $output + asn1ate $input >> $output +} + +generate v3/manifest_v3.asn v3/manifest_schema_v3.py +generate v1/manifest-1.0.0 v1/manifest_schema_v1.py \ No newline at end of file diff --git a/manifesttool/mtool/asn1/manifest_codec.py b/manifesttool/mtool/asn1/manifest_codec.py new file mode 100644 index 0000000..ab8ed60 --- /dev/null +++ b/manifesttool/mtool/asn1/manifest_codec.py @@ -0,0 +1,220 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import abc +import base64 +import hashlib +import logging +import re +import uuid +from collections import OrderedDict +from pathlib import Path +from typing import Optional +from typing import TypeVar + +import yaml +from cryptography.hazmat.primitives.asymmetric import ec + +from manifesttool.mtool.payload_format import PayloadFormat + +READ_BLOCK_SIZE = 65536 + +ManifestAsnCodecBaseType = TypeVar( + 'ManifestAsnCodecBaseType', bound='ManifestAsnCodecBase') + +logger = logging.getLogger('manifest-codec') + +class ManifestAsnCodecBase(abc.ABC): + + @abc.abstractmethod + def get_der_signed_resource(self, signature: bytes) -> bytes: + raise NotImplementedError + + @abc.abstractmethod + def get_signed_data(self) -> bytes: + raise NotImplementedError + + @classmethod + @abc.abstractmethod + def decode( + cls, + data: bytes, + verification_key: Optional[ec.EllipticCurvePublicKey] + ) -> OrderedDict: + raise NotImplementedError + + @staticmethod + @abc.abstractmethod + def get_name() -> str: + raise NotImplementedError + + @abc.abstractmethod + def set_payload_version(self, version): + raise NotImplementedError + + @abc.abstractmethod + def set_update_priority(self, priority: int): + raise NotImplementedError + + @abc.abstractmethod + def set_vendor_id(self, vendor_id: bytes): + raise NotImplementedError + + @abc.abstractmethod + def set_vendor_data(self, data: bytes): + raise NotImplementedError + + @abc.abstractmethod + def set_class_id(self, class_id: bytes): + raise NotImplementedError + + @abc.abstractmethod + def set_device_id(self, device_id: bytes): + raise NotImplementedError + + @abc.abstractmethod + def set_payload_fingerprint(self, digest: bytes, size: int): + raise NotImplementedError + + @abc.abstractmethod + def set_payload_uri(self, uri: str): + raise NotImplementedError + + @abc.abstractmethod + def set_payload_format(self, payload_format: str): + raise NotImplementedError + + @abc.abstractmethod + def set_delta_metadata( + self, + installed_digest: bytes, + installed_size: int, + precursor_digest: bytes + ): + raise NotImplementedError + + @abc.abstractmethod + def set_update_certificate(self, cert_data: bytes): + raise NotImplementedError + + @abc.abstractmethod + def set_image_signature(self, signature: bytes): + raise NotImplementedError + + @abc.abstractmethod + def set_component_name(self, component: str): + raise NotImplementedError + + def process_input_config(self, fw_version, input_cfg: dict) -> bytes: + self.set_payload_version(fw_version) + + if 'priority' in input_cfg: + self.set_update_priority(int(input_cfg['priority'])) + else: + raise AssertionError('priority filed myst be provided') + + self.set_component_name(input_cfg.get('component', 'MAIN')) + + vendor_id = self.encode_vendor_cfg(input_cfg) + + self.encode_device_cfg(input_cfg, vendor_id) + + return self._encode_payload_cfg(input_cfg) + + def _encode_payload_cfg(self, input_cfg) -> bytes: + if 'payload' not in input_cfg: + raise AssertionError('payload element not found') + if 'file-path' in input_cfg['payload']: + file_path = input_cfg['payload']['file-path'] + with open(file_path, 'rb') as fh: + hash_ctx = hashlib.sha256() + buf = fh.read(READ_BLOCK_SIZE) + while buf: + hash_ctx.update(buf) + buf = fh.read(READ_BLOCK_SIZE) + installed_digest = hash_ctx.digest() + self.set_payload_fingerprint( + digest=installed_digest, + size=fh.tell() + ) + else: + raise AssertionError( + 'payload:file-path must be provided') + if 'url' in input_cfg['payload']: + self.set_payload_uri(input_cfg['payload']['url']) + else: + raise AssertionError('payload:url not found') + if 'format' in input_cfg['payload']: + try: + payload_format = PayloadFormat(input_cfg['payload']['format']) + except KeyError: + raise AssertionError('unknown payload-format') + self.set_payload_format(str(payload_format.value)) + else: + raise AssertionError('payload-format element not found') + + if payload_format == PayloadFormat.PATCH: + delta_file = Path(input_cfg['payload']['file-path']) + delta_config_file = delta_file.with_suffix('.yaml') + with delta_config_file.open('rb') as fh: + delta_cfg = yaml.safe_load(fh) + installed_digest = base64.b64decode(delta_cfg['installed-digest']) + self.set_delta_metadata( + installed_digest=installed_digest, + installed_size=int(delta_cfg['installed-size']), + precursor_digest=base64.b64decode( + delta_cfg['precursor-digest']) + ) + return installed_digest + + def encode_device_cfg(self, input_cfg, vendor_id): + if 'device' not in input_cfg: + raise AssertionError('device element not found') + if 'model-name' in input_cfg['device']: + class_id = uuid.uuid5(vendor_id, input_cfg['device']['model-name']) + elif 'class-id' in input_cfg['device']: + class_id = uuid.UUID(input_cfg['device']['class-id']) + else: + raise AssertionError( + 'either device:class-id or device:model-name must be provided') + logger.info('Class-ID: %s', class_id.bytes.hex()) + self.set_class_id(class_id.bytes) + + def encode_vendor_cfg(self, input_cfg): + if 'vendor' not in input_cfg: + raise AssertionError('invalid vendor element not found') + if 'domain' in input_cfg['vendor']: + if not re.match(r'^\S+\.\S+$', input_cfg['vendor']['domain']): + raise AssertionError('invalid vendor_domain') + vendor_domain = input_cfg['vendor']['domain'] + vendor_id = uuid.uuid5(uuid.NAMESPACE_DNS, vendor_domain) + elif 'vendor-id' in input_cfg['vendor']: + vendor_id = uuid.UUID(input_cfg['vendor']['vendor-id']) + else: + raise AssertionError( + 'either vendor:vendor-id or vendor:domain must be provided') + + logger.info('Vendor-ID: %s', vendor_id.bytes.hex()) + self.set_vendor_id(vendor_id.bytes) + + if 'vendor' in input_cfg and 'custom-data-path' in input_cfg['vendor']: + self.set_vendor_data( + Path(input_cfg['vendor']['custom-data-path']).read_bytes() + ) + else: + pass # vendor data is an optional field + return vendor_id diff --git a/manifesttool/mtool/asn1/v1/__init__.py b/manifesttool/mtool/asn1/v1/__init__.py new file mode 100644 index 0000000..6d87425 --- /dev/null +++ b/manifesttool/mtool/asn1/v1/__init__.py @@ -0,0 +1,18 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +from manifesttool.mtool.asn1.v1.manifest_encoder_v1 import ManifestAsnCodecV1 diff --git a/ASN.1/v1/manifest-1.0.0 b/manifesttool/mtool/asn1/v1/manifest-1.0.0 similarity index 80% rename from ASN.1/v1/manifest-1.0.0 rename to manifesttool/mtool/asn1/v1/manifest-1.0.0 index df74088..87f4946 100644 --- a/ASN.1/v1/manifest-1.0.0 +++ b/manifesttool/mtool/asn1/v1/manifest-1.0.0 @@ -1,4 +1,20 @@ - +-- ---------------------------------------------------------------------------- +-- Copyright 2019 ARM Limited or its affiliates +-- +-- 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. +-- ---------------------------------------------------------------------------- -- Manifest definition file in ASN.1 (v. 1.0.0) ManifestSchema DEFINITIONS IMPLICIT TAGS ::= BEGIN @@ -72,7 +88,7 @@ ManifestSchema DEFINITIONS IMPLICIT TAGS ::= BEGIN Manifest ::= SEQUENCE { manifestVersion ENUMERATED { - v1(1), + v1(1) }, description UTF8String OPTIONAL, timestamp INTEGER, diff --git a/ASN.1/v1/manifest-format-1.0.md b/manifesttool/mtool/asn1/v1/manifest-format-1.0.md similarity index 98% rename from ASN.1/v1/manifest-format-1.0.md rename to manifesttool/mtool/asn1/v1/manifest-format-1.0.md index 08d2e04..c2c13c2 100644 --- a/ASN.1/v1/manifest-format-1.0.md +++ b/manifesttool/mtool/asn1/v1/manifest-format-1.0.md @@ -201,7 +201,7 @@ Below are the field desriptions, organized by type: * `priority` - The importance of the update. This is an integer that is provided to an application-specific authorisation function. 0 typically means "mandatory" and increasing values have lower priority. * `dependencies` - References other manifests (other data types are an error). When a device applies this manifest, it must simultaneously apply all the manifests that this list references. **Note:** The current Device Management Update Client release does not support this functionality. * `payload` - Describes a payload for an IoT device to apply. See below for subproperties. -* `aliases` - Allows a manifest to provide an alternate location for obtaining any payload or other manifest references. See [Resource aliases] for more information. **Note:** The current Device Management Update Client release does not support this functionality. +* `aliases` - Allows a manifest to provide an alternate location for obtaining any payload or other manifest references. **Note:** The current Device Management Update Client release does not support this functionality. ##### `PayloadDescription` properties diff --git a/manifesttool/mtool/asn1/v1/manifest_encoder_v1.py b/manifesttool/mtool/asn1/v1/manifest_encoder_v1.py new file mode 100644 index 0000000..589049d --- /dev/null +++ b/manifesttool/mtool/asn1/v1/manifest_encoder_v1.py @@ -0,0 +1,186 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import hashlib +import logging +import time +from collections import OrderedDict +from typing import Optional + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives.asymmetric import ec +from pyasn1.codec.der import decoder as der_decoder +from pyasn1.codec.der import encoder as der_encoder +from pyasn1.codec.native.encoder import encode as native_encoder +from pyasn1.type.univ import SequenceOf + +from manifesttool.mtool import ecdsa_helper +from manifesttool.mtool.asn1.manifest_codec import ManifestAsnCodecBase +from manifesttool.mtool.asn1.v1 import manifest_schema_v1 as schema + + +class ManifestAsnCodecV1(ManifestAsnCodecBase): + VERSION = 'v1' + + logger = logging.getLogger('v1-manifest-codec') + + def __init__(self, dom=None): + + if dom: + self.dom = dom + else: + self.dom = schema.Resource() + self.dom['resourceType'] = 'manifest' + self.dom['resource']['manifest'] = schema.Manifest() + self.dom['resource']['manifest']['manifestVersion'] = 'v1' + self.dom['resource']['manifest']['nonce'] = b'' + self.dom['resource']['manifest']['deviceId'] = b'' + self.dom['resource']['manifest']['vendorInfo'] = b'' + self.dom['resource']['manifest']['applyImmediately'] = True + self.dom['resource']['manifest']['encryptionMode']['enum'] = \ + 'none-ecc-secp256r1-sha256' + self.dom['resource']['manifest'][ + 'payload'] = schema.PayloadDescription() + self.dom['resource']['manifest']['payload'][ + 'storageIdentifier'] = "default" + self.dom['resource']['manifest']['payload'][ + 'reference'] = schema.ResourceReference() + self.fingerprint = None + + @classmethod + def get_name(cls) -> str: + return cls.VERSION + + def get_der_signed_resource(self, signature: bytes) -> bytes: + hash_ctx = hashlib.sha256() + hash_ctx.update(self.get_signed_data()) + signed_digest = hash_ctx.digest() + + resource_signature_dom = schema.ResourceSignature() + resource_signature_dom['hash'] = signed_digest + signature_block = schema.SignatureBlock() + signature_block['signature'] = signature + signature_block['certificates'] = SequenceOf() + certificate_reference = schema.CertificateReference() + certificate_reference['fingerprint'] = self.fingerprint + certificate_reference['uri'] = '' + signature_block['certificates'].append(certificate_reference) + resource_signature_dom['signatures'] = SequenceOf() + resource_signature_dom['signatures'].append(signature_block) + + signed_resource_dom = schema.SignedResource() + signed_resource_dom['resource'] = self.dom + signed_resource_dom['signature'] = resource_signature_dom + + return der_encoder.encode(signed_resource_dom) + + def get_signed_data(self) -> bytes: + return der_encoder.encode(self.dom) + + @classmethod + def decode( + cls, + data: bytes, + verification_key: Optional[ec.EllipticCurvePublicKey] + ) -> OrderedDict: + signed_resource_dom = der_decoder.decode( + data, + asn1Spec=schema.SignedResource())[0] + if not verification_key: + return native_encoder(signed_resource_dom) + + codec = ManifestAsnCodecV1(dom=signed_resource_dom['resource']) + signed_data = codec.get_signed_data() + signature = bytes( + signed_resource_dom['signature']['signatures'][0]['signature']) + + try: + ecdsa_helper.ecdsa_verify( + public_key=verification_key, + signed_data=signed_data, + signature=signature + ) + cls.logger.info('Manifest Signature verified!') + except InvalidSignature as ex: + raise AssertionError( + 'Manifest Signature verification failed') from ex + return native_encoder(signed_resource_dom) + + def set_payload_version(self, version: str): + if version: + try: + version_number = int(version) + except ValueError: + raise AssertionError( + 'invalid version {} - version must be ' + 'a valid positive integer'.format(version) + ) + else: + version_number = int(time.time()) + self.dom['resource']['manifest']['timestamp'] = version_number + + def set_update_priority(self, priority: int): + self.dom['resource']['manifest']['priority'] = priority + + def set_vendor_id(self, vendor_id: bytes): + self.dom['resource']['manifest']['vendorId'] = vendor_id + + def set_vendor_data(self, data: bytes): + self.dom['resource']['manifest']['vendorInfo'] = data + + def set_class_id(self, class_id: bytes): + self.dom['resource']['manifest']['classId'] = class_id + + def set_device_id(self, device_id: bytes): + self.dom['resource']['manifest']['classId'] = device_id + + def set_payload_fingerprint(self, digest: bytes, size: int): + self.dom['resource']['manifest']['payload']['reference'][ + 'hash'] = digest + self.dom['resource']['manifest']['payload']['reference']['size'] = size + + def set_payload_uri(self, uri: str): + self.dom['resource']['manifest']['payload']['reference']['uri'] = uri + + def set_payload_format(self, payload_format: str): + _format = payload_format + if payload_format == 'arm-patch-stream': + _format = 'bsdiff-stream' + self.dom['resource']['manifest']['payload']['format']['enum'] = _format + + def set_delta_metadata( + self, + installed_digest: bytes, + installed_size: int, + precursor_digest: bytes + ): + self.dom['resource']['manifest']['payload'][ + 'installedDigest'] = installed_digest + self.dom['resource']['manifest']['payload'][ + 'installedSize'] = installed_size + self.dom['resource']['manifest']['precursorDigest'] = precursor_digest + + def set_update_certificate(self, cert_data: bytes): + hash_ctx = hashlib.sha256() + hash_ctx.update(cert_data) + self.fingerprint = hash_ctx.digest() + + def set_image_signature(self, signature: bytes): + pass # do nothing here + + def set_component_name(self, component: str): + pass diff --git a/manifesttool/v1/manifest_definition.py b/manifesttool/mtool/asn1/v1/manifest_schema_v1.py similarity index 87% rename from manifesttool/v1/manifest_definition.py rename to manifesttool/mtool/asn1/v1/manifest_schema_v1.py index 26273e0..a603af3 100644 --- a/manifesttool/v1/manifest_definition.py +++ b/manifesttool/mtool/asn1/v1/manifest_schema_v1.py @@ -1,36 +1,31 @@ -# -*- coding: utf-8 -*- -#---------------------------------------------------------------------------- -# The confidential and proprietary information contained in this file may -# only be used by a person authorised under and to the extent permitted -# by a subsisting licensing agreement from ARM Limited or its affiliates. -# -# (C) COPYRIGHT 2016 ARM Limited or its affiliates. -# ALL RIGHTS RESERVED -# -# This entire notice must be reproduced on all copies of this file -# and copies of this file may only be made by a person if such person is -# permitted to do so under the terms of a subsisting license agreement -# from ARM Limited or its affiliates. -#---------------------------------------------------------------------------- -# -# This file has been generated using asn1ate (v ) from 'ASN.1/v1/manifest-1.0.0' -# Last Modified on 2019-03-18 12:08:08.480914 -from pyasn1.type import univ, char, namedtype, namedval, tag, constraint, useful - +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +# Auto-generated by asn1ate v.0.6.0 from manifest-1.0.0 +# (last modified on 2020-01-26 09:34:14.860967) -class Uri(char.UTF8String): - pass +from pyasn1.type import univ, char, namedtype, namedval, tag, constraint, useful class Bytes(univ.OctetString): pass -class UUID(univ.OctetString): - pass - - -class Payload(univ.OctetString): +class Uri(char.UTF8String): pass @@ -44,13 +39,13 @@ class CertificateReference(univ.Sequence): ) -class SignatureBlock(univ.Sequence): +class KeyTableEntry(univ.Sequence): pass -SignatureBlock.componentType = namedtype.NamedTypes( - namedtype.NamedType('signature', univ.OctetString()), - namedtype.NamedType('certificates', univ.SequenceOf(componentType=CertificateReference())) +KeyTableEntry.componentType = namedtype.NamedTypes( + namedtype.OptionalNamedType('hash', univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), + namedtype.OptionalNamedType('payloadKey', univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))) ) @@ -68,27 +63,6 @@ class MacBlock(univ.Sequence): ) -class KeyTableEntry(univ.Sequence): - pass - - -KeyTableEntry.componentType = namedtype.NamedTypes( - namedtype.OptionalNamedType('hash', univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), - namedtype.OptionalNamedType('payloadKey', univ.OctetString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))) -) - - -class ResourceSignature(univ.Sequence): - pass - - -ResourceSignature.componentType = namedtype.NamedTypes( - namedtype.NamedType('hash', univ.OctetString()), - namedtype.NamedType('signatures', univ.SequenceOf(componentType=SignatureBlock())), - namedtype.OptionalNamedType('macs', univ.SequenceOf(componentType=MacBlock())) -) - - class ResourceReference(univ.Sequence): pass @@ -100,16 +74,6 @@ class ResourceReference(univ.Sequence): ) -class ResourceAlias(univ.Sequence): - pass - - -ResourceAlias.componentType = namedtype.NamedTypes( - namedtype.NamedType('hash', univ.OctetString()), - namedtype.NamedType('uri', Uri()) -) - - class PayloadDescription(univ.Sequence): pass @@ -142,6 +106,20 @@ class PayloadDescription(univ.Sequence): ) +class ResourceAlias(univ.Sequence): + pass + + +ResourceAlias.componentType = namedtype.NamedTypes( + namedtype.NamedType('hash', univ.OctetString()), + namedtype.NamedType('uri', Uri()) +) + + +class UUID(univ.OctetString): + pass + + class Manifest(univ.Sequence): pass @@ -174,6 +152,10 @@ class Manifest(univ.Sequence): ) +class Payload(univ.OctetString): + pass + + class Resource(univ.Sequence): pass @@ -189,6 +171,27 @@ class Resource(univ.Sequence): ) +class SignatureBlock(univ.Sequence): + pass + + +SignatureBlock.componentType = namedtype.NamedTypes( + namedtype.NamedType('signature', univ.OctetString()), + namedtype.NamedType('certificates', univ.SequenceOf(componentType=CertificateReference())) +) + + +class ResourceSignature(univ.Sequence): + pass + + +ResourceSignature.componentType = namedtype.NamedTypes( + namedtype.NamedType('hash', univ.OctetString()), + namedtype.NamedType('signatures', univ.SequenceOf(componentType=SignatureBlock())), + namedtype.OptionalNamedType('macs', univ.SequenceOf(componentType=MacBlock())) +) + + class SignedResource(univ.Sequence): pass @@ -197,3 +200,5 @@ class SignedResource(univ.Sequence): namedtype.NamedType('resource', Resource()), namedtype.NamedType('signature', ResourceSignature()) ) + + diff --git a/manifesttool/mtool/asn1/v3/__init__.py b/manifesttool/mtool/asn1/v3/__init__.py new file mode 100644 index 0000000..e9f3f79 --- /dev/null +++ b/manifesttool/mtool/asn1/v3/__init__.py @@ -0,0 +1,18 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +from manifesttool.mtool.asn1.v3.manifest_encoder_v3 import ManifestAsnCodecV3 diff --git a/manifesttool/mtool/asn1/v3/manifest_encoder_v3.py b/manifesttool/mtool/asn1/v3/manifest_encoder_v3.py new file mode 100644 index 0000000..01d89dc --- /dev/null +++ b/manifesttool/mtool/asn1/v3/manifest_encoder_v3.py @@ -0,0 +1,163 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import logging +from collections import OrderedDict +from typing import Optional + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives.asymmetric import ec +from pyasn1.codec.der import decoder as der_decoder +from pyasn1.codec.der import encoder as der_encoder +from pyasn1.codec.native.encoder import encode as native_encoder + +from manifesttool.mtool import ecdsa_helper +from manifesttool.mtool.asn1.manifest_codec import ManifestAsnCodecBase +from manifesttool.mtool.asn1.v3 import manifest_schema_v3 as manifest_schema + + +class ManifestAsnCodecV3(ManifestAsnCodecBase): + VERSION = 'v3' + + logger = logging.getLogger('v3-manifest-codec') + + def __init__(self, dom=None): + + if dom: + self.dom = dom + else: + self.dom = manifest_schema.Manifest() + + @classmethod + def get_name(cls) -> str: + return cls.VERSION + + def set_payload_version(self, version: str): + assert isinstance(version, str) + self.dom['payload-version'] = version + + def set_update_priority(self, priority: int): + self.dom['update-priority'] = priority + + def set_vendor_id(self, vendor_id: bytes): + self.dom['vendor-id'] = vendor_id + + def set_vendor_data(self, data: bytes): + self.dom['vendor-data'] = data + + def set_class_id(self, class_id: bytes): + self.dom['class-id'] = class_id + + def set_device_id(self, device_id: bytes): + self.dom['device-id'] = device_id + + def set_payload_fingerprint(self, digest: bytes, size: int): + self.dom['payload-digest'] = digest + self.dom['payload-size'] = size + + def set_payload_uri(self, uri: str): + self.dom['payload-uri'] = uri + + def set_payload_format(self, payload_format: str): + self.dom['payload-format'] = payload_format + + def set_delta_metadata( + self, + installed_digest: bytes, + installed_size: int, + precursor_digest: bytes + ): + delta_meta_dom = manifest_schema.DeltaMetadata() + delta_meta_dom['installed-size'] = installed_size + delta_meta_dom['installed-digest'] = installed_digest + delta_meta_dom['precursor-digest'] = precursor_digest + self.dom['delta-metadata'] = delta_meta_dom + + @classmethod + def decode( + cls, + data: bytes, + verification_key: Optional[ec.EllipticCurvePublicKey] + ) -> OrderedDict: + + signed_resource_dom = der_decoder.decode( + data, asn1Spec=manifest_schema.SignedResource())[0] + if not verification_key: + return native_encoder(signed_resource_dom) + + codec = ManifestAsnCodecV3(dom=signed_resource_dom['manifest']) + signed_data = codec.get_signed_data() + der_signature = bytes(signed_resource_dom['signature']) + signature = ecdsa_helper.signature_raw_to_der(der_signature) + + try: + ecdsa_helper.ecdsa_verify( + public_key=verification_key, + signed_data=signed_data, + signature=signature + ) + cls.logger.info('Manifest Signature verified!') + except InvalidSignature as ex: + raise AssertionError( + 'Manifest Signature verification failed') from ex + + raw_image_signature = bytes( + codec.dom['installed-signature']) + if raw_image_signature: + der_image_signature = \ + ecdsa_helper.signature_raw_to_der( + raw_image_signature + ) + digest = bytes(codec.dom['payload-digest']) + if str(codec.dom['payload-format']) == \ + 'arm-patch-stream': + digest = bytes( + codec.dom['delta-metadata']['installed-digest'] + ) + try: + ecdsa_helper.ecdsa_verify_prehashed( + public_key=verification_key, + digest=digest, + signature=der_image_signature + ) + cls.logger.info('Image Signature verified!') + except InvalidSignature as ex: + raise AssertionError( + 'Image Signature verification failed') from ex + + return native_encoder(signed_resource_dom) + + def get_signed_data(self) -> bytes: + # sha_content = utils.sha_hash(enc_data) + + return der_encoder.encode(self.dom) + + def get_der_signed_resource(self, signature: bytes) -> bytes: + resource_dom = manifest_schema.SignedResource() + resource_dom['manifest-version'] = self.VERSION + resource_dom['manifest'] = self.dom + resource_dom['signature'] = signature + return der_encoder.encode(resource_dom) + + def set_update_certificate(self, cert_data: bytes): + raise NotImplementedError + + def set_image_signature(self, signature: bytes): + self.dom['installed-signature'] = signature + + def set_component_name(self, component: str): + self.dom['component-name'] = component diff --git a/manifesttool/mtool/asn1/v3/manifest_schema_v3.py b/manifesttool/mtool/asn1/v3/manifest_schema_v3.py new file mode 100644 index 0000000..c786cd5 --- /dev/null +++ b/manifesttool/mtool/asn1/v3/manifest_schema_v3.py @@ -0,0 +1,65 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +# Auto-generated by asn1ate v.0.6.0 from manifest_v3.asn +# (last modified on 2020-03-09 21:15:44.743188) + +from pyasn1.type import univ, char, namedtype, namedval, tag, constraint, useful + + +class DeltaMetadata(univ.Sequence): + pass + + +DeltaMetadata.componentType = namedtype.NamedTypes( + namedtype.NamedType('installed-size', univ.Integer()), + namedtype.NamedType('installed-digest', univ.OctetString()), + namedtype.NamedType('precursor-digest', univ.OctetString()) +) + + +class Manifest(univ.Sequence): + pass + + +Manifest.componentType = namedtype.NamedTypes( + namedtype.NamedType('vendor-id', univ.OctetString()), + namedtype.NamedType('class-id', univ.OctetString()), + namedtype.NamedType('update-priority', univ.Integer()), + namedtype.NamedType('component-name', char.UTF8String()), + namedtype.NamedType('payload-version', char.UTF8String()), + namedtype.NamedType('payload-digest', univ.OctetString()), + namedtype.NamedType('payload-size', univ.Integer()), + namedtype.NamedType('payload-uri', char.UTF8String()), + namedtype.NamedType('payload-format', univ.Enumerated(namedValues=namedval.NamedValues(('raw-binary', 1), ('arm-patch-stream', 5)))), + namedtype.NamedType('installed-signature', univ.OctetString()), + namedtype.OptionalNamedType('delta-metadata', DeltaMetadata()), + namedtype.OptionalNamedType('vendor-data', univ.OctetString()) +) + + +class SignedResource(univ.Sequence): + pass + + +SignedResource.componentType = namedtype.NamedTypes( + namedtype.NamedType('manifest-version', univ.Enumerated(namedValues=namedval.NamedValues(('v3', 3)))), + namedtype.NamedType('manifest', Manifest()), + namedtype.NamedType('signature', univ.OctetString()) +) + + diff --git a/manifesttool/mtool/asn1/v3/manifest_v3.asn b/manifesttool/mtool/asn1/v3/manifest_v3.asn new file mode 100644 index 0000000..ea0a153 --- /dev/null +++ b/manifesttool/mtool/asn1/v3/manifest_v3.asn @@ -0,0 +1,75 @@ +-- ---------------------------------------------------------------------------- +-- Copyright 2019 ARM Limited or its affiliates +-- +-- 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. +-- ---------------------------------------------------------------------------- + +-- Manifest definition file in ASN.1 (v. 1.1.0) +ManifestSchema DEFINITIONS IMPLICIT TAGS ::= BEGIN + + -- Describing of arm-bsdiff-stream payload + DeltaMetadata ::= SEQUENCE { + -- represents reconstructed payload size + installed-size INTEGER, + -- represents reconstructed payload digest + installed-digest OCTET STRING, + + -- specifies currently installed payload digest + precursor-digest OCTET STRING + } + + Manifest ::= SEQUENCE { + + -- identifier fields + vendor-id OCTET STRING, + class-id OCTET STRING, + + -- update priority to be passed to an application callback + update-priority INTEGER, + + -- component name + component-name UTF8String, + + -- payload description -- + payload-version UTF8String, + payload-digest OCTET STRING, + payload-size INTEGER, + payload-uri UTF8String, + payload-format ENUMERATED { + raw-binary(1), + arm-patch-stream(5) + }, + + -- raw ECDSA signature (r||s) over installed payload + installed-signature OCTET STRING, + + -- only relevant if payload-format = arm-patch-stream + delta-metadata DeltaMetadata OPTIONAL, + + -- custom data to be passed to an endpoint device + vendor-data OCTET STRING OPTIONAL + } + + SignedResource ::= SEQUENCE { + manifest-version ENUMERATED { + v3(3) + }, + manifest Manifest, + + -- raw ECDSA signature (r||s) over installed payload + signature OCTET STRING + } + +END diff --git a/manifesttool/mtool/ecdsa_helper.py b/manifesttool/mtool/ecdsa_helper.py new file mode 100644 index 0000000..c5bbdf9 --- /dev/null +++ b/manifesttool/mtool/ecdsa_helper.py @@ -0,0 +1,99 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +from cryptography import x509 +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.asymmetric import utils as ec_utils +from cryptography.utils import int_to_bytes + + +def ecdsa_sign_prehashed(digest, pem_key_data): + private_key = serialization.load_pem_private_key( + pem_key_data, + password=None, + backend=default_backend() + ) + return private_key.sign( + digest, ec.ECDSA(ec_utils.Prehashed(hashes.SHA256()))) + + +def ecdsa_sign(data_to_sign, pem_key_data): + private_key = serialization.load_pem_private_key( + pem_key_data, + password=None, + backend=default_backend() + ) + return private_key.sign(data_to_sign, ec.ECDSA(hashes.SHA256())) + +def public_key_from_private(pem_priv_key_data) -> ec.EllipticCurvePublicKey: + private_key = serialization.load_pem_private_key( + pem_priv_key_data, + password=None, + backend=default_backend() + ) + return private_key.public_key() + +def public_key_from_certificate(certificate_data) -> ec.EllipticCurvePublicKey: + cert = x509.load_der_x509_certificate( + certificate_data, default_backend()) + return cert.public_key() + + +def public_key_from_bytes(public_key_data) -> ec.EllipticCurvePublicKey: + return ec.EllipticCurvePublicKey.from_encoded_point( + curve=ec.SECP256R1(), + data=public_key_data + ) + +def public_key_to_bytes(public_key) -> bytes: + return public_key.public_bytes( + encoding=serialization.Encoding.X962, + format=serialization.PublicFormat.UncompressedPoint + ) + + +def signature_raw_to_der(raw_signature): + return ec_utils.encode_dss_signature( + r=int.from_bytes(raw_signature[:32], byteorder='big'), + s=int.from_bytes(raw_signature[32:], byteorder='big') + ) + + +def signature_der_to_raw(signature): + # pylint: disable=invalid-name + r, s = ec_utils.decode_dss_signature(signature) + return int_to_bytes(r, 32) + int_to_bytes(s, 32) + + +def ecdsa_verify_prehashed(public_key, digest, signature): + public_key.verify( + signature, + digest, + ec.ECDSA(ec_utils.Prehashed(hashes.SHA256())) + ) + + +def ecdsa_verify(public_key, signed_data, signature): + public_key.verify( + signature, + signed_data, + ec.ECDSA(hashes.SHA256()) + ) diff --git a/manifesttool/mtool/manifest-input-schema.json b/manifesttool/mtool/manifest-input-schema.json new file mode 100644 index 0000000..3cc79ab --- /dev/null +++ b/manifesttool/mtool/manifest-input-schema.json @@ -0,0 +1,101 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Manifest-tool input validator", + "description": "This schema is used to validate the input arguments for manifest-tool", + "type": "object", + "required": [ + "vendor", + "device", + "priority", + "payload" + ], + "properties": { + "vendor": { + "type": "object", + "properties": { + "domain": { + "$ref": "#/definitions/non_empty_string", + "description": "Vendor Domain", + "pattern": "\\w+(\\.\\w+)+" + }, + "vendor-id": { + "$ref": "#/definitions/uuid_hex_string", + "description": "Vendor UUID" + }, + "custom-data-path": { + "$ref": "#/definitions/non_empty_string", + "description": "Path to custom data file - must be accessible by the manifest-tool" + } + }, + "oneOf": [ + {"required": ["domain"]}, + {"required": ["vendor-id"]} + ] + }, + "device": { + "type": "object", + "properties": { + "model-name": { + "$ref": "#/definitions/non_empty_string", + "description": "Device model name" + }, + "class-id": { + "$ref": "#/definitions/uuid_hex_string", + "description": "Device class UUID" + } + }, + "oneOf": [ + {"required": ["model-name"]}, + {"required": ["class-id"]} + ] + }, + "priority": { + "description": "Update priority", + "type": "integer" + }, + "payload": { + "type": "object", + "required": [ + "url", + "format", + "file-path" + ], + "properties": { + "format": { + "description": "Payload format type", + "enum": [ + "raw-binary", + "arm-patch-stream" + ] + }, + "url": { + "$ref": "#/definitions/non_empty_string", + "description": "Payload URL in the cloud storage" + }, + "file-path": { + "$ref": "#/definitions/non_empty_string", + "description": "Path to payload file - must be accessible by the manifest-tool" + } + } + }, + "component": { + "description": "Component name - only relevant for manifest v3", + "$ref": "#/definitions/non_empty_string" + }, + "sign-image":{ + "description": "Do sign installed image - only relevant for manifest v3. Required for devices with PKI image authentication in bootloader", + "type": "boolean" + } + }, + "definitions": { + "non_empty_string": { + "type": "string", + "minLength": 1 + }, + "uuid_hex_string": { + "type": "string", + "pattern": "[0-9a-fA-F]{32}", + "description": "HEX encoded UUID string" + } + } +} \ No newline at end of file diff --git a/manifesttool/mtool/mtool.py b/manifesttool/mtool/mtool.py new file mode 100644 index 0000000..77700fb --- /dev/null +++ b/manifesttool/mtool/mtool.py @@ -0,0 +1,144 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +import argparse +import enum +import logging +import sys + +from manifesttool import __version__ +from manifesttool.mtool.actions.create import CreateAction +from manifesttool.mtool.actions.parse import ParseAction +from manifesttool.mtool.actions.public_key import PublicKeyAction +from manifesttool.mtool.actions.schema import PrintSchemaAction +from manifesttool.mtool.asn1.v1 import ManifestAsnCodecV1 +from manifesttool.mtool.asn1.v3 import ManifestAsnCodecV3 + +logger = logging.getLogger('manifest-tool') + + +class Actions(enum.Enum): + CREATE = 'create' + CREATE_V1 = 'create-v1' + PARSE = 'parse' + SCHEMA = 'schema' + PUB_KEY = 'public-key' + + +def get_parser(): + parser = argparse.ArgumentParser( + description='Manifest tool for creating, signing and verifying ' + 'Pelion Device management update certificates' + ) + + parser.add_argument( + '--version', + action='version', + version='Manifest-Tool version {}'.format(__version__) + + ) + + parser.add_argument( + '-q', '--quiet', + action='store_true', + help='Suppress information prints. Error prints only.' + ) + + parser.add_argument( + '--debug', + action='store_true', + help='Show exception info on error.' + ) + + actions_parser = parser.add_subparsers(dest='action') + actions_parser.required = True + create_parser = actions_parser.add_parser( + Actions.CREATE.value, + help='Create a Pelion Device management update certificate', + add_help=False + ) + CreateAction.register_parser_args( + create_parser, ManifestAsnCodecV3.get_name()) + + create_parser = actions_parser.add_parser( + Actions.CREATE_V1.value, + help='Create a Pelion Device management update certificate', + add_help=False + ) + CreateAction.register_parser_args( + create_parser, ManifestAsnCodecV1.get_name()) + + verify_parser = actions_parser.add_parser( + Actions.PARSE.value, + help='Parse and verify Pelion Device management update certificate', + add_help=False + ) + ParseAction.register_parser_args(verify_parser) + + schema_parser = actions_parser.add_parser( + Actions.SCHEMA.value, + help='Print input validation schema' + ) + PrintSchemaAction.register_parser_args(schema_parser) + + schema_parser = actions_parser.add_parser( + Actions.PUB_KEY.value, + help='Get Uncompressed Public key in binary form' + ) + PublicKeyAction.register_parser_args(schema_parser) + + return parser + + +def entry_point(argv=sys.argv[1:]): # pylint: disable=dangerous-default-value + parser = get_parser() + args = parser.parse_args(argv) + + logging.basicConfig( + stream=sys.stdout, + format='%(asctime)s %(levelname)s %(message)s', + level=logging.ERROR if args.quiet else logging.DEBUG + ) + try: + action = Actions(args.action) + if action == Actions.PARSE: + ParseAction.entry_point(args) + elif action == Actions.CREATE: + CreateAction.entry_point(args, ManifestAsnCodecV3) + elif action == Actions.CREATE_V1: + CreateAction.entry_point(args, ManifestAsnCodecV1) + elif action == Actions.SCHEMA: + PrintSchemaAction.entry_point(args) + elif action == Actions.PUB_KEY: + PublicKeyAction.entry_point(args) + else: + # will never get here + raise AssertionError('Invalid action') + except Exception as ex: # pylint: disable=broad-except + if args.debug: + raise + logger.error( + str(ex), + exc_info=args.debug + ) + return 1 + return 0 + + +if __name__ == '__main__': + raise SystemExit(entry_point()) diff --git a/manifesttool/sign.py b/manifesttool/mtool/payload_format.py similarity index 65% rename from manifesttool/sign.py rename to manifesttool/mtool/payload_format.py index f3a0423..4e600ce 100644 --- a/manifesttool/sign.py +++ b/manifesttool/mtool/payload_format.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates +# Copyright 2019 ARM Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0 # @@ -17,16 +16,9 @@ # limitations under the License. # ---------------------------------------------------------------------------- -from manifesttool.v1.sign import main as sign_v1 -from manifesttool.utils import detect_version +import enum -def main(options): - version = detect_version(options.manifest) - if not version: - return 1 - sign = { - '1' : sign_v1 - }.get(version) - if not sign: - return 1 - return sign(options) + +class PayloadFormat(enum.Enum): + RAW = 'raw-binary' + PATCH = 'arm-patch-stream' diff --git a/manifesttool/parse.py b/manifesttool/parse.py deleted file mode 100644 index 6d6b18f..0000000 --- a/manifesttool/parse.py +++ /dev/null @@ -1,86 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -import json, logging -from builtins import bytes -from manifesttool.v1.parse import parse as parser_v1 -import sys - -LOG = logging.getLogger(__name__) - -def skipAhead(code): - rc = 0 - if code == 0x81: - rc = 1 - if code == 0x82: - rc = 2 - if code == 0x83: - rc = 3 - if code == 0x84: - rc = 4 - return rc - -def parse(options): - LOG.debug("Attempting to determine manifest version...") - # 32 bytes is currently sufficient to detect the manifest type. - data = options.input_file.read(32) - headerData = bytes(data) - # options.input_file.seek(0) - # In both cases, the manifest starts with a DER SEQUENCE tag. - if headerData[0] != 0x30: - LOG.critical("input file is not a manifest.") - return None, None - # skip past the length - pos = 2 + skipAhead(headerData[1]) - - version = None - # For version 1, the first object in the SEQUENCE should be another SEQUENCE - if headerData[pos] == 0x30: - version = 1 - # For version 2+, a CMS wrapper is used, so the tag should be an OID tag - if headerData[pos] == 0x06: - version = 2 - - if version == None: - LOG.critical("No recognized manifest format found.") - return None, None - # For now, we will assume that 2+ means 2. - parser = { - 1 : parser_v1 - }.get(version, None) - if not parser: - LOG.critical("Unrecognized manifest version.") - return None, None - if sys.version_info.major < 3: - headerData = ''.join([chr(x) for x in headerData]) - return parser(options, headerData) - - -def main(options): - decoded_manifest = parse(options) - if not decoded_manifest: - return 1 - - indent = None if not options.pretty_json else 4 - - # Write to output buffer/file - options.output_file.write(str.encode(json.dumps(decoded_manifest, indent = indent))) - - # If we're writing to TTY, add a helpful newline - if options.output_file.isatty(): - options.output_file.write(b'\n') diff --git a/manifesttool/prepare.py b/manifesttool/prepare.py deleted file mode 100644 index d4ecd5b..0000000 --- a/manifesttool/prepare.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -import logging, sys -LOG = logging.getLogger(__name__) - -from manifesttool.v1.create import main as create_v1 -from urllib3.exceptions import MaxRetryError -import copy -import time -import tempfile -import os -import os.path -import shutil -import json -from manifesttool import defaults - - -MAX_NAME_LEN = 128 # The update API has a maximum name length of 128, but this is not queriable. - -tempdirname = None -manifest_file = None - -def main_wrapped(options): - try: - from mbed_cloud.update import UpdateAPI - import mbed_cloud.exceptions - except: - LOG.critical('manifest-tool update commands require installation of the Pelion Device Management SDK:' - ' https://github.com/ARMmbed/mbed-cloud-sdk-python') - return 1 - LOG.debug('Preparing an update on Pelion Device Management') - # upload a firmware - api = None - try: - # If set use api key set in manifest-tool update. - if hasattr(options, 'api_key') and options.api_key: - tempKey = options.api_key - config = {'api_key': tempKey} - api = UpdateAPI(config) - # Otherwise use API key set in manifest-tool init - else: api = UpdateAPI() - - except ValueError: - LOG.critical('API key is required to connect to the Update Service. It can be added using manifest-tool init -a' - ' or by manually editing .mbed_cloud_config.json') - return 1 - - manifestInput = { - 'applyImmediately' : True - } - - try: - if os.path.exists(defaults.config): - with open(defaults.config) as f: - manifestInput.update(json.load(f)) - if not options.input_file.isatty(): - content = options.input_file.read() - if content and len(content) >= 2: #The minimum size of a JSON file is 2: '{}' - manifestInput.update(json.loads(content)) - except ValueError as e: - LOG.critical("JSON Decode Error: {}".format(e)) - return 1 - - payload_filePath = manifestInput.get("payloadFile", None) - if options.payload: - payload_filePath = options.payload.name - - if not options.payload_name: - name = os.path.basename(payload_filePath) + time.strftime('-%Y-%m-%dT%H:%M:%S') - LOG.info('Using {} as payload name.'.format(name)) - options.payload_name = name - if len(options.payload_name) > MAX_NAME_LEN: - LOG.critical( - 'Payload name is too long. Maximum length is {size}. ("{base}" <- {size}. overflow -> "{overflow}")'.format( - size=MAX_NAME_LEN, base=options.payload_name[:MAX_NAME_LEN], - overflow=options.payload_name[MAX_NAME_LEN:])) - return 1 - - if not options.manifest_name: - name = os.path.basename(payload_filePath) + time.strftime('-%Y-%m-%dT%H:%M:%S-manifest') - LOG.info('Using {} as manifest name.'.format(name)) - options.manifest_name = name - - if len(options.manifest_name) > MAX_NAME_LEN: - LOG.critical( - 'Manifest name is too long. Maximum length is {size}. ("{base}" <- {size}. overflow -> "{overflow}")'.format( - size=MAX_NAME_LEN, base=options.manifest_name[:MAX_NAME_LEN], - overflow=options.manifest_name[MAX_NAME_LEN:])) - return 1 - - kwArgs = {} - if options.payload_description: - kwArgs['description'] = options.payload_description - try: - payload = api.add_firmware_image( - name = options.payload_name, - datafile = payload_filePath, - **kwArgs) - except mbed_cloud.exceptions.CloudApiException as e: - # TODO: Produce a better failuer message - LOG.critical('Upload of payload failed with:\n{}'.format(e).rstrip()) - LOG.critical('Check API server URL "{}"'.format(api.config["host"])) - return 1 - except MaxRetryError as e: - LOG.critical('Upload of payload failed with:\n{}'.format(e)) - LOG.critical('Failed to establish connection to API-GW') - LOG.critical('Check API server URL "{}"'.format(api.config["host"])) - return 1 - - LOG.info("Created new firmware at {}".format(payload.url)) - # create a manifest - create_opts = copy.copy(options) - create_opts.uri = payload.url - create_opts.payload = options.payload - if not (hasattr(create_opts, "output_file") and create_opts.output_file): - global manifest_file - manifest_file = open(os.path.join(tempdirname,'manifest'),'wb') - create_opts.output_file = manifest_file - - rc = create_v1(create_opts, manifestInput) - create_opts.output_file.close() - if rc: - return rc - - kwArgs = {} - if options.manifest_description: - kwArgs['description'] = options.manifest_description - - # upload a manifest - try: - manifest = api.add_firmware_manifest( - name = options.manifest_name, - datafile = create_opts.output_file.name, - **kwArgs) - except mbed_cloud.exceptions.CloudApiException as e: - # TODO: Produce a better failuer message - LOG.critical('Upload of manifest failed with:') - print(e) - return 1 - LOG.info('Created new manifest at {}'.format(manifest.url)) - LOG.info('Manifest ID: {}'.format(manifest.id)) - return 0 - -def main(options): - global tempdirname - tempdirname = tempfile.mkdtemp() - RC = main_wrapped(options) - if manifest_file: - manifest_file.close() - shutil.rmtree(tempdirname) - return RC diff --git a/manifesttool/signature_schema.py b/manifesttool/signature_schema.py deleted file mode 100644 index 348e344..0000000 --- a/manifesttool/signature_schema.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2017 ARM Limited or its affiliates -# -# 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 a python class representation of the ASN.1 schema defined -# in manifest.asn. It is used to generate a JSON representation of the manifest -# from raw data. -# -# It differs from manifest_definition.py as it's not used by pyasn1, it's not used -# to encode the manifest data nor is it automatically generated. -# -# The process looks like: -# (Input data) -> (Python object representation) -> (JSON) -> (PyASN1 object) -> ([DER] encoding) -# [ this file ] -import time, collections -from manifesttool import utils -from manifesttool.errorhandler import InvalidObject - -class BaseObject(object): - - # Basic check to see if all required fields are set. - # Does NOT check if the set value is of right type accoridng to ASN.1 definition - def verify(self, required_fields): - for f in required_fields: - if self.__dict__.get(f) is None: - raise InvalidObject("Value for field %r not set, but it's required" % f) - - # Convinience method to just convert object to python dict - def to_dict(self): - return utils.todict(self) - -class SignedResource(BaseObject): - def __init__(self, resource, signature): - self.resource = resource - self.signature = signature - - -class CertificateReference(object): - def __init__(self, fingerprint, uri): - self.fingerprint = fingerprint - self.uri = uri - -class SignatureBlock(object): - def __init__(self, signature, certificates): - self.signature = signature - self.certificates = certificates - -class ResourceSignature(object): - def __init__(self, hash, signatures): - self.hash = hash - self.signatures = signatures diff --git a/manifesttool/templates.py b/manifesttool/templates.py deleted file mode 100644 index 1edca5a..0000000 --- a/manifesttool/templates.py +++ /dev/null @@ -1,85 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- - -UpdateDefaultResources = ''' -//---------------------------------------------------------------------------- -// The confidential and proprietary information contained in this file may -// only be used by a person authorised under and to the extent permitted -// by a subsisting licensing agreement from ARM Limited or its affiliates. -// -// (C) COPYRIGHT 2013-2017 ARM Limited or its affiliates. -// ALL RIGHTS RESERVED -// -// This entire notice must be reproduced on all copies of this file -// and copies of this file may only be made by a person if such person is -// permitted to do so under the terms of a subsisting license agreement -// from ARM Limited or its affiliates. -//---------------------------------------------------------------------------- - -#ifdef MBED_CLOUD_CLIENT_USER_CONFIG_FILE -#include MBED_CLOUD_CLIENT_USER_CONFIG_FILE -#endif - -#include - -#ifdef MBED_CLOUD_DEV_UPDATE_ID -const uint8_t arm_uc_vendor_id[] = {{ - {vendorId} -}}; -const uint16_t arm_uc_vendor_id_size = sizeof(arm_uc_vendor_id); - -const uint8_t arm_uc_class_id[] = {{ - {classId} -}}; -const uint16_t arm_uc_class_id_size = sizeof(arm_uc_class_id); -#endif - -#ifdef MBED_CLOUD_DEV_UPDATE_CERT -const uint8_t arm_uc_default_fingerprint[] = {{ - {certFp} -}}; -const uint16_t arm_uc_default_fingerprint_size = - sizeof(arm_uc_default_fingerprint); - -const uint8_t arm_uc_default_subject_key_identifier[] = {{ - {ski} -}}; -const uint16_t arm_uc_default_subject_key_identifier_size = - sizeof(arm_uc_default_subject_key_identifier); - -const uint8_t arm_uc_default_certificate[] = {{ - {cert} -}}; -const uint16_t arm_uc_default_certificate_size = sizeof(arm_uc_default_certificate); -#endif - - -#ifdef MBED_CLOUD_DEV_UPDATE_PSK -const uint8_t arm_uc_default_psk[] = {{ - {psk} -}}; -const uint8_t arm_uc_default_psk_size = sizeof(arm_uc_default_psk); -const uint16_t arm_uc_default_psk_bits = sizeof(arm_uc_default_psk)*8; - -const uint8_t arm_uc_default_psk_id[] = {{ - {pskId} -}}; -const uint8_t arm_uc_default_psk_id_size = sizeof(arm_uc_default_psk_id); -#endif -''' diff --git a/manifesttool/update.py b/manifesttool/update.py deleted file mode 100644 index 1a82f8d..0000000 --- a/manifesttool/update.py +++ /dev/null @@ -1,41 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -import logging -import sys -LOG = logging.getLogger(__name__) - -from manifesttool import prepare -from manifesttool import update_device as device - -def main(options): - if (hasattr(options,"psk") and options.psk) or (hasattr(options,"mac") and options.mac): - LOG.critical('manifest-tool update commands are not currently enabled for PSK/MAC authentication.') - return 1 - try: - from mbed_cloud.update import UpdateAPI - from mbed_cloud import __version__ as mc_version - if mc_version < "1.2.6": - LOG.warning("Your version of mbed-cloud-sdk may need updating: https://github.com/ARMmbed/mbed-cloud-sdk-python") - except: - LOG.critical('manifest-tool update commands require installation of the Pelion Device Management SDK: https://github.com/ARMmbed/mbed-cloud-sdk-python') - return 1 - return { - "prepare" : prepare.main, - "device" : device.main - }[options.update_action](options) diff --git a/manifesttool/update_device.py b/manifesttool/update_device.py deleted file mode 100644 index 214af8f..0000000 --- a/manifesttool/update_device.py +++ /dev/null @@ -1,289 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- - -import logging, sys -LOG = logging.getLogger(__name__) - -from manifesttool.v1.create import main as create_v1 -from urllib3.exceptions import MaxRetryError -import copy -import time -import tempfile -import os -import os.path -import shutil -import json -from manifesttool import defaults - -STOP_STATES = {'autostopped', - 'conflict', - 'expired', - 'manifestremoved', - 'quotaallocationfailed', - 'userstopped'} - -MAX_NAME_LEN = 128 # The update API has a maximum name length of 128, but this is not queriable. - -def main(options): - try: - # import mbed_cloud.update - from mbed_cloud.update import UpdateAPI - # from mbed_cloud.device_directory import DeviceDirectoryAPI - import mbed_cloud.exceptions - except: - LOG.critical('manifest-tool update commands require installation of the Pelion Device Management SDK:' - ' https://github.com/ARMmbed/mbed-cloud-sdk-python') - return 1 - - LOG.debug('Preparing an update on Pelion Device Management') - # upload a firmware - api = None - # dd_api = None - try: - # If set use api key set in manifest-tool update. - if hasattr(options, 'api_key') and options.api_key: - tempKey = options.api_key - config = {'api_key': tempKey} - api = UpdateAPI(config) - # Otherwise use API key set in manifest-tool init - else: api = UpdateAPI() - # dd_api = DeviceDirectoryAPI() - - except ValueError: - LOG.critical('API key is required to connect to the Update Service. It can be added using manifest-tool init -a' - ' or by manually editing .mbed_cloud_config.json') - return 1 - - manifestInput = { - 'applyImmediately' : True - } - - try: - if os.path.exists(defaults.config): - with open(defaults.config) as f: - manifestInput.update(json.load(f)) - if not options.input_file.isatty(): - content = options.input_file.read() - if content and len(content) >= 2: #The minimum size of a JSON file is 2: '{}' - manifestInput.update(json.loads(content)) - except ValueError as e: - LOG.critical("JSON Decode Error: {}".format(e)) - return 1 - - payload_filePath = manifestInput.get("payloadFile", None) - if options.payload: - payload_filePath = options.payload.name - - if not payload_filePath: - LOG.critical('Either -p/--payload must be specified or a payload file must be provided via -i.') - return 1 - - if not options.payload_name: - name = os.path.basename(payload_filePath) + time.strftime('-%Y-%m-%dT%H:%M:%S') - LOG.info('Using {} as payload name.'.format(name)) - options.payload_name = name - if len(options.payload_name) > MAX_NAME_LEN: - LOG.critical( - 'Payload name is too long. Maximum length is {size}. ("{base}" <- {size}. overflow -> "{overflow}")'.format( - size=MAX_NAME_LEN, base=options.payload_name[:MAX_NAME_LEN], - overflow=options.payload_name[MAX_NAME_LEN:])) - return 1 - - if not options.manifest_name: - name = os.path.basename(payload_filePath) + time.strftime('-%Y-%m-%dT%H:%M:%S-manifest') - LOG.info('Using {} as manifest name.'.format(name)) - options.manifest_name = name - - if len(options.manifest_name) > MAX_NAME_LEN: - LOG.critical( - 'Manifest name is too long. Maximum length is {size}. ("{base}" <- {size}. overflow -> "{overflow}")'.format( - size=MAX_NAME_LEN, base=options.manifest_name[:MAX_NAME_LEN], - overflow=options.manifest_name[MAX_NAME_LEN:])) - return 1 - campaign_name = os.path.basename(payload_filePath) + time.strftime('-%Y-%m-%dT%H:%M:%S-campaign') - if len(campaign_name) > MAX_NAME_LEN: - LOG.critical( - 'Campaign name is too long. Maximum length is {size}. ("{base}" <- {size}. overflow -> "{overflow}")'.format( - size=MAX_NAME_LEN, base=campaign_name[:MAX_NAME_LEN], - overflow=campaign_name[MAX_NAME_LEN:])) - return 1 - query_name = payload_filePath + time.strftime('-%Y-%m-%dT%H:%M:%S-filter') - if len(query_name) > MAX_NAME_LEN: - LOG.critical( - 'Filter name is too long. Maximum length is {size}. ("{base}" <- {size}. overflow -> "{overflow}")'.format( - size=MAX_NAME_LEN, base=query_name[:MAX_NAME_LEN], - overflow=query_name[MAX_NAME_LEN:])) - return 1 - - - payload = None - manifest = None - campaign = None - RC = 0 - handled = False - manifest_file = None - tempdirname = tempfile.mkdtemp() - try: - kwArgs = {} - if options.payload_description: - kwArgs['description'] = options.payload_description - try: - payload = api.add_firmware_image( - name = options.payload_name, - datafile = payload_filePath, - **kwArgs) - except mbed_cloud.exceptions.CloudApiException as e: - # TODO: Produce a better failuer message - LOG.critical('Upload of payload failed with:\n{}'.format(e).rstrip()) - handled = True - LOG.critical('Check API server URL "{}"'.format(api.config["host"])) - raise e - except MaxRetryError as e: - LOG.critical('Upload of payload failed with:\n{}'.format(e)) - handled=True - LOG.critical('Failed to establish connection to API-GW') - LOG.critical('Check API server URL "{}"'.format(api.config["host"])) - raise e - - LOG.info("Created new firmware at {}".format(payload.url)) - # create a manifest - create_opts = copy.copy(options) - create_opts.uri = payload.url - create_opts.payload = options.payload - - if not (hasattr(create_opts, "output_file") and create_opts.output_file): - try: - manifest_file = open(os.path.join(tempdirname,'manifest'),'wb') - LOG.info("Created temporary manifest file at {}".format(manifest_file.name)) - create_opts.output_file = manifest_file - except IOError as e: - LOG.critical("Failed to create temporary manifest file with:") - print(e) - LOG.critical("Try using '-o' to output a manifest file at a writable location.") - handled = True - raise e - try: - rc = create_v1(create_opts, manifestInput) - except IOError as e: - LOG.critical("Failed to create manifest with:") - print(e) - handled = True - raise e - - if rc: - return rc - - kwArgs = {} - if options.manifest_description: - kwArgs['description'] = options.manifest_description - - manifest_path = create_opts.output_file.name - create_opts.output_file.close() - # upload a manifest - try: - manifest = api.add_firmware_manifest( - name = options.manifest_name, - datafile = manifest_path, - **kwArgs) - except mbed_cloud.exceptions.CloudApiException as e: - # TODO: Produce a better failure message - LOG.critical('Upload of manifest failed with:') - print(e) - LOG.critical("Try using '-o' to output a manifest file at a writable location.") - handled = True - raise e - - LOG.info('Created new manifest at {}'.format(manifest.url)) - LOG.info('Manifest ID: {}'.format(manifest.id)) - - try: - campaign = api.add_campaign( - name = campaign_name, - manifest_id = manifest.id, - device_filter = {'id': { '$eq': options.device_id }}, - ) - except mbed_cloud.exceptions.CloudApiException as e: - LOG.critical('Campaign creation failed with:') - print(e) - handled = True - raise e - - LOG.info('Campaign successfully created. Current state: %r' % (campaign.state)) - LOG.info('Campaign successfully created. Filter result: %r' % (campaign.device_filter)) - - LOG.info("Starting the update campaign...") - - # By default a new campaign is created with the 'draft' status. We can manually start it. - try: - new_campaign = api.start_campaign(campaign) - new_campaign = None - except mbed_cloud.exceptions.CloudApiException as e: - LOG.critical('Starting campaign failed with:') - print(e) - handled = True - raise e - - LOG.info("Campaign successfully started. Current state: %r. Checking updates.." % (campaign.state)) - oldstate = api.get_campaign(campaign.id).state - LOG.info("Current state: %r" % (oldstate)) - timeout = options.timeout - while timeout != 0: - c = api.get_campaign(campaign.id) - if oldstate != c.state: - LOG.info("Current state: %r" % (c.state)) - oldstate = c.state - if c.state in STOP_STATES: - LOG.info("Finished in state: %r" % (c.state)) - break - time.sleep(1) - if timeout > 0: - timeout -= 1 - if timeout == 0: - LOG.critical("Campaign timed out") - RC = 1 - - except KeyboardInterrupt as e: - LOG.critical('User Aborted... Cleaning up.') - RC = 1 - except: - if not handled: - LOG.critical('Unhandled Exception:') - import traceback - traceback.print_exc(file=sys.stdout) - RC = 1 - finally: - # cleanup - if manifest_file: - manifest_file.close() - shutil.rmtree(tempdirname) - if not options.no_cleanup: - LOG.info("** Deleting update campaign and manifest **") - try: - if campaign and campaign.id: - api.delete_campaign(campaign.id) - if manifest and manifest.id: - api.delete_firmware_manifest(manifest.id) - if payload and payload.id: - api.delete_firmware_image(payload.id) - # dd_api.delete_query(new_query.id) - except mbed_cloud.exceptions.CloudApiException as e: - LOG.critical('Cleanup of campaign failed with:') - print(e) - RC = 1 - return RC diff --git a/manifesttool/utils.py b/manifesttool/utils.py deleted file mode 100644 index 45a9cbe..0000000 --- a/manifesttool/utils.py +++ /dev/null @@ -1,203 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -from __future__ import division -import sys, time, collections, hashlib, logging -from manifesttool import __version__ as uc_version -from manifesttool import codec -import os - -from pyasn1.codec.der import encoder as der_encoder -from pyasn1.error import PyAsn1Error - -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives.kdf.hkdf import HKDF - -from future.moves.urllib.request import urlopen, Request -from future.moves.urllib.parse import urlparse, urlencode -from future.moves.urllib.error import HTTPError, URLError - -from builtins import bytes - -LOG = logging.getLogger(__name__) - -def fatal(message, *args): - """Log a fatal error and exit with an unsuccessful code.""" - LOG.critical(message, *args) - sys.exit(1) - -def read_file(fname): - with open(fname, 'rb') as f: - return f.read() - -def calculate_hash(options, m): - md = hashes.Hash(hashes.SHA256(), backend=default_backend()) - md.update(m) - return md.finalize() - -def sha_hash(content): - sha = hashlib.sha256() - sha.update(content) - return sha.digest() - -def read_file_chunked(options, fd): - data = fd.read(options.chunk_size) - while data: - yield data - data = fd.read(options.chunk_size) - -def hash_file(options, fname): - if not hasattr(options,'hash') or not options.hash: - options.hash = 'sha256' - md = { - 'sha256' : hashes.Hash(hashes.SHA256(), backend=default_backend()) - }.get(options.hash, None) - - if not hasattr(options,'chunk_size') or not options.chunk_size: - options.chunk_size = 4096 - with open(fname,'rb') as fd: - for chunk in read_file_chunked(options, fd): - md.update(chunk) - return md.finalize() - -def size_file(options, fname): - return os.path.getsize(fname) - -def getDevicePSK_HKDF(mode, masterKey, vendorId, classId, keyUsage): - # Construct the device PSK - # Device UUID is the IKM. - hashAlg = { - 'aes-128-ctr-ecc-secp256r1-sha256' : hashes.SHA256, - 'none-ecc-secp256r1-sha256': hashes.SHA256, - 'none-none-sha256': hashes.SHA256, - 'none-psk-aes-128-ccm-sha256': hashes.SHA256, - 'psk-aes-128-ccm-sha256': hashes.SHA256 - }.get(mode) - - hkdf = HKDF( - algorithm = hashAlg(), - length = 128//8, - # The master key is the salt - salt = masterKey, - # Device Vendor ID + Device Class ID is the info - info = keyUsage + vendorId + classId, - backend = default_backend() - ) - return hkdf - -def download_file(url): - # Create request structure - LOG.debug('Trying to download: {}'.format(url)) - try: - req = Request(url) - except ValueError as e: - fatal('Client error. Could not download %r as the URL is invalid. Error: %r', url, str(e)) - req.add_header('User-Agent', 'ARM Update Client/%s)' % uc_version) - - # Read and return - try: - r = urlopen(req) - content = r.read() - r.close() - return content - except URLError as e: - fatal('Could not download %r. Client error: %r', url, str(e)) - except HTTPError as e: - fatal('Could not download %r. Server error: %r', url, str(e)) - -def todict(obj): - """ - Recursively convert a Python object graph to sequences (lists) - and mappings (dicts) of primitives (bool, int, float, string, ...) - http://stackoverflow.com/a/22679824/503866 - """ - if sys.version_info.major == 3 and isinstance(obj, (str,bytes)): - return obj - elif sys.version_info.major == 2 and isinstance(obj, (str,bytes,unicode)): - return obj - elif isinstance(obj, dict): - return dict((key, todict(val)) for key, val in obj.items() if val is not None) - elif isinstance(obj, collections.Iterable): - return [todict(val) for val in obj] - elif hasattr(obj, '__dict__'): - return todict(vars(obj)) - elif hasattr(obj, '__slots__'): - return todict(dict((name, getattr(obj, name)) for name in getattr(obj, '__slots__'))) - return obj - -def override_kwargs(obj, kwargs): - for key, value in kwargs.items(): - if not value: - continue - if hasattr(obj, key): - setattr(obj, key, value) - -def encode(data, options, schema): - encoder = { - 'der': der_encoder, - }[options.encoding] - - try: - asn = codec.obj2asn(data, schema) - output = encoder.encode(asn) - return output - except PyAsn1Error as err: - import traceback - # exc_type, exc_value, exc_traceback = sys.exc_info() - # traceback.print_stack() - # traceback.print_tb(exc_traceback) - LOG.critical('PyAsn1Error. This is propbably a bug. Could not encode ' - 'generated manifest.\nEnsure all fields are properly defined and ' - 'provided. Also check, in the case of the manifest changing, that ' - 'the generated "manifest_definition.py" file is up to date. The file can ' - 'be re-generated with the asn1py.py tool. Error message: "{0}"'.format(err)) - return None - -def skipAhead(code): - rc = 0 - if code == 0x81: - rc = 1 - if code == 0x82: - rc = 2 - if code == 0x83: - rc = 3 - if code == 0x83: - rc = 4 - return rc - -def detect_version(input_file): - # 32 bytes is currently sufficient to detect the manifest type. - headerData = bytes(input_file.read(32)) - input_file.seek(0) - # In both cases, the manifest starts with a DER SEQUENCE tag. - if headerData[0] != 0x30: - LOG.critical("input file is not a manifest.") - return None - # skip past the length - pos = 2 + skipAhead(headerData[1]) - - version = None - # For version 1, the first object in the SEQUENCE should be another SEQUENCE - if headerData[pos] == 0x30: - version = '1' - # For version 2+, a CMS wrapper is used, so the tag should be an OID tag - if headerData[pos] == 0x06: - version = '2' - - return version diff --git a/manifesttool/v1/create.py b/manifesttool/v1/create.py deleted file mode 100644 index 5eca50d..0000000 --- a/manifesttool/v1/create.py +++ /dev/null @@ -1,821 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -from __future__ import division -import codecs, hashlib, sys, json, os, base64, binascii, logging, ecdsa, uuid -# We use subprocess inline with the guidelines detailed here, so we ignore -# bandit warnings -# https://bandit.readthedocs.io/en/latest/plugins/b603_subprocess_without_shell_equals_true.html -import subprocess #nosec -import tempfile -from collections import namedtuple - -# from pyasn1 import debug -# debug.setLogger(debug.Debug('all')) - -from cryptography.hazmat.primitives import ciphers as cryptoCiphers -from cryptography.hazmat.primitives import hashes as cryptoHashes -from cryptography.hazmat.primitives.ciphers.aead import AESCCM -from cryptography.hazmat import backends as cryptoBackends -from cryptography import x509 - -from manifesttool import utils, codec, errorhandler, defaults -from manifesttool.v1.manifest_schema import SignedResource, Resource, ResourceSignature, ResourceReference, \ - Manifest, CertificateReference, PayloadDescription, ResourceAlias, \ - SignatureBlock, MacBlock -from manifesttool.v1 import manifest_definition -from manifesttool import keytable_pb2 - - -# Import different encoders -from pyasn1.codec.der import encoder as der_encoder -from pyasn1.codec.native import decoder as native_decoder -from pyasn1.error import PyAsn1Error -from pyasn1.type.univ import OctetString, Sequence -from pyasn1.type import namedtype - -from builtins import bytes - -nonceSize = 16 - -LOG = logging.getLogger(__name__) - -def manifestGet(manifest, path, shortpath = None): - if shortpath: - fieldValue = manifestGet(manifest, path = shortpath) - if fieldValue: - return fieldValue - pathList = path.split('.') - subManifest = manifest - while subManifest and pathList: - subManifest = subManifest.get(pathList[0]) - pathList = pathList[1:] - if subManifest and not isinstance(subManifest, (str, bytes, int, bool, dict, list)): - subManifest = str(subManifest) - return subManifest - -class cryptoMode: - _mode = namedtuple('CryptoMode', 'name,symSize,hashSize,payloadEncrypt') - MODES = { - 0: _mode('invalid', None, None, None), - 1: _mode('aes-128-ctr-ecc-secp256r1-sha256', 128/8, 256/8, True), - 2: _mode('none-ecc-secp256r1-sha256', 128/8, 256/8, False), - 3: _mode('none-none-sha256', 128/8, 256/8, False), - 4: _mode('none-psk-aes-128-ccm-sha256', 128/8, 256/8, False), - 5: _mode('psk-aes-128-ccm-sha256', 128/8, 256/8, True) - } - @staticmethod - def name2enum(name): - for k,v in cryptoMode.MODES.items(): - if v.name == name: - return k - else: - return None - def __init__(self, mode): - m = self.MODES.get(mode) - self.symSize = m.symSize - self.hashSize = m.hashSize - self.payloadEncrypt = m.payloadEncrypt - self.name = m.name - -def ARM_UC_mmCryptoModeShouldEncrypt(mode): - return cryptoMode(mode).payloadEncrypt - - -def encryptClearText(cleartext, key, iv): - backend = cryptoBackends.default_backend() - iv_counter = int.from_bytes(bytes(iv), byteorder='big') - # Create the cipher object - cipher = cryptoCiphers.Cipher(cryptoCiphers.algorithms.AES(key), cryptoCiphers.modes.CTR(iv), backend=backend) - encryptor = cipher.encryptor() - # Encrypt the plain text - ciphertext = encryptor.update(bytes(cleartext)) + encryptor.finalize() - return ciphertext - -def encryptKeyAES(options, manifestInput, encryptionInfo, payload): - # Store the PSK ID - pskId = manifestGet(manifestInput, 'resource.resource.manifest.payload.encryptionInfo.id.key', 'encryptionKeyId') - if not pskId: - LOG.critical('The aes-psk encryption mode requires a "encryptionKeyId" entry in the input JSON file') - sys.exit(1) - encryptionInfo["id"] = { "key" : codecs.decode(pskId, 'hex')} - secret = options.payload_secret - - # Read the secret - secret_data = utils.read_file(secret) if os.path.isfile(secret) else base64.b64decode(secret) - if not secret_data: - LOG.critical('The aes-psk encryption mode requires either a base64-encoded secret or a valid file to be passed via the "-s" option.') - sys.exit(1) - - # generate an IV - IV = os.urandom(nonceSize) - # generate a new key - key = os.urandom(nonceSize) - - cipherpayload = encryptClearText(payload, key, IV) - - # NOTE: In general, ECB is a poor choice, since it fails quickly to known-plaintext attacks. In this case, however, - # ECB should be appropriate, since the plaintext is precisely one AES block, and it is comprised of high entropy - # random data; therefore, the plaintext is never known. - - # Create the cipher object - cipher = cryptoCiphers.Cipher(cryptoCiphers.algorithms.AES(bytes(secret_data)), - cryptoCiphers.modes.ECB(), backend=backend) # nosec ignore bandit B404 - keyEncryptor = cipher.encryptor() - # Encrypt the plain text - cipherKey = keyEncryptor.update(bytes(key)) + encryptor.finalize() - return ciphertext - - return IV, cipherKey, cipherpayload - -def get_payload_description(options, manifestInput): - crypto_mode = manifestGet(manifestInput, 'resource.resource.manifest.encryptionMode.enum', 'encryptionMode') - crypto_mode = crypto_mode if crypto_mode in cryptoMode.MODES else cryptoMode.name2enum(crypto_mode) - if not crypto_mode: - crypto_mode = get_crypto_mode(options, manifestInput) - crypto_name = cryptoMode.MODES.get(crypto_mode).name - - payload_format = manifestGet(manifestInput, 'resource.resource.manifest.payload.enum', 'payloadFormat') - if payload_format: - LOG.debug('Found payload format in input: {}'.format(payload_format)) - else: - payload_format = 'raw-binary' - if hasattr(options, 'payload_format') and options.payload_format: - payload_format = options.payload_format - - payload_format = { - 'raw-binary' : 1, - 'bsdiff-stream' : 5 - }.get(payload_format, 1) - - payload_file = manifestGet(manifestInput, 'resource.resource.manifest.payload.reference.file', 'payloadFile') - if hasattr(options, 'payload') and options.payload: - payload_file = options.payload.name - # payload URI defaults to the payload file path if no payload URI is supplied. - payload_uri = payload_file - payload_uri = manifestGet(manifestInput, 'resource.resource.manifest.payload.reference.uri', 'payloadUri') - if hasattr(options, 'uri') and options.uri: - payload_uri = options.uri - - dependencies = manifestGet(manifestInput, 'resource.resource.manifest.dependencies') - if not any((payload_uri, payload_file)) and not dependencies: - LOG.critical('No payload was specified and no dependencies were provided.') - sys.exit(1) - # fwFile/fwUri is optional, so if not provided we just return empty - return None - - payload_hash = manifestGet(manifestInput, 'resource.resource.manifest.payload.reference.hash', 'payloadHash') - payload_size = manifestGet(manifestInput, 'resource.resource.manifest.payload.reference.size', 'payloadSize') - if payload_hash: - LOG.debug('Found hash in input, skipping payload load. Hash: {}'.format(payload_hash)) - payload_hash = binascii.a2b_hex(payload_hash) - else: - if not payload_file: - LOG.critical('Either -p/--payload must be specified or a payload hash must be provided via -i.') - sys.exit(1) - payload_filePath = payload_file - # If file path is not absolute, then make it relative to input file - if os.path.isabs(payload_file) or not options.input_file.isatty(): - payload_filePath = os.path.join(os.path.dirname(options.input_file.name), payload_file) - # Read payload input, record length and hash it - payload_size = utils.size_file(options, payload_filePath) - payload_hash = utils.hash_file(options, payload_filePath) - LOG.debug('payload of {} bytes loaded. Hash: {}'.format(payload_size, binascii.b2a_hex(payload_hash))) - - # Ensure the cryptoMode is valid - if not crypto_mode in cryptoMode.MODES: - valid_modes = ", ".join((('%s (%d)' % (v.name, k) for k, v in cryptoMode.MODES.items()))) - LOG.critical('Could not find specified cryptoMode (%d) in list of valid encryption modes. ' - 'Please use on of the following: %r' % (crypto_mode, valid_modes)) - sys.exit(1) - - # Get encryption options for the provided mode - should_encrypt = ARM_UC_mmCryptoModeShouldEncrypt(crypto_mode) - if hasattr(options, 'encrypt_payload') and options.encrypt_payload and not should_encrypt: - LOG.critical('--encrypt-payload specified, but cryptoMode({cryptoMode}) does not support encryption.'.format(**manifestInput)) - sys.exit(1) - - encryptionInfo = None - if should_encrypt: - LOG.debug('Crypto mode {} ({}) requires encryption. Will ensure ciphers are valid and loaded...'\ - .format(crypto_mode, crypto_name)) - if not options.encrypt_payload: - LOG.critical('Specified crypto mode ({cryptoMode}) requires encryption, ' - 'but --encrypt-payload not specified.'.format(**manifestInput)) - sys.exit(1) - cipherFile = manifestGet(manifestInput, 'resource.resource.manifest.payload.encryptionInfo.file', 'encryptedPayloadFile') - if not cipherFile: - LOG.critical('"resource.resource.manifest.payload.encryptionInfo.file" must be specified in the JSON input' - 'file when --encrypt-payload is specified on the command-line.') - sys.exit(1) - encryptionInfo = {} - - cipherModes = { - 'aes-psk' : encryptKeyAES - } - - if not options.encrypt_payload in cipherModes: - LOG.critical('Specified encryption mode "{mode}" is not supported'.format(mode=options.encrypt_payload)) - sys.exit(1) - - init_vector, cipherKey, cipherpayload = cipherModes.get(options.encrypt_payload)(options, manifestInput, encryptionInfo, content) - - with open(cipherFile,'wb') as f: - f.write(cipherpayload) - - encryptionInfo["key"] = { "cipherKey": cipherKey } - encryptionInfo["initVector"] = init_vector - LOG.debug('payload ({} bytes) encrypted. Cipher key: {}, cipher payload ouptut to : {}'.format(len(content), cipherKey, cipherFile)) - - else: - LOG.debug('Will not encrypt payload as crypto mode {} ({}) does not require it'.format(crypto_mode, crypto_name)) - - installedDigest = manifestGet(manifestInput, 'installedDigest') - installedSize = manifestGet(manifestInput, 'installedSize') - installedFile = manifestGet(manifestInput, 'installedFile') - if installedFile and not installedDigest and not installedSize: - installedFilePath = installedFile - # If file path is not absolute, then make it relative to input file - if os.path.isabs(installedFilePath): - installedFilePath = os.path.join(os.path.dirname(options.input_file.name), installedFilePath) - # Read payload input, record length and hash it - installedSize = utils.size_file(options, installedFilePath) - installedDigest = utils.hash_file(options, installedFilePath) - LOG.debug('payload of {} bytes loaded. Hash: {}'.format(installedSize, binascii.b2a_hex(installedDigest))) - - return PayloadDescription( - **{ - "storageIdentifier": manifestGet(manifestInput,'resource.resource.manifest.payload.storageIdentifier', 'storageIdentifier') or "default", - "reference": ResourceReference( - hash = payload_hash, - uri = payload_uri, - size = payload_size - ), - "encryptionInfo": encryptionInfo, - "format" : payload_format, - "installedSize":installedSize, - "installedDigest":installedDigest - } - ) - -def get_manifest_aliases(options, manifestInput): - aliases = [] - for alias in manifestGet(manifestInput,'resource.resource.manifest.aliases') or []: - # Ensure all required options are defined - if not all(k in alias for k in ('file', 'uri')): - LOG.critical('Could not create aliases, as all required keys for alias are not defined ("uri" and "file")') - sys.exit(1) - - # Read alias file to calculate hash - fPath = alias['file'] - if not os.path.isabs(fPath): - fPath = os.path.join(os.path.dirname(options.input_file.name), fPath) - content = utils.read_file(fPath) - sha_hash = utils.sha_hash(content) - LOG.debug('Creating ResourceAlias for file {} with SHA reference {}'.format(fPath, sha_hash)) - - aliases.append(ResourceAlias( - hash = sha_hash, - uri = alias['uri'] - )) - return aliases - -def get_manifest_dependencies(options, manifestInput): - dependencies = [] - for link in manifestGet(manifestInput, 'resource.resource.manifest.dependencies') or []: - if not any(k in link for k in ('uri', 'file')): - LOG.critical('Manifest link requires either a "uri" or a "file"' - 'key - or both. Could only find %r' % link.keys()) - sys.exit(1) - LOG.debug('Adding manifest link reference (URI: {}, File: {})'.format(link.get('uri', None), link.get('file', None))) - - # If file isn't provided, we attempt to download the file from provided URI - # If the user provides the link as a filepath, just read the file - if 'file' in link: - linkPath = link['file'] - if not os.path.isabs(linkPath): - linkPath = os.path.join(os.path.dirname(options.input_file.name), linkPath) - content = utils.read_file(linkPath) - else: - content = utils.download_file(link['uri']) - - # Calculate the hash and length. - manifest_hash = utils.sha_hash(content) - manifest_length = len(content) - LOG.debug('Linked manifest of {} bytes loaded. Hash: {}'.format(manifest_length, manifest_hash)) - - link_uri = link['uri'] if 'uri' in link else link['file'] - dependencies.append({ - 'hash': manifest_hash, - 'uri': link_uri, - 'size': manifest_length - }) - return dependencies - -def get_crypto_mode(options, manifestInput): - crypto_mode = manifestGet(manifestInput, 'resource.resource.manifest.encryptionMode.enum', 'encryptionMode') - crypto_mode = crypto_mode if crypto_mode in cryptoMode.MODES else cryptoMode.name2enum(crypto_mode) - if not crypto_mode: - isEncrypted = hasattr(options, 'encrypt_payload') and options.encrypt_payload - isMAC = hasattr(options, 'mac') and options.mac - - if isEncrypted and isMAC: - cryptname = 'psk-aes-128-ccm-sha256' - if not isEncrypted and isMAC: - cryptname = 'none-psk-aes-128-ccm-sha256' - if not isEncrypted and not isMAC: - cryptname = 'none-ecc-secp256r1-sha256' - if isEncrypted and not isMAC: - cryptname = 'aes-128-ctr-ecc-secp256r1-sha256' - crypto_mode = cryptoMode.name2enum(cryptname) - - return crypto_mode - -def get_manifest(options, manifestInput): - vendor_info = manifestGet(manifestInput, 'resource.resource.manifest.vendorInfo', 'vendorInfo') or b"" - vendor_id = manifestGet(manifestInput, 'resource.resource.manifest.vendorId', 'vendorId') - device_id = manifestGet(manifestInput, 'resource.resource.manifest.deviceId', 'deviceId') - class_id = manifestGet(manifestInput, 'resource.resource.manifest.classId', 'classId') - - if not device_id and not (vendor_id and class_id): - LOG.critical('Input file must contain either Device ID, or both Vendor and Class IDs, or all three\n' - 'deviceId:"{}"\nvendorId:"{}"\nclassId:"{}"'.format(device_id, vendor_id, class_id)) - sys.exit(1) - - validTo = manifestGet(manifestInput, 'resource.resource.manifest.applyPeriod.validTo', 'applyPeriod.validTo') - validFrom = manifestGet(manifestInput, 'resource.resource.manifest.applyPeriod.validFrom', 'applyPeriod.validFrom') - applyPeriod = None - if validTo or validFrom: - applyPeriod = { - 'validFrom' : validFrom, - 'validTo' : validTo, - } - - crypto_mode = { 'enum' : get_crypto_mode(options, manifestInput) } - nonce = manifestGet(manifestInput, 'resource.resource.manifest.nonce') - if nonce: - nonce = binascii.a2b_hex(nonce) - else: - nonce = os.urandom(nonceSize) - if not manifestGet(manifestInput, 'resource.resource.manifest.applyImmediately', 'applyImmediately'): - LOG.warning('applyImmediately is currently ignored by the update client; manifests are always applied immediately.') - - manifestVersion = manifestGet(manifestInput,'resource.resource.manifest.version') - precursorDigest = manifestGet(manifestInput, 'precursorDigest') - precursorFile = manifestGet(manifestInput, 'precursorFile') - priority = manifestGet(manifestInput, 'priority') - installedDigest = manifestGet(manifestInput, 'installedDigest') - installedSize = manifestGet(manifestInput, 'installedSize') - installedFile = manifestGet(manifestInput, 'installedFile') - - if manifestVersion: - pass - else: - manifestVersion = 'v1' - - if precursorFile and not precursorDigest: - precursorDigest = utils.hash_file(options, precursorFile) - - return Manifest( - manifestVersion = manifestVersion, - vendorId = uuid.UUID(vendor_id).bytes if vendor_id else b'', - classId = uuid.UUID(class_id).bytes if class_id else b'', - deviceId = uuid.UUID(device_id).bytes if device_id else b'', - nonce = nonce, - vendorInfo = binascii.a2b_hex(vendor_info), - applyPeriod = applyPeriod, - precursorDigest = precursorDigest, - applyImmediately = manifestGet(manifestInput, 'resource.resource.manifest.applyImmediately', 'applyImmediately'), - priority = priority, - encryptionMode = crypto_mode, - description = manifestGet(manifestInput, 'resource.resource.manifest.description', 'description'), - aliases = get_manifest_aliases(options, manifestInput), - payload = get_payload_description(options, manifestInput), - dependencies = get_manifest_dependencies(options, manifestInput), - timestamp = manifestGet(manifestInput, 'resource.resource.manifest.timestamp') - ) - -def getDevicePSKData(mode, psk, nonce, digest, payload_key): - crypto_mode = cryptoMode(mode) - LOG.debug('Creating PSK data: ') - LOG.debug(' mode: {}'.format(crypto_mode.name)) - LOG.debug(' iv ({0} bytes): {1}'.format(len(nonce), binascii.b2a_hex(nonce))) - LOG.debug(' md ({0} bytes): {1}'.format(len(digest), binascii.b2a_hex(digest))) - data = {'hash':digest} - if payload_key: - data['cek'] = payload_key - asnData = native_decoder.decode(data, asn1Spec=manifest_definition.KeyTableEntry()) - - plainText = der_encoder.encode(asnData) - LOG.debug('PSK plaintext ({0} bytes): {1}'.format(len(plainText), binascii.b2a_hex(plainText))) - - pskSig = { - 'none-psk-aes-128-ccm-sha256': lambda key, iv, d: AESCCM(key[:128//8]).encrypt(iv, d, b''), - 'psk-aes-128-ccm-sha256': lambda key, iv, d: AESCCM(key[:128//8]).encrypt(iv, d, b'') - }.get(crypto_mode.name, lambda a,b,d: None)(psk, nonce, plainText) - LOG.debug('PSK data ({0} bytes): {1}'.format(len(pskSig), binascii.b2a_hex(pskSig))) - return pskSig - -def symmetricArgsOkay(options): - okay = hasattr(options, 'private_key') and options.private_key - # okay = okay and hasattr(options, 'psk_table_encoding') and options.psk_table_encoding - if hasattr(options, 'psk_table_encoding') and options.psk_table_encoding: - okay = okay and True - okay = okay and hasattr(options, 'psk_table') and options.psk_table - return okay - -def isPsk(mode): - crypto_mode = cryptoMode(mode) - return { - 'aes-128-ctr-ecc-secp256r1-sha256' : False, - 'none-ecc-secp256r1-sha256':False, - 'none-none-sha256': False, - 'none-psk-aes-128-ccm-sha256': True, - 'psk-aes-128-ccm-sha256': True - }.get(crypto_mode.name) - -def get_symmetric_signature(options, manifestInput, enc_data): - input_hash = manifestGet(manifestInput,'signature.hash') or b'' - - # There should always be a signing key on create. - if not hasattr(options,'private_key') or not options.private_key: - if 'psk-master-key' in manifestInput: - try: - options.private_key = open(manifestInput['psk-master-key'],'rb') - except: - LOG.critical('No PSK master key specified and default key ({}) cannot be opened'.format(manifestInput['private-key'])) - sys.exit(1) - else: - LOG.critical('Resource is not signed and no PSK master key is provided.') - sys.exit(1) - - if not symmetricArgsOkay(options): - LOG.critical('--mac requires:') - LOG.critical(' --private-key: The master key for generating device PSKs') - # 80 chars ->| - # ================================================================================ - LOG.critical(' --psk-table: the output file for PSKs. This argument is optional/ignored') - LOG.critical(' when inline encoding is used.') - LOG.critical(' --psk-table-encoding: the encoding to use for the PSK output file.') - LOG.critical(' Either:') - LOG.critical(' --device-urn: The device URN for the target device (Endpoint Client Name)') - LOG.critical(' OR:') - LOG.critical(' --filter-id: The filter identifier used to gather device URNs') - sys.exit(1) - - # Get SHA-256 hash of content and sign it using private key - sha_content = utils.sha_hash(enc_data) - # If a hash is provided in the input json, then the encoded content must match the provided hash - if input_hash and sha_content != binascii.a2b_hex(input_hash): - LOG.critical('Manifest hash provided in input file does not match hashed output') - LOG.critical('Expected: {0}'.format(input_hash)) - LOG.critical('Actual: {0}'.format(binascii.b2a_hex(sha_content))) - sys.exit(1) - - # Load a default URN out of the settings file. - devices = manifestGet(manifestInput,'deviceURNs') or [] - LOG.info('Loaded device URNs from {!r}'.format(defaults.config)) - for dev in devices: - LOG.info(' {!r}'.format(dev)) - - # Optionally load a URN out of the command-line arguments - if hasattr(options, 'device_urn') and options.device_urn: - cmdDevs = [options.device_urn] - LOG.info('Loaded device URNs from input arguments') - for dev in cmdDevs: - LOG.info(' {!r}'.format(dev)) - devices.extend(cmdDevs) - if hasattr(options, 'filter_id') and options.filter_id: - LOG.critical('Device Filters not supported yet.') - sys.exit(1) - - # Use only unique devices - devices = list(set(devices)) - - crypto_mode = get_crypto_mode(options, manifestInput) - - payload_key = b'' - if hasattr(options, 'payload_key') and options.payload_key: - LOG.debug('Converting payload key ({0}) to binary'.format(options.payload_key)) - payload_key = bytes(binascii.a2b_hex(options.payload_key)) - LOG.debug('Payload key length: {0}'.format(len(payload_key))) - master_key = options.private_key.read() - vendor_id = manifestGet(manifestInput, 'resource.resource.manifest.vendorId', 'vendorId') - class_id = manifestGet(manifestInput, 'resource.resource.manifest.classId', 'classId') - iv = os.urandom(13) - deviceSymmetricInfos = {} - # For each device - maxIndexSize = 0 - maxRecordSize = 0 - LOG.info('Creating per-device validation codes...') - for device in devices: - LOG.info(' {!r}'.format(device)) - - hkdf = utils.getDevicePSK_HKDF(cryptoMode(crypto_mode).name, master_key, uuid.UUID(vendor_id).bytes, uuid.UUID(class_id).bytes, b'Authentication') - psk = hkdf.derive(bytes(device, 'utf-8')) - maxIndexSize = max(maxIndexSize, len(device)) - # Now encrypt the hash with the selected AE algorithm. - pskCipherData = getDevicePSKData(crypto_mode, psk, iv, sha_content, payload_key) - recordData = der_encoder.encode(OctetString(hexValue=binascii.b2a_hex(pskCipherData).decode("ascii"))) - maxRecordSize = max(maxRecordSize, len(recordData)) - deviceSymmetricInfos[device] = recordData - # print (deviceSymmetricInfos) - def proto_encode(x): - keytable = keytable_pb2.KeyTable() - - for k, d in x.items(): - entry = keytable.entries.add() - entry.urn = k - entry.opaque = d - return keytable.SerializeToString() - # Save the symmetric info file - encodedSymmertricInfos = { - 'json' : lambda x : json.JSONEncoder(default=binascii.b2a_base64).encode(x), - 'cbor' : lambda x : None, - 'protobuf': proto_encode, - 'text' : lambda x : '\n'.join([','.join([binascii.b2a_hex(y) for y in (k,d)]) for k, d in x.items()]) + '\n' - # 'inline' : lambda x : None - }.get(options.psk_table_encoding)(deviceSymmetricInfos) - options.psk_table.write(encodedSymmertricInfos) - - #========================= - # PSK ID is the subject key identifier (hash) of the master key. - # The URI of the "certificate" is the location at which to find the key table or key query. - # PSK is known only to the signer and the device - # PSK Signature is AE(PSK, hash), but it is not included, since it must be distributed in the key table. - shaMaster = cryptoHashes.Hash(cryptoHashes.SHA256(), cryptoBackends.default_backend()) - shaMaster.update(master_key) - subjectKeyIdentifier = shaMaster.finalize() - - mb = MacBlock( pskID = subjectKeyIdentifier, - keyTableIV = iv, - keyTableRef = 'thismessage://1', - keyTableVersion = 0, - keyTableRecordSize = maxRecordSize, - keyTableIndexSize = maxIndexSize - ) - macs=[mb] - rs = ResourceSignature( - hash = sha_content, - signatures = [], - macs = macs) - return rs - - -def get_signature(options, manifestInput, enc_data): - signatures = manifestGet(manifestInput,'signature.signatures') or [] - input_hash = manifestGet(manifestInput,'signature.hash') or b'' - signing_tool = manifestGet(manifestInput, 'signing-tool') or '' - if getattr(options, 'signing_tool', None): - signing_tool = options.signing_tool - - - # There should always be a signing key or signing tool on create. - if not signing_tool and not getattr(options,'private_key', None): - if 'private-key' in manifestInput: - try: - options.private_key = open(manifestInput['private-key'],'r') - except: - LOG.critical('No private key specified and default key ({}) cannot be opened'.format(manifestInput['private-key'])) - sys.exit(1) - else: - LOG.critical('Resource is not signed and no signing key is provided.') - sys.exit(1) - - # Get SHA-256 hash of content and sign it using private key - sha_content = utils.sha_hash(enc_data) - if len(signatures): - # If a signature is provided in the input json, then the encoded content must match the provided hash - # Signature validation is not performed, since this would require certificate acquisition, which may not be - # possible - if sha_content != binascii.a2b_hex(input_hash): - LOG.critical('Manifest hash provided in input file does not match hashed output') - LOG.critical('Expected: {0}'.format(input_hash)) - LOG.critical('Actual: {0}'.format(binascii.b2a_hex(sha_content))) - sys.exit(1) - # TODO: perform best-effort signature validation - - signature = None - if signing_tool: - # get the key id - key_id = manifestGet(manifestInput, 'signing-key-id') - if hasattr(options, 'signing_key_id') and options.signing_key_id: - key_id = options.signing_key_id - digest_algo = 'sha256' - infile = None - with tempfile.NamedTemporaryFile(delete = False) as f: - infile = f.name - f.write(enc_data) - f.flush() - LOG.debug('Temporary manifest file: {}'.format(infile)) - outfile = None - with tempfile.NamedTemporaryFile(delete = False) as f: - outfile = f.name - LOG.debug('Temporary signature file: {}'.format(outfile)) - - try: - cmd = [signing_tool, digest_algo, key_id, infile, outfile] - LOG.debug('Running "{}" to sign manifest.'.format(' '.join(cmd))) - # This command line is constructed internally, so we ignore bandit - # warnings about executing a Popen. See: - # https://bandit.readthedocs.io/en/latest/plugins/b603_subprocess_without_shell_equals_true.html - p = subprocess.Popen(cmd) #nosec - p.wait() - if p.returncode != 0: - LOG.critical('Signing tool failed.') - sys.exit(1) - with open(outfile, 'rb') as f: - signature = f.read() - - except: - LOG.critical('Failed to execute signing tool.') - sys.exit(1) - finally: - os.unlink(infile) - os.unlink(outfile) - LOG.debug('Signature: {}'.format(binascii.b2a_hex(signature).decode('utf-8'))) - - elif hasattr(options, 'private_key') and options.private_key: - sk = ecdsa.SigningKey.from_pem(options.private_key.read()) - signature = sk.sign_digest(sha_content, sigencode=ecdsa.util.sigencode_der) - - certificates = [] - - # pick a signature block with no signature in it. - inputCerts = manifestGet(manifestInput, 'certificates') or [] - - # If no certificate was provided in the manifest input or in options, - if len(inputCerts) == 0: - # then load the default certificate - inputCerts = manifestInput.get('default-certificates', []) - - # If there is still no certificate, - if len(inputCerts) == 0: - # Search through all signature blocks for one that contains certificates but no signature - for idx, sb in enumerate(signatures): - if not 'signature' in sb: - inputCerts = sb.get('certificates', []) - # This signature will be appended later so we must trim it. - del signatures[idx] - break - - for idx, cert in enumerate(inputCerts): - if not any(k in cert for k in ('file', 'uri')): - LOG.critical('Could not find "file" or "uri" property for certificate') - sys.exit(1) - - # If 'file', we just use the content in local file - if 'file' in cert: - fPath = cert['file'] - if not os.path.isabs(fPath): - fPath = os.path.join(os.path.dirname(options.input_file.name), cert['file']) - content = utils.read_file(fPath) - - # Else we download the file contents - else: - content = utils.download_file(cert['uri']) - # Figure our which extension the certificate has - contentPath = cert['file'] if 'file' in cert else cert['uri'] - ext = contentPath.rsplit('.', 1)[1] - - # Read the certificate file, and get DER encoded data - if ext == 'pem': - lines = content.replace(" ",'').split() - content = binascii.a2b_base64(''.join(lines[1:-1])) - - # Verify the certificate hash algorithm - # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280) - # fingerprint = utils.sha_hash(content) - cPath = cert['file'] if 'file' in cert else cert['uri'] - certObj = None - try: - certObj = x509.load_der_x509_certificate(content, cryptoBackends.default_backend()) - except ValueError as e: - LOG.critical("X.509 Certificate Error in ({file}): {error}".format(error=e, file=cPath)) - sys.exit(1) - - if not certObj: - LOG.critical("({file}) is not a valid certificate".format(file=cPath)) - sys.exit(1) - if not isinstance(certObj.signature_hash_algorithm, cryptoHashes.SHA256): - LOG.critical("In ({file}): Only SHA256 certificates are supported by the Device Management Update client at this time.".format(file=cPath)) - sys.exit(1) - fingerprint = certObj.fingerprint(cryptoHashes.SHA256()) - - LOG.debug('Creating certificate reference ({}) from {} with fingerprint {}'.format(idx, contentPath, fingerprint)) - uri = '' - if 'uri' in cert: - uri = cert['uri'] - certificates.append(CertificateReference( - fingerprint = fingerprint, - uri = uri - )) - - LOG.debug('Signed hash ({}) of encoded content ({} bytes) with resulting signature {}'.format( - sha_content, len(enc_data), signature)) - if signature: - signatures.append(SignatureBlock(signature = signature, certificates = certificates)) - return ResourceSignature( - hash = sha_content, - signatures = signatures - ) - -def create_signed_resource(options, manifestInput): - - - # Create the Resource structure first, and encode it using specified encoding scheme - # This encoded data will then be used for signing - try: - resource = Resource( - resource = get_manifest(options, manifestInput), - resourceType = Resource.TYPE_MANIFEST - ) - except errorhandler.InvalidObject as err: - LOG.critical('Unable to create resource object: {0}'.format(err)) - sys.exit(1) - - # Convert the Python object to a Python dictionary, and then encode to - # specified encoding format - resource_encoded = utils.encode(resource.to_dict(), options, manifest_definition.Resource()) - - signature = None - crypto_mode = get_crypto_mode(options, manifestInput) - if isPsk(crypto_mode): - signature = get_symmetric_signature(options, manifestInput, enc_data = resource_encoded) - else: - signature = get_signature(options, manifestInput, enc_data = resource_encoded) - try: - sresource = SignedResource( - resource = resource, - signature = signature - ) - return sresource.to_dict() - except errorhandler.InvalidObject as err: - LOG.critical('Unable to create signed resource: {0}'.format(err)) - sys.exit(1) - -def toCfile(varname, data, colwidth=120, indentsize=4): - s = '#include \n' - s += 'uint8_t {}[] = {{\n'.format(varname) - xl = ['{0:#04x}'.format(b) for b in bytes(data)] - # w = (ax + b*(x-1)) - # w = ax + bx - b - # (w + b) / (a + b) - rowcount = int((colwidth - indentsize + len(', ') - len(',')) / len(', 0x00')) - while len(xl): - rownum = min(rowcount,len(xl)) - row = ' ' + ', '.join(xl[:rownum]) - if len(xl) > rownum: - row += ',' - xl = xl[rownum:] - row += '\n' - s += row; - s += '};\n' - return codecs.encode(s, 'utf8') - -def write_result(data, options): - if hasattr(options,'hex') and options.hex: - LOG.debug('Converting binary data into hex encoded string') - data = codecs.encode(data, 'hex') - if hasattr(options,'c_file') and options.c_file: - LOG.debug('Converting binary data into a C file.') - data = toCfile('manifest', data) - - # Write result to output file or stdout buffer. - options.output_file.write(data) - - # Append newline if outputting to TTY - if hasattr(options, 'output_file') and options.output_file.isatty(): - options.output_file.write(b'\n') - -def main(options, manifestInput): - LOG.debug('Creating new manifest from input file and options') - - # Parse input files and options. Generate hydrated and hierachial manifest JSON. - manifest = create_signed_resource(options, manifestInput) - LOG.debug('Manifest python object successfully created from ASN.1 definition and input') - - # Encode data if requested - output = utils.encode(manifest, options, manifest_definition.SignedResource()) - LOG.debug('Manifest successfully encoded into desired format ({}). Size: {} bytes.'.format(options.encoding, len(output))) - - if hasattr(options, 'mac') and options.mac and options.psk_table_encoding == 'inline': - output += options.psk_table - - # And we're done - write_result(output, options) diff --git a/manifesttool/v1/manifest_schema.py b/manifesttool/v1/manifest_schema.py deleted file mode 100644 index 5662f69..0000000 --- a/manifesttool/v1/manifest_schema.py +++ /dev/null @@ -1,189 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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 a python class representation of the ASN.1 schema defined -# in manifest.asn. It is used to generate a JSON representation of the manifest -# from raw data. -# -# It differs from manifest_definition.py as it's not used by pyasn1, it's not used -# to encode the manifest data nor is it automatically generated. -# -# The process looks like: -# (Input data) -> (Python object representation) -> (JSON) -> (PyASN1 object) -> ([DER] encoding) -# [ this file ] -import time, collections -from manifesttool import utils -from manifesttool.errorhandler import InvalidObject - -class BaseObject(object): - - # Basic check to see if all required fields are set. - # Does NOT check if the set value is of right type accoridng to ASN.1 definition - def verify(self, required_fields): - for f in required_fields: - if self.__dict__.get(f) is None: - raise InvalidObject("Value for field %r not set, but it's required" % f) - - # Convinience method to just convert object to python dict - def to_dict(self): - return utils.todict(self) - -class Resource(BaseObject): - TYPE_MANIFEST, TYPE_FIRMWARE = range(2) - - def __init__(self, resource, resourceType, uri=None): - self.uri = uri - self.resourceType = resourceType - self.resource = resource - - # If type is manifest, then key is manifest. payload if not. - k = { - Resource.TYPE_MANIFEST: "manifest", - Resource.TYPE_FIRMWARE: "payload" - }[self.resourceType] - self.resource = { - k: resource - } - -class Manifest(BaseObject): - # Manifest version enum values - V1 = 1 - - # Encryption mode enum values - ENCRYPTION_MODE_INVALID = 0 - ENCRYPTION_MODE_AES_128 = 1 - ENCRYPTION_MODE_NONE_ECC = 2 - ENCRYPTION_MODE_NONE = 3 - ENCRYPTION_MODE_NONE_PSK_CCM_16 = 4 - ENCRYPTION_MODE_PSK_CCM_16 = 4 - - - def __init__(self, **kwargs): - # Set defaults - self.manifestVersion = Manifest.V1 - self.timestamp = int(time.time()) - self.deviceId = None - self.vendorId = None - self.classId = None - self.vendorInfo = None - self.description = None - self.nonce = None - self.applyImmediately = False - self.precursorDigest = None - self.priority = None - - # self.applyPeriod = { - # 'validFrom': int(time.time()), - # 'validTo': int(time.time()) + (3600 * 24 * 30) - # } - self.applyPeriod = None - self.encryptionMode = { - "enum" : Manifest.ENCRYPTION_MODE_NONE - } - self.aliases = [] - self.dependencies = [] - self.payload = None - - # Override with kwargs - for key, value in kwargs.items(): - if value is None: - continue - if hasattr(self, key): - setattr(self, key, value) - - # Check that all required fields are set - self.verify(["manifestVersion", "timestamp", "deviceId", "vendorId", "classId", "vendorInfo",\ - "applyImmediately", "dependencies", "nonce", "aliases"]) - -class PayloadDescription(BaseObject): - FORMAT_UNDEFINED = 0 - FORMAT_RAW_BINARY = 1 - FORMAT_CBOR = 2 - FORMAT_HEX_LOCATION_LENGTH_DATA = 3 - FORMAT_ELF = 4 - FORMAT_BSDIF_STREAM = 5 - - def __init__(self, **kwargs): - # Set defaults - if kwargs.get('format', None) is not None: - self.format = { "enum" : kwargs['format']} - else: - self.format = { - "enum": PayloadDescription.FORMAT_RAW_BINARY - } - self.encryptionInfo = None - self.storageIdentifier = None - self.reference = None - self.version = None - self.installedDigest = None - self.installedSize = None - - # Override with kwargs - for key, value in kwargs.items(): - if value is None: - continue - if key is "format": - continue - if hasattr(self, key): - setattr(self, key, value) - - # Verify that all required fields are set - self.verify(["format", "storageIdentifier", "reference"]) - -class SignedResource(BaseObject): - def __init__(self, resource, signature): - self.resource = resource - self.signature = signature - -class ResourceReference(object): - def __init__(self, hash, size, uri=None): - self.hash = hash - self.uri = uri - self.size = size - -class ResourceAlias(object): - def __init__(self, hash, uri): - self.hash = hash - self.uri = uri - -class CertificateReference(object): - def __init__(self, fingerprint, uri): - self.fingerprint = fingerprint - self.uri = uri - -class SignatureBlock(object): - def __init__(self, signature, certificates): - self.signature = signature - self.certificates = certificates - -class MacBlock(object): - def __init__(self, pskID, keyTableIV, keyTableVersion, keyTableIndexSize, keyTableRecordSize, keyTableRef=None): - self.pskID = pskID - self.keyTableIV = keyTableIV - self.keyTableVersion = keyTableVersion - self.keyTableRef = keyTableRef - self.keyTableIndexSize = keyTableIndexSize - self.keyTableRecordSize = keyTableRecordSize - -class ResourceSignature(object): - def __init__(self, hash, signatures, macs=None): - self.hash = hash - self.signatures = signatures - if macs: - self.macs = macs diff --git a/manifesttool/v1/parse.py b/manifesttool/v1/parse.py deleted file mode 100644 index 77df1e9..0000000 --- a/manifesttool/v1/parse.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- - -import json, logging, binascii -from manifesttool import codec -from manifesttool.v1 import manifest_definition - -# All supported decoders -from pyasn1.codec.der import decoder as der_decoder - -LOG = logging.getLogger(__name__) - -# Wrapper class with same signature as pyasn1 decoders -class json_decoder(object): - def decode(self, data, schema): - return (json.dumps(data),) - -def parse(options, prefix): - data = prefix + options.input_file.read() - LOG.debug('Read {} bytes of encoded data. Will try to decode...'.format(len(data))) - - decoded_data = { - "der": lambda d: codec.bin2obj(d, manifest_definition.SignedResource(), der_decoder, True), - }[options.encoding](data) - LOG.debug('Successfully decoded data from {} encoded binary'.format(options.encoding)) - return decoded_data diff --git a/manifesttool/v1/sign.py b/manifesttool/v1/sign.py deleted file mode 100644 index 0e9774c..0000000 --- a/manifesttool/v1/sign.py +++ /dev/null @@ -1,236 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- - -import logging, os, binascii, json -from manifesttool import verify -from manifesttool.v1 import verify_signed_resource as definition -from manifesttool import codec, utils, defaults -from manifesttool import signature_schema as schema -from manifesttool import create -# All supported decoders -from pyasn1.codec.der import decoder as der_decoder - -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives.asymmetric import ec -from cryptography.hazmat.primitives.serialization import load_pem_private_key -from cryptography.exceptions import InvalidSignature -from cryptography import x509 - -LOG = logging.getLogger(__name__) - -def sig_from_dict(d): - certificates = [] - for cr in d['certificates']: - certificates.append(schema.CertificateReference( - fingerprint = binascii.a2b_hex(cr['fingerprint']), - uri = cr.get('uri','') - )) - return schema.SignatureBlock( - signature = binascii.a2b_hex(d['signature']), - certificates = certificates) - -def sign(options): - # Load defaults - defaultConfig = {} - if os.path.exists(defaults.config): - with open(defaults.config) as f: - defaultConfig = json.load(f) - - # Load the existing manifest - content = None - if hasattr(options, 'manifest') and options.manifest: - options.manifest.seek(0) - content = options.manifest.read() - else: - content = utils.download_file(options.url) - - # Extract the signed resource. - signed_resource_data = { - "der": lambda d: codec.bin2obj(d, definition.SignedResource(), der_decoder), - }[options.encoding](content) - if not signed_resource_data: - return 1 - LOG.debug('Decoded SignedResource from {} encoded binary'.format(options.encoding)) - - # Sign the resource - # Calculate the hash of the content of the existing manifest - c_hash = utils.sha_hash(signed_resource_data['resource']) - if not 'hash' in signed_resource_data['signature']: - LOG.critical('Manifest does not contain a hash') - return None - # Extract the hash - e_hash = binascii.a2b_hex(signed_resource_data['signature']['hash']) - # Compare calculated and extracted hashes - if c_hash != e_hash: - LOG.critical('Hash mismatch\nExpected: {}\nActual: {}'.format(binascii.b2a_hex(e_hash),binascii.b2a_hex(c_hash))) - return None - LOG.debug('Manifest hash: {}'.format(binascii.b2a_hex(c_hash))) - - # Load a certificate and private key - # Private key must be in .manifest_tool.json, or provided on the command-line - - # 1. Check the command-line - if not hasattr(options,'private_key') or not options.private_key: - # 2. Check the default config - if 'private-key' in defaultConfig: - try: - # NOTE: binary is not specified since the key is usually PEM encoded. - options.private_key = open(defaultConfig['private-key'],'r') - except: - LOG.critical('No private key specified and default key ({}) cannot be opened'.format(defaultConfig['private-key'])) - return 1 - # 3. Fail if the private key is not found - if not hasattr(options, 'private_key') or not options.private_key: - LOG.critical('No private key specified and default key ({}) cannot be opened'.format(defaultConfig['private-key'])) - return 1 - if not hasattr(options, 'password'): - options.password = None - - # Load the private key - privkey = load_pem_private_key(options.private_key.read(), password=options.password, backend=default_backend()) - - # Make sure that this is an ECDSA key! - if not isinstance(privkey, ec.EllipticCurvePrivateKey): - LOG.critical('Private key was not an ECC private key') - return 1 - LOG.debug('Loaded private key') - LOG.info('Signing manifest...') - # Create signature - sig = privkey.sign(signed_resource_data['resource'], ec.ECDSA(hashes.SHA256())) - LOG.debug('Signature: {}'.format(binascii.b2a_hex(sig))) - - # destroy the privkey object - privkey = None - - # Certificate must be in .manifest_tool.json, or provided on the command-line - # Load the certificate - if not hasattr(options,'certificate') or not options.certificate: - if 'default-certificates' in defaultConfig: - options.certificate = open(defaultConfig['default-certificates'][0]['file'],'rb') - - if not hasattr(options,'certificate') or not options.certificate: - LOG.critical('No certificate specified and default certificate ({}) cannot be opened'.format(defaultConfig['default-certificates'][0]['file'])) - return 1 - - # Load the certificate object from the DER file - certObj = None - try: - certObj = x509.load_der_x509_certificate(options.certificate.read(), default_backend()) - except ValueError as e: - LOG.critical("X.509 Certificate Error in ({file}): {error}".format(error=e, file=options.certificate.name)) - return(1) - - if not certObj: - LOG.critical("({file}) is not a valid certificate".format(file=cPath)) - return(1) - - # Make sure that the certificate is signed with SHA256 - if not isinstance(certObj.signature_hash_algorithm, hashes.SHA256): - LOG.critical("In ({file}): Only SHA256 certificates are supported by the update client at this time.".format(file=cPath)) - return(1) - - LOG.info('Verifying signature with supplied certificate...') - - # Verify the signature with the provided certificate to ensure that the update target will be able to do so - try: - pubkey = certObj.public_key() - pubkey.verify(sig, signed_resource_data['resource'], ec.ECDSA(hashes.SHA256())) - except InvalidSignature as e: - LOG.critical('New signature failed to verify with supplied certificate ({})'.format(options.certificate.name)) - return 1 - - # Store the fingerprint of the certificate - fingerprint = certObj.fingerprint(hashes.SHA256()) - - certificates = [] - # for idx in range(len()) - # certObj = None - # try: - # certObj = x509.load_der_x509_certificate(options.certificate.read(), default_backend()) - # except ValueError as e: - # LOG.critical("X.509 Certificate Error in ({file}): {error}".format(error=e, file=options.certificate.name)) - # return(1) - # - # if not certObj: - # LOG.critical("({file}) is not a valid certificate".format(file=cPath)) - # return(1) - # if not isinstance(certObj.signature_hash_algorithm, hashes.SHA256): - # LOG.critical("In ({file}): Only SHA256 certificates are supported by the update client at this time.".format(file=cPath)) - # return(1) - # LOG.debug('Creating certificate reference ({}) from {} with fingerprint {}'.format(idx, options.certificate.name, fingerprint)) - LOG.debug('Creating certificate reference from {} with fingerprint {}'.format(options.certificate.name, fingerprint)) - uri = '' - # TODO: Insert URI for delegation of trust - cr = schema.CertificateReference( - fingerprint = fingerprint, - uri = uri - ) - # Append the certificate reference to the current list - # NOTE: Currently, only one certificate reference will exist in the certificates list, but with delegation of trust - # there will be more certificate references - certificates.append(cr) - LOG.debug('Signed hash ({}) of encoded content ({} bytes) with resulting signature {}'.format( - binascii.b2a_hex(c_hash), len(content), binascii.b2a_hex(sig))) - - signatures = [] - for s in signed_resource_data['signature']['signatures']: - signatures.append(sig_from_dict(s)) - - # encode the signature block - signatures.append(schema.SignatureBlock(signature = sig, certificates = certificates)) - - # encode the resource signature - resource_signature = schema.ResourceSignature( - hash = c_hash, - signatures = signatures - ) - - # encode the signed resource - signed_resource = schema.SignedResource( - resource = signed_resource_data['resource'], - signature = resource_signature - ) - - # Convert the signed resource into a python dictionary - manifest_dict = signed_resource.to_dict() - # Encode the Python dictionary as a DER stream - output = utils.encode(manifest_dict, options, definition.SignedResource()) - - # Write the result to the output_file - if hasattr(options, 'output_file') and options.output_file: - # Write result to output file or stdout buffer. - options.output_file.write(output) - - # Append newline if outputting to TTY - if options.output_file.isatty(): - options.output_file.write(b'\n') - return 0 - return 1 - -def main(options): - if hasattr(options, 'manifest') and options.manifest: - options.input_file = options.manifest - if not hasattr(options, 'input_file') or not options.input_file: - return 1 - rc = verify.main(options) - if rc: - return rc - LOG.debug('Adding new signature to manifest') - return sign(options) diff --git a/manifesttool/v1/verify.py b/manifesttool/v1/verify.py deleted file mode 100644 index 7c387a7..0000000 --- a/manifesttool/v1/verify.py +++ /dev/null @@ -1,454 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- - -import json, logging, hashlib, time, sys, binascii, ecdsa, os, tempfile, uuid - -from manifesttool.v1 import verify_signed_resource, verify_resource, verify_manifest_minimal, manifest_definition -from manifesttool import codec, utils, defaults - -from cryptography import x509 -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import hashes -from cryptography.hazmat.primitives import asymmetric -import cryptography - -# All supported decoders -from pyasn1.codec.der import decoder as der_decoder - -LOG = logging.getLogger(__name__) - -commonParameters = [ - 'timestamp' -] - -def certificateQuery(options, fingerprints, URLs): - '''Load a certificate from a directory that contains certificates named by fingerprint''' - cert = None - missingCertURLs = [] - # Load defaults - defaultConfig = {} - if os.path.exists(defaults.config): - with open(defaults.config) as f: - defaultConfig = json.load(f) - - for i,fingerprint in enumerate(fingerprints): - path = os.path.join(options.certificate_directory, fingerprint) - LOG.debug('Fetching certificate: {}'.format(path)) - #look up the fingerprint - cert = None - if os.path.exists(path) and os.path.isfile(path): - cert = path - break - else: - LOG.debug('Could not find {}, checking default certificates'.format(path)) - defaultCertificateList = defaultConfig.get('default-certificates', []) - for defaultCertificate in defaultCertificateList: - if 'file' in defaultCertificate: - LOG.debug('Checking {} ...'.format(defaultCertificate['file'])) - with open(defaultCertificate['file'], 'rb') as certfile: - cert_data = certfile.read() - x509cert = x509.load_der_x509_certificate(cert_data, default_backend()) - fp = x509cert.fingerprint(hashes.SHA256()) - if binascii.b2a_hex(fp).decode('utf-8') == fingerprint: - cert = certfile.name - break - else: - LOG.debug('Fingerprint mismatch for {}\n' - 'Expected: {}\n' - 'Actual: {}'.format(certfile.name, fingerprint, binascii.b2a_hex(fp).decode('utf-8'))) - if cert: - break - - # load the certificate and check its fingerprint. - if not cert: - LOG.debug('Failed to find certificate: {}'.format(path)) - else: - return None - # TODO: Fetch missing certificates - # TODO: Validate certificate chain - - LOG.debug('Found certificate: {}'.format(cert)) - return cert - -def verifyManifestV1(options, data, signedResource, resource, manifest): - if manifest['manifestVersion'] != 'v1': - LOG.critical('Not a version 1 manifest') - return None - LOG.info('Manifest version {}: OK'.format(manifest['manifestVersion'])) - # Extract the crypto mode - if 'oid' in manifest['encryptionMode']: - LOG.critical('Cannot verify Object ID encryptionMode') - return None - - if not 'enum' in manifest['encryptionMode']: - LOG.critical('No encryptionMode specified') - return None - - emode = manifest['encryptionMode']['enum'] - modes = verify_manifest_minimal.Manifest().getComponentType()['encryptionMode'].getType().getComponentType()['enum'].getType().getNamedValues() - if modes.getValue(emode) != None and emode != modes.getName(0): - LOG.info('Encryption mode {}: OK'.format(emode)) - else: - LOG.critical('Encryption mode {} not supported'.format(emode)) - return None - # NOTE: Currently only modes 1-3 are supported and these modes only allow SHA256. - # This means that the manifest is hashed with SHA256. - - # Load defaults - defaultConfig = {} - if os.path.exists(defaults.config): - with open(defaults.config) as f: - defaultConfig = json.load(f) - - # Verify UUIDs - for i in ['vendorId', 'classId', 'deviceId']: - if i in manifest: - try: - LOG.debug('Found {}: {}'.format(i,manifest[i])) - manifest_id = uuid.UUID(manifest[i]) - except: - #if len(uuid) != 0 and len(uuid) != 128/8: - LOG.critical('UUIDs ({}) must be 0 or 128 bits'.format(i)) - return None - expect_id = None - if hasattr(options,i) and getattr(options,i): - expect_id = uuid.UUID(getattr(options,i)) - else: - expect_id = defaultConfig.get(i, None) - if expect_id: - expect_id = uuid.UUID(expect_id) - LOG.debug('Using default {} from {}'.format(i,defaults.config)) - if expect_id: - if manifest_id != expect_id: - LOG.critical('UUID mismatch for {}\n' - 'Expected: {}\n' - 'Actual: {}'.format(i, expect_id, manifest_id)) - return None - LOG.info('UUID {}: OK'.format(i)) - else: - LOG.warning('UUID {} not specified; ignoring'.format(i)) - - # Verify the manifest hash - if not 'signature' in signedResource: - LOG.critical('Signature missing, but encryption mode {} requires a signature'.format(emode)) - return None - c_hash = utils.sha_hash(signedResource['resource']) - if not 'hash' in signedResource['signature']: - LOG.critical('Manifest does not contain a hash') - return None - e_hash = binascii.a2b_hex(signedResource['signature']['hash']) - if c_hash != e_hash: - LOG.critical('Hash mismatch\nExpected: {}\nActual: {}'.format(binascii.b2a_hex(e_hash),binascii.b2a_hex(c_hash))) - return None - LOG.debug('Manifest hash: {}'.format(binascii.b2a_hex(c_hash).decode('utf-8'))) - LOG.info('Maninfest hash: OK') - - if not options.certificateQuery: - LOG.warning('No certificateQuery provided, will not verify signatures') - if (emode == 'none-ecc-secp256r1-sha256' or emode == 'aes-128-ctr-ecc-secp256r1-sha256') and options.certificateQuery: - if not 'signatures' in signedResource['signature']: - LOG.critical('Signature missing, but encryption mode {} requires a signature'.format(emode)) - return None - for signature in signedResource['signature']['signatures']: - if not 'certificates' in signature: - LOG.critical('A certificate reference is mandatory in a signature') - return None - if len(signature['certificates']) == 0: - LOG.critical('At least one certificate reference is mandatory in a signature') - return None - if not 'fingerprint' in signature['certificates'][0] or len(signature['certificates'][0]['fingerprint']) == 0: - LOG.critical('A fingerprint is mandatory in a certificate') - return None - LOG.debug('Verifying signature by {}'.format(signature['certificates'][0]['fingerprint'])) - fingerprints = [x['fingerprint'] for x in signature['certificates']] - URLs = [x['uri'] if 'uri' in x else '' for x in signature['certificates']] - certfile = options.certificateQuery(options, fingerprints, URLs) - if certfile == None: # TODO: Option for mandatory certificate verification - if options.mandatory_signature: - LOG.critical('Could not find certificate chain matching {}'.format(fingerprints[0])) - return None - LOG.warning('Could not find certificate chain matching {}'.format(fingerprints[0])) - else: - #if not options.ecdsaVerify(cert, signature): - # ok = False - # vk = ecdsa.VerifyingKey.from_pem(keypem) - # ok = vk.verify(binascii.a2b_hex(signature['signature']), - # signedResource['resource'], - # hashfunc=hashlib.sha256, - # sigdecode=ecdsa.util.sigdecode_der) - LOG.debug('Opening {} ...'.format(certfile)) - with open(certfile,'rb') as cert: - ok = options.ecdsaVerify(cert,signature['signature'],e_hash) - if not ok: - LOG.critical('Signature verification failed') - return None - LOG.info('Signature by {}: OK'.format(fingerprints[0])) - - - # Decode the full manifest. - full_manifest = { - "der": lambda d: codec.bin2obj(data, manifest_definition.SignedResource(), der_decoder), - }[options.encoding](data) - LOG.debug('Parsed whole manifest from {}-encoded binary object'.format(options.encoding)) - - full_manifest = full_manifest['resource']['resource']['manifest'] - # TODO: Measure nonce entropy - if not 'nonce' in full_manifest: - LOG.critical('A nonce is required in the manifest') - return None - else: - nonce = binascii.a2b_hex(full_manifest['nonce']) - if len(nonce)*8 != 128: - LOG.critical('Nonce must be 128 bits. Got {}: {}'.format(len(nonce)*8, binascii.b2a_hex(nonce))) - return None - LOG.info('nonce: {} OK'.format(full_manifest['nonce'])) - - # Call vendor-supplied Vendor Info Validator - if hasattr(options, 'validateVendorInfo'): - if options.validateVendorInfo(options, full_manifest['vendorInfo']): - LOG.critical('Vendor Info Validation failed') - return None - LOG.info('VendorInfo: OK') - - # Extract apply period - applyPeriod = full_manifest.get('applyPeriod') - - # must have either a payload or a dependency - if not 'payload' in full_manifest and ( - not 'dependencies' in full_manifest or len(full_manifest['dependencies']) == 0): - LOG.critical('Manifest must contain either a dependency or a payload') - sys.exit(1) - - # Verify the payload - if 'payload' in full_manifest: - payload = full_manifest['payload'] - LOG.debug('Manifest contains a payload') - # Verify the payload format - if 'enum' in payload['format']: - enum = payload['format']['enum'] - payloadFormats = manifest_definition.PayloadDescription().getComponentType()['format'].getType().getComponentType()['enum'].getType().getNamedValues() - if payloadFormats.getValue(enum) == None or enum == payloadFormats.getName(0): - LOG.critical('Payload format not recognized') - return None - LOG.info('Payload format {}: OK'.format(enum)) - elif 'objectId' in payload['format']: - LOG.warning('Cannot verify Object ID payload format') - else: - LOG.critical('Payload does not contain a format') - return None - if payload['format']['enum'] == 'bsdiff-stream': - # Check for presence of required fields - if 'precursorDigest' not in full_manifest: - LOG.critical('Precursor Digest is mandatory for bsdiff-stream payloads') - return None - if 'installedDigest' not in payload: - LOG.critical('Installed Digest is mandatory for bsdiff-stream payloads') - return None - if 'installedSize' not in payload: - LOG.critical('Installed Size is mandatory for bsdiff-stream payloads') - return None - if emode == 'aes-128-ctr-ecc-secp256r1-sha256': - if not 'encryptionInfo' in payload: - LOG.critical('Encryption info must be present for encrypted payload distribution') - return None - cryptinfo = payload['encryptionInfo'] - # Validate the encryption information - # Validate the init vector: - if not 'initVector' in cryptinfo or len(binascii.a2b_hex(cryptinfo['initVector'])) != 128/8: - LOG.critical('When using aes-128-ctr-ecc-secp256r1-sha256, a 128-bit AES initialization vector is mandatory') - if 'initVector' in cryptinfo: - iv = binascii.a2b_hex(cryptinfo['initVector']) - LOG.critical('Expected 128 bits, got {}: {}'.format(len(iv)*8, binascii.b2a_hex(iv))) - return None - # TODO: Verify the entropy of the init vector - - # Determine the key mode - kmode = 0 - # Options: - if 'key' in cryptinfo['id'] and 'cipherKey' in cryptinfo['key']: - if len(cryptinfo['key']['cipherKey']) == 0: - # Select a preshared local key - kmode = 1 - LOG.debug('Using local preshared key for decryption') - else: - # Select a preshared local key & decrypt a session key - kmode = 2 - LOG.debug('Using local preshared key to decrypt the payload key') - # Select certificate & decrypt a session key (Single-device only) - elif 'certificate' in cryptinfo['id'] and 'cipherKey' in cryptinfo['key']: - kmode = 3 - LOG.debug('Using ECDH to decrypt the device key') - # Select a certificate & a keytable - elif 'certificate' in cryptinfo['id'] and 'keyTable' in cryptinfo['key']: - kmode = 4 - LOG.debug('Using ECDH to decrypt the payload key from the key table') - - if kmode == 0: - LOG.critical('Unrecognized key distribution mode') - return None - - # NOTE: It is not possible to verify payload without a device key when it is encrypted. - # Verify the storage identifier - if not 'storageIdentifier' in payload or len(payload['storageIdentifier']) == 0: - LOG.critical('storageIdentifier must be provided') - return None - # Verify the resource reference - if not 'reference' in payload: - LOG.critical('A resource reference is mandatory in a payload-bearing manifest') - return None - if not 'hash' in payload['reference'] or len(payload['reference']['hash']) == 0: - LOG.critical('A resource hash is mandatory in a payload reference') - return None - if not 'size' in payload['reference'] or payload['reference']['size'] == 0: - LOG.critical('Zero-size resources are not permitted') - return None - - if 'uri' in payload['reference']: - LOG.debug('Payload refers to URI: {}'.format(payload['reference']['uri'])) - # TODO: verify payload URI - - # Do not verify the version string; it is for presentation only. - - # TODO: Validate aliases - # TODO: Validate dependencies - - return {'timestamp':full_manifest['timestamp'], 'applyPeriod': applyPeriod} - - -def verifyManifest(options): - data = options.input_file.read() - LOG.debug('Read {} bytes of encoded data. Will try to decode...'.format(len(data))) - - # TODO: Verify the DER structure's encoding - - # Extract the signed resource. - signed_resource_data = { - "der": lambda d: codec.bin2obj(d, verify_signed_resource.SignedResource(), der_decoder), - }[options.encoding](data) - LOG.debug('Decoded SignedResource from {} encoded binary'.format(options.encoding)) - - # Verify that the content *is* a manifest. - # NOTE: This requires a parsing pass of the resource. - resource_data = { - "der": lambda d: codec.bin2obj(d, verify_resource.Resource(), der_decoder), - }[options.encoding](signed_resource_data['resource']) - LOG.debug('Decoded Resource from {} encoded binary'.format(options.encoding)) - - if resource_data['resourceType'] != 'manifest': - LOG.critical('The supplied file does not contain a manifest') - return 1 - - # Extract some relevant manifest information: - manifest_data = { - "der": lambda d: codec.bin2obj(d, verify_manifest_minimal.Manifest(), der_decoder), - }[options.encoding](resource_data['resource']) - LOG.debug('Decoded Manifest from {} encoded binary'.format(options.encoding)) - - # Select a manifest format decoder based on the manifest version. - def noVersionError(options, data, signedResource, resource, manifest): - LOG.critical('Unsupported manifest version: {}'.format(manifest_data['manifestVersion'])) - None - - manifest_verification_data = { - 'v1': verifyManifestV1 - }.get(manifest_data['manifestVersion'],noVersionError)(options, data, signed_resource_data, resource_data, manifest_data) - - if manifest_verification_data == None: - return 1 - - # Verify the manifest timestamp is sane - - # The manifest timestamp should not be in the future, nor before the first release of this tool. - # manifest_timestamp = decoded_data['resource']['resource']['manifest']['timestamp'] - manifest_timestamp = manifest_verification_data['timestamp'] - systime = int(time.time()) - if manifest_timestamp > systime: - LOG.critical('Manifests MUST not be timestamped in the future.\n' - 'Expected timestamp < {} ({})\n' - 'Actual timestamp: {} ({})'.format( - systime, time.ctime(systime), manifest_timestamp, time.ctime(manifest_timestamp))) - - release_time = time.mktime(time.strptime('2016-11-22T00:00:00',"%Y-%m-%dT%H:%M:%S")) - if manifest_timestamp < int(release_time): - LOG.critical('Manifests MUST not be timestamped before 2017.\n' - 'Expected timestamp > {} ({})\n' - 'Actual timestamp: {} ({})'.format( - int(release_time), time.ctime(int(release_time)), manifest_timestamp, time.ctime(manifest_timestamp))) - LOG.info('Timestamp {} < {} < {}: OK'.format(int(release_time), manifest_timestamp, systime)) - - # Verify applyPeriod - if 'applyPeriod' in manifest_verification_data and manifest_verification_data['applyPeriod']: - applyPeriod = manifest_verification_data['applyPeriod'] - if release_time > applyPeriod['validFrom'] or \ - applyPeriod['validFrom'] > applyPeriod['validTo'] or \ - applyPeriod['validTo'] > systime: - LOG.critical('Apply perion outside expected bounds: Expected:\n{} <= {} <= {} <= {}'.format( - release_time, applyPeriod['validFrom'], applyPeriod['validTo'], systime - )) - return 1 - LOG.info('Apply period {} to {} OK'.format(applyPeriod['validFrom'], applyPeriod['validTo'])) - - - # Verify each URL - - # Fetch each file from each listed URL (may not be possible, depending on network architecture) - # Validate the hash of each file from each listed URL - - # Write to output buffer/file - # indent = None if not options.pretty_json else 2 - # options.output_file.write(str.encode(json.dumps(decoded_data, indent = indent))) - - # If we're writing to TTY, add a helpful newline - # if options.output_file.isatty(): - # options.output_file.write(b'\n') - - return 0 - -def cryptographyEcdsaVerify(certfile, sig, sha): - LOG.debug('Reading {}'.format(certfile.name)) - cert_data = certfile.read() - cert = x509.load_der_x509_certificate(cert_data, default_backend()) - pubkey = cert.public_key() - bsig = binascii.a2b_hex(sig) - LOG.debug('Verifying...\n' - 'Signature: ({sigtype}){sig}\n' - 'Hash: ({shatype}){sha}'.format( - sigtype=type(bsig),sig=repr(bsig),shatype=type(sha),sha=repr(sha))) - try: - pubkey.verify( - bsig, - sha, - asymmetric.ec.ECDSA(asymmetric.utils.Prehashed(hashes.SHA256())) - ) - except cryptography.exceptions.InvalidSignature as e: - return False - return True - - -def main(options): - - options.ecdsaVerify = cryptographyEcdsaVerify - - if not options.certificate_directory: - options.certificate_directory = defaults.certificatePath - options.certificateQuery = certificateQuery - options.mandatory_signature = True - # if not hasattr(options, 'verifyScript'): - - return verifyManifest(options) diff --git a/manifesttool/v1/verify_manifest_minimal.py b/manifesttool/v1/verify_manifest_minimal.py deleted file mode 100644 index 93cc586..0000000 --- a/manifesttool/v1/verify_manifest_minimal.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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 has been generated using asn1ate (v ) from './manifesttool/verify/manifest.asn' -# Last Modified on 2017-01-10 11:40:03 -from pyasn1.type import univ, char, namedtype, namedval, tag, constraint, useful - - -class UUID(univ.OctetString): - pass - - -class Manifest(univ.Sequence): - pass - - -Manifest.componentType = namedtype.NamedTypes( - namedtype.NamedType('manifestVersion', univ.Enumerated(namedValues=namedval.NamedValues(('v1', 1)))), - namedtype.OptionalNamedType('description', char.UTF8String()), - namedtype.NamedType('timestamp', univ.Integer()), - namedtype.NamedType('vendorId', UUID()), - namedtype.NamedType('classId', UUID()), - namedtype.NamedType('deviceId', UUID()), - namedtype.NamedType('nonce', univ.OctetString()), - namedtype.NamedType('vendorInfo', univ.OctetString()), - namedtype.OptionalNamedType('precursorDigest', univ.OctetString()), - namedtype.OptionalNamedType('applyPeriod', univ.Sequence(componentType=namedtype.NamedTypes( - namedtype.NamedType('validFrom', univ.Integer()), - namedtype.NamedType('validTo', univ.Integer()) - )) - ), - namedtype.NamedType('applyImmediately', univ.Boolean()), - namedtype.OptionalNamedType('priority', univ.Integer()), - namedtype.NamedType('encryptionMode', univ.Choice(componentType=namedtype.NamedTypes( - namedtype.NamedType('enum', univ.Enumerated(namedValues=namedval.NamedValues(('invalid', 0), ('aes-128-ctr-ecc-secp256r1-sha256', 1), ('none-ecc-secp256r1-sha256', 2), ('none-none-sha256', 3), ('none-psk-aes-128-ccm-sha256', 4), ('aes-128-ccm-psk-sha256', 5)))), - namedtype.NamedType('objectId', univ.ObjectIdentifier()) - )) - ), - namedtype.NamedType('aliases', univ.Any()), - namedtype.NamedType('dependencies', univ.Any()), - namedtype.OptionalNamedType('payload', univ.Any()) -) diff --git a/manifesttool/v1/verify_resource.py b/manifesttool/v1/verify_resource.py deleted file mode 100644 index e566fa3..0000000 --- a/manifesttool/v1/verify_resource.py +++ /dev/null @@ -1,37 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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 has been generated using asn1ate (v ) from './manifesttool/verify/resource.asn' -# Last Modified on 2017-01-10 10:46:42 -from pyasn1.type import univ, char, namedtype, namedval, tag, constraint, useful - - -class Uri(char.UTF8String): - pass - - -class Resource(univ.Sequence): - pass - - -Resource.componentType = namedtype.NamedTypes( - namedtype.OptionalNamedType('uri', Uri()), - namedtype.NamedType('resourceType', univ.Enumerated(namedValues=namedval.NamedValues(('manifest', 0), ('payload', 1)))), - namedtype.NamedType('resource', univ.Any()) -) diff --git a/manifesttool/v1/verify_signed_resource.py b/manifesttool/v1/verify_signed_resource.py deleted file mode 100644 index db65cb2..0000000 --- a/manifesttool/v1/verify_signed_resource.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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 has been generated using asn1ate (v ) from './tools/manifest-wrapper.asn' -# Last Modified on 2017-01-06 14:48:42 -from pyasn1.type import univ, char, namedtype, namedval, tag, constraint, useful - - -class Bytes(univ.OctetString): - pass - - -class Uri(char.UTF8String): - pass - - -class CertificateReference(univ.Sequence): - pass - - -CertificateReference.componentType = namedtype.NamedTypes( - namedtype.NamedType('fingerprint', Bytes()), - namedtype.NamedType('uri', Uri()) -) - - -class SignatureBlock(univ.Sequence): - pass - - -SignatureBlock.componentType = namedtype.NamedTypes( - namedtype.NamedType('signature', univ.OctetString()), - namedtype.NamedType('certificates', univ.SequenceOf(componentType=CertificateReference())) -) - -class MacBlock(univ.Sequence): - pass - - -MacBlock.componentType = namedtype.NamedTypes( - namedtype.NamedType('pskID', univ.OctetString()), - namedtype.NamedType('keyTableVersion', univ.Integer()), - namedtype.OptionalNamedType('keyTableIV', univ.OctetString()), - namedtype.OptionalNamedType('keyTableRef', char.UTF8String()), - namedtype.NamedType('keyTableIndexSize', univ.Integer()), - namedtype.NamedType('keyTableRecordSize', univ.Integer()) -) - -class ResourceSignature(univ.Sequence): - pass - - -ResourceSignature.componentType = namedtype.NamedTypes( - namedtype.NamedType('hash', univ.OctetString()), - namedtype.NamedType('signatures', univ.SequenceOf(componentType=SignatureBlock())), - namedtype.OptionalNamedType('macs', univ.SequenceOf(componentType=MacBlock())) -) - - -class SignedResource(univ.Sequence): - pass - - -SignedResource.componentType = namedtype.NamedTypes( - namedtype.NamedType('resource', univ.Any()), - namedtype.NamedType('signature', ResourceSignature()) -) - - -class Payload(univ.OctetString): - pass - - -class UUID(univ.OctetString): - pass diff --git a/manifesttool/verify.py b/manifesttool/verify.py deleted file mode 100644 index 02a1236..0000000 --- a/manifesttool/verify.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- -import json, logging, binascii -from builtins import bytes -from manifesttool.v1.verify import main as verify_v1 - -LOG = logging.getLogger(__name__) - -def skipAhead(code): - rc = 0 - if code == 0x81: - rc = 1 - if code == 0x82: - rc = 2 - if code == 0x83: - rc = 3 - if code == 0x83: - rc = 4 - return rc - -def main(options): - LOG.debug("Attempting to determine manifest version...") - # 32 bytes is currently sufficient to detect the manifest type. - headerData = bytes(options.input_file.read(32)) - options.input_file.seek(0) - # In both cases, the manifest starts with a DER SEQUENCE tag. - if headerData[0] != 0x30: - LOG.critical("input file is not a manifest.") - return 1 - # skip past the length - pos = 2 + skipAhead(headerData[1]) - - version = None - # For version 1, the first object in the SEQUENCE should be another SEQUENCE - if headerData[pos] == 0x30: - version = 1 - # For version 2+, a CMS wrapper is used, so the tag should be an OID tag - if headerData[pos] == 0x06: - version = 2 - - if version == None: - LOG.critical("No recognized manifest format found.") - return 1 - - # For now, we will assume that 2+ means 2. - parser = { - 1 : verify_v1 - }.get(version, None) - if not parser: - LOG.critical("Unrecognized manifest version.") - return 1 - return parser(options) diff --git a/manifesttool/verify/manifest-wrapper.asn b/manifesttool/verify/manifest-wrapper.asn deleted file mode 100644 index 6ed3c0e..0000000 --- a/manifesttool/verify/manifest-wrapper.asn +++ /dev/null @@ -1,46 +0,0 @@ --- -*- coding: utf-8 -*- --- ---------------------------------------------------------------------------- --- Copyright 2017 ARM Limited or its affiliates --- --- 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. --- ---------------------------------------------------------------------------- --- Manifest wrapper definition file in ASN.1 (v. 1.0.0) - -ManifestSchema DEFINITIONS IMPLICIT TAGS ::= BEGIN - - Uri ::= UTF8String - Bytes ::= OCTET STRING - UUID ::= OCTET STRING - Payload ::= OCTET STRING - - CertificateReference ::= SEQUENCE { - fingerprint Bytes, - uri Uri - } - SignatureBlock ::= SEQUENCE { - signature OCTET STRING, - certificates SEQUENCE OF CertificateReference - } - ResourceSignature ::= SEQUENCE { - hash OCTET STRING, - signatures SEQUENCE OF SignatureBlock - } - - SignedResource ::= SEQUENCE { - resource ANY, - signature ResourceSignature - } - -END diff --git a/manifesttool/verify/manifest.asn b/manifesttool/verify/manifest.asn deleted file mode 100644 index c69134a..0000000 --- a/manifesttool/verify/manifest.asn +++ /dev/null @@ -1,52 +0,0 @@ --- -*- coding: utf-8 -*- --- ---------------------------------------------------------------------------- --- Copyright 2017 ARM Limited or its affiliates --- --- 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. --- ---------------------------------------------------------------------------- --- Manifest definition file in ASN.1 (v. 1.0.0) -ManifestSchema DEFINITIONS IMPLICIT TAGS ::= BEGIN - - UUID ::= OCTET STRING - Manifest ::= SEQUENCE { - manifestVersion ENUMERATED { - v1(1) - }, - description UTF8String OPTIONAL, - timestamp INTEGER, - vendorId UUID, - classId UUID, - deviceId UUID, - nonce OCTET STRING, - vendorInfo OCTET STRING, - applyPeriod SEQUENCE { - validFrom INTEGER, - validTo INTEGER - } OPTIONAL, - applyImmediately BOOLEAN, - encryptionMode CHOICE { - enum ENUMERATED { - invalid(0), - aes-128-ctr-ecc-secp256r1-sha256(1), - none-ecc-secp256r1-sha256(2), - none-none-sha256(3) - }, - objectId OBJECT IDENTIFIER - }, - aliases ANY, - dependencies ANY, - payload ANY OPTIONAL - } -END diff --git a/manifesttool/verify/resource.asn b/manifesttool/verify/resource.asn deleted file mode 100644 index 3d52ce2..0000000 --- a/manifesttool/verify/resource.asn +++ /dev/null @@ -1,31 +0,0 @@ --- -*- coding: utf-8 -*- --- ---------------------------------------------------------------------------- --- Copyright 2017 ARM Limited or its affiliates --- --- 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. --- ---------------------------------------------------------------------------- --- Manifest definition file in ASN.1 (v. 1.0.0) -ManifestSchema DEFINITIONS IMPLICIT TAGS ::= BEGIN - - Uri ::= UTF8String - Resource ::= SEQUENCE { - uri Uri OPTIONAL, - resourceType ENUMERATED { - manifest(0), payload(1) - }, - resource ANY - } - -END diff --git a/requirements.txt b/requirements.txt index d7d7f97..4341140 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,9 +1,7 @@ -ecdsa>=0.13 -cryptography>=2.0.0 -pyasn1>=0.2.1,<0.3.0 -asn1ate>=0.5 -pyparsing>=2.1.0 -future>=0.16.0 -urllib3>=1.20 -colorama>=0.3.9,<0.4.0 -protobuf>=3.5.0,<3.6.0 +PyYAML>=4.2b1,<=5.3.1 +asn1ate>=0.5,<=0.6.0 +cryptography>=2.5,<=2.9.2 +jsonschema>=2.6.0,<=3.2.0 +pyasn1==0.3.1,<=0.4.8 +urllib3>=1.20,<=1.25.9 +mbed-cloud-sdk>=2.0.6,<=2.2.0 \ No newline at end of file diff --git a/setup.py b/setup.py index 0c1041b..a50970b 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- -# Copyright 2016-2017 ARM Limited or its affiliates +# Copyright 2019 ARM Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0 # @@ -17,24 +16,26 @@ # limitations under the License. # ---------------------------------------------------------------------------- -from setuptools import setup, find_packages +from setuptools import setup, find_packages, Extension + import manifesttool -import os -if os.name == 'nt': - entry_points={ - "console_scripts": [ - "manifest-tool=manifesttool.clidriver:main", - ], - } - scripts = [] -else: - platform_deps = [] - # entry points are nice, but add ~100ms to startup time with all the - # pkg_resources infrastructure, so we use scripts= instead on unix-y - # platforms: - scripts = ['bin/manifest-tool', ] - entry_points = {} +armbsdiff = Extension( + 'manifesttool.armbsdiff', + sources=[ + 'bsdiff/bsdiff.c', + 'bsdiff/bsdiff_helper.c', + 'bsdiff/bsdiff_python.c', + 'bsdiff/lz4.c', + 'bsdiff/varint.c' + ], + include_dirs=['bsdiff'], + define_macros=[('LZ4_MEMORY_USAGE', '10')], + extra_compile_args=['--std=c99', '-O3'] +) + +with open('requirements.txt', 'rt') as fh: + pdmfota_requirements = fh.readlines() setup( name='manifest-tool', @@ -45,9 +46,17 @@ url='https://github.com/ARMmbed/manifest-tool', author='ARM', author_email='support@arm.com', - packages=find_packages(exclude=['tests*']), + packages=find_packages(exclude=['tests']), zip_safe=False, - scripts=scripts, - entry_points=entry_points, - install_requires=open('requirements.txt').read().splitlines() + entry_points={ + "console_scripts": [ + "manifest-tool=manifesttool.mtool.mtool:entry_point", + "manifest-dev-tool=manifesttool.dev_tool.dev_tool:entry_point", + "manifest-delta-tool=manifesttool.delta_tool.delta_tool:entry_point" + ], + }, + python_requires='>=3.5.0', + include_package_data=True, + install_requires=pdmfota_requirements, + ext_modules=[armbsdiff] ) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..2ef7735 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,94 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import contextlib +import os +from pathlib import Path + +import pytest + +from manifesttool import armbsdiff +from manifesttool.delta_tool import delta_tool +from manifesttool.dev_tool import defaults +from manifesttool.dev_tool.actions import init as dev_init + + +@pytest.fixture(scope="session") +def happy_day_data(tmp_path_factory): + yield data_generator(tmp_path_factory, size=512) + + +def data_generator(tmp_path_factory, size): + tmp_path = tmp_path_factory.mktemp("data") + key_file = tmp_path / 'dev.key.pem' + certificate_file = tmp_path / 'dev.cert.der' + dev_init.generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False, + cred_valid_time=8 + ) + bsdiff_version = armbsdiff.get_version().encode('utf-8') + fw_file = tmp_path / 'fw.bin' + fw_data = bsdiff_version + os.urandom(size) + fw_file.write_bytes(fw_data) + new_fw_file = tmp_path / 'new_fw.bin' + new_fw_data = fw_data + os.urandom(512) + new_fw_file.write_bytes(new_fw_data) + delta_file = tmp_path / 'delta.bin' + delta_tool.generate_delta( + orig_fw=fw_file, + new_fw=new_fw_file, + output_delta_file=delta_file, + block_size=512, + threshold=60 + ) + + dev_cfg = tmp_path / 'dev.manifest_cfg.yaml' + dev_init.generate_developer_config( + key_file=key_file, + certificate_file=certificate_file, + config=dev_cfg, + do_overwrite=True + ) + + api_config_path = tmp_path / 'service_cfg.json' + dev_init.generate_service_config( + api_key='sdsdadadadsdadasdadsadasdas', + api_url=defaults.API_GW, + api_config_path=api_config_path + ) + + return { + 'fw_file': fw_file, + 'new_fw_file': new_fw_file, + 'delta_file': delta_file, + 'key_file': key_file, + 'certificate_file': certificate_file, + 'tmp_path': tmp_path, + 'dev_cfg': dev_cfg, + 'api_config_path': api_config_path + } + +@contextlib.contextmanager +def working_directory(path: Path): + current = Path.cwd() + os.chdir(path.as_posix()) + try: + yield + finally: + os.chdir(current.as_posix()) \ No newline at end of file diff --git a/tests/delta_tool/test_generate_delta.py b/tests/delta_tool/test_generate_delta.py new file mode 100644 index 0000000..699e5cf --- /dev/null +++ b/tests/delta_tool/test_generate_delta.py @@ -0,0 +1,126 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +import os + +import pytest + +from manifesttool import armbsdiff +from manifesttool.delta_tool.delta_tool import entry_point +from manifesttool.delta_tool.delta_tool import generate_delta + + +@pytest.fixture(scope="session") +def test_files(tmp_path_factory): + fw_size_bits = 1024 * 512 + + temp_dir = tmp_path_factory.mktemp("data") + current_bsdiff_version = armbsdiff.get_version().encode('utf-8') + unsupported_bsdiff_version = b'PELION/BSDIFF666' + + orig_fw_name = temp_dir / 'orig_fw.bin' + orig_fw_data = current_bsdiff_version + os.urandom(fw_size_bits) + orig_fw_name.write_bytes(orig_fw_data) + + new_add_fw_name = temp_dir / 'new_fw.bin' + new_add_fw_data = current_bsdiff_version + os.urandom( + 512) + orig_fw_data + os.urandom(512) + new_add_fw_name.write_bytes(new_add_fw_data) + + other_fw_name = temp_dir / 'other_fw.bin' + other_fw_data = unsupported_bsdiff_version + os.urandom(fw_size_bits) + other_fw_name.write_bytes(other_fw_data) + + return { + 'orig_fw': orig_fw_name, + 'new_fw': new_add_fw_name, + 'other_fw': other_fw_name, + } + + +def test_generate_delta_happy_day(tmp_path, test_files): + delta_file = tmp_path / 'delta.bin' + generate_delta( + test_files['orig_fw'], + test_files['new_fw'], + delta_file, + 512, + 60 + ) + print('Delta-file-size={delta} new-file-size={new}'.format( + delta=len(delta_file.read_bytes()), + new=len(test_files['new_fw'].read_bytes()))) + +def test_cli_generate_delta_happy_day(tmp_path, test_files): + delta_file = tmp_path / 'delta.bin' + cmd = [ + '--current-fw', test_files['orig_fw'].as_posix(), + '--new-fw', test_files['new_fw'].as_posix(), + '--output', delta_file.as_posix(), + '--block-size', '1024' + ] + assert 0 == entry_point(cmd) + print('Delta-file-size={delta} new-file-size={new}'.format( + delta=len(delta_file.read_bytes()), + new=len(test_files['new_fw'].read_bytes()))) + +def test_cli_generate_delta_happy_day_skip_check(tmp_path, test_files): + delta_file = tmp_path / 'delta.bin' + cmd = [ + '--current-fw', test_files['orig_fw'].as_posix(), + '--new-fw', test_files['other_fw'].as_posix(), + '--output', delta_file.as_posix(), + '--block-size', '1024', + '--skip-size-check' + ] + assert 0 == entry_point(cmd) + print('Delta-file-size={delta} new-file-size={new}'.format( + delta=len(delta_file.read_bytes()), + new=len(test_files['new_fw'].read_bytes()))) + + +def test_generate_delta_no_compression(tmp_path, test_files): + with pytest.raises(AssertionError): + generate_delta( + test_files['orig_fw'], + test_files['other_fw'], + tmp_path / 'delta.bin', + 512, + 60 + ) + + +def test_generate_delta_skip_size_check(tmp_path, test_files): + generate_delta( + test_files['orig_fw'], + test_files['other_fw'], + tmp_path / 'delta.bin', + 512, + 0 + ) + + +def test_generate_delta_skip_threshold(tmp_path, test_files): + with pytest.raises(AssertionError): + generate_delta( + test_files['orig_fw'], + test_files['new_fw'], + tmp_path / 'delta.bin', + 512, + 1 + ) diff --git a/tests/dev_tool/test_dev_create.py b/tests/dev_tool/test_dev_create.py new file mode 100644 index 0000000..cdc4320 --- /dev/null +++ b/tests/dev_tool/test_dev_create.py @@ -0,0 +1,59 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +import pytest + +from manifesttool.dev_tool import defaults +from manifesttool.dev_tool import dev_tool +from manifesttool.dev_tool.actions.init import generate_developer_config +from tests import conftest + + +@pytest.mark.parametrize( + 'action', + [ + ['create'], + ['create', '--sign-image'], + ['create-v1'] + ] +) +def test_cli_developer(happy_day_data, action): + + dev_cfg = happy_day_data['tmp_path'] / defaults.DEV_CFG + generate_developer_config( + key_file=happy_day_data['key_file'], + certificate_file=happy_day_data['certificate_file'], + config=dev_cfg, + do_overwrite=True + ) + + output_manifest = happy_day_data['tmp_path'] / 'manifest.bin' + cmd = ['--debug'] + action + [ + '--priority', '100500', + '--output', output_manifest.as_posix(), + '--cache-dir', happy_day_data['tmp_path'].as_posix(), + '--payload-url', 'https://arm.com/foo.bin?id=67567565576857', + '--payload-path', happy_day_data['delta_file'].as_posix(), + '--vendor-data', dev_cfg.as_posix(), + ] + + if not any(['v1' in x for x in action]): + cmd.extend(['--fw-version', '100.500.0']) + + with conftest.working_directory(happy_day_data['tmp_path']): + assert 0 == dev_tool.entry_point(cmd) \ No newline at end of file diff --git a/tests/dev_tool/test_dev_init.py b/tests/dev_tool/test_dev_init.py new file mode 100644 index 0000000..fd66e86 --- /dev/null +++ b/tests/dev_tool/test_dev_init.py @@ -0,0 +1,78 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +import yaml + +from manifesttool.delta_tool.delta_tool import digest_file +from manifesttool.dev_tool import dev_tool, defaults +from tests import conftest + + +def test_cli(tmp_path): + c_source = tmp_path /'update_default_resources.c' + cache_dir = tmp_path / defaults.BASE_PATH.as_posix() + dev_cfg = cache_dir / defaults.DEV_CFG + cert = cache_dir / defaults.UPDATE_PUBLIC_KEY_CERT + key = cache_dir / defaults.UPDATE_PRIVATE_KEY + api_cfg = cache_dir / defaults.CLOUD_CFG + + dummy_api_key = '456321789541515' + dummy_api_url = 'https://i.am.tired.of.writing.tests.com' + + cmd = [ + '--debug', + 'init' + ] + + with conftest.working_directory(tmp_path): + assert 0 == dev_tool.entry_point(cmd) + + assert not api_cfg.is_file() + + dev_cfg_digest = digest_file(dev_cfg) + c_source_digest = digest_file(c_source) + cert_digest = digest_file(cert) + key_digest = digest_file(key) + + cmd = [ + 'init', + '--api-key', dummy_api_key, + '--api-url', dummy_api_url + ] + + with conftest.working_directory(tmp_path): + assert 0 == dev_tool.entry_point(cmd + ['--api-url', 'https://some.url.arm.com']) + + assert c_source_digest == digest_file(c_source) + assert cert_digest == digest_file(cert) + assert key_digest == digest_file(key) + assert dev_cfg_digest == digest_file(dev_cfg) + assert api_cfg.is_file() + + with conftest.working_directory(tmp_path): + assert 0 == dev_tool.entry_point(cmd + ['--force']) + + assert c_source_digest != digest_file(c_source) + assert cert_digest != digest_file(cert) + assert key_digest != digest_file(key) + assert dev_cfg_digest != digest_file(dev_cfg) + + with api_cfg.open('rb') as fh: + api_cfg_data = yaml.safe_load(fh) + assert dummy_api_key == api_cfg_data['api_key'] + assert dummy_api_url == api_cfg_data['host'] diff --git a/tests/dev_tool/test_dev_update.py b/tests/dev_tool/test_dev_update.py new file mode 100644 index 0000000..b137d11 --- /dev/null +++ b/tests/dev_tool/test_dev_update.py @@ -0,0 +1,113 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +import pytest +from mbed_cloud import UpdateAPI + +from manifesttool.dev_tool import dev_tool +from tests import conftest + + +def mock_update_apis(mocker, status='autostopped'): + mocker.patch.object( + UpdateAPI, '__init__', + lambda _self, conf: None + ) + + mocker.patch.object( + UpdateAPI, 'add_firmware_image', + return_value=mocker.MagicMock(url='http://some.nice.url') + ) + + mocker.patch.object( + UpdateAPI, 'add_firmware_manifest', + return_value=mocker.MagicMock(url='http://some.nice.url', id=100500) + ) + + mocker.patch.object( + UpdateAPI, 'add_campaign', + return_value=mocker.MagicMock(state='ready', device_filter=100500) + ) + + mocker.patch.object(UpdateAPI, 'start_campaign') + + mocker.patch.object( + UpdateAPI, 'get_campaign', + return_value=mocker.MagicMock( + state=status, + device_filter=100500) + ) + + mocker.patch.object(UpdateAPI, 'delete_campaign') + mocker.patch.object(UpdateAPI, 'delete_firmware_manifest') + mocker.patch.object(UpdateAPI, 'delete_firmware_image') + + +@pytest.mark.parametrize( + 'action', + [ + ['update'], + ['update', '--sign-image'], + ['update-v1'] + ] +) +def test_cli_update_delta_happy_day(happy_day_data, action, mocker): + mock_update_apis(mocker) + + assert 0 == _common( + happy_day_data, + action, + happy_day_data['delta_file'] +) + + +def _common(happy_day_data, action, payload_path): + cmd = ['--debug'] + action + [ + '--cache-dir', happy_day_data['tmp_path'].as_posix(), + '--payload-path', payload_path.as_posix(), + '--vendor-data', happy_day_data['dev_cfg'].as_posix(), + '--wait-for-completion', + '--timeout', '1', + '--device-id', '1234' + ] + if any(['v1' in x for x in action]): + cmd.extend(['--fw-version', '100500']) + else: + cmd.extend(['--fw-version', '100.500.666']) + + with conftest.working_directory(happy_day_data['tmp_path']): + return dev_tool.entry_point(cmd) + + +@pytest.mark.parametrize( + 'action', + [ + ['update'], + ['update', '--sign-image'], + ['update-v1'] + ] +) +def test_cli_update_full_timeout(happy_day_data, action, mocker): + mock_update_apis(mocker, 'scheduled') + with pytest.raises(AssertionError): + _common( + happy_day_data, + action, + happy_day_data['fw_file'] + ) + diff --git a/tests/dev_tool/test_init_generate_credentials.py b/tests/dev_tool/test_init_generate_credentials.py new file mode 100644 index 0000000..2003a78 --- /dev/null +++ b/tests/dev_tool/test_init_generate_credentials.py @@ -0,0 +1,91 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import pytest + +from manifesttool.delta_tool.delta_tool import digest_file +from manifesttool.dev_tool.actions.init import generate_credentials + + +def test_happy_day(tmp_path): + generate_credentials( + key_file=tmp_path / 'dev.key.pem', + certificate_file=tmp_path / 'dev.cert.der', + do_overwrite=False, + cred_valid_time=8 + ) + + +def test_happy_not_overwriting_keys(tmp_path): + key_file = tmp_path / 'dev.key.pem' + certificate_file = tmp_path / 'dev.cert.der' + generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False, + cred_valid_time=8 + ) + key_digest = digest_file(key_file) + cert_digest = digest_file(certificate_file) + generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False, + cred_valid_time=8 + ) + assert key_digest == digest_file(key_file) + assert cert_digest == digest_file(certificate_file) + + +def test_overwriting_keys(tmp_path): + key_file = tmp_path / 'dev.key.pem' + certificate_file = tmp_path / 'dev.cert.der' + generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False, + cred_valid_time=8 + ) + key_digest = digest_file(key_file) + cert_digest = digest_file(certificate_file) + generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=True, + cred_valid_time=8 + ) + assert key_digest != digest_file(key_file) + assert cert_digest != digest_file(certificate_file) + + +def test_bad_state(tmp_path): + key_file = tmp_path / 'dev.key.pem' + certificate_file = tmp_path / 'dev.cert.der' + generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False, + cred_valid_time=8 + ) + key_file.unlink() + with pytest.raises(AssertionError): + generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False, + cred_valid_time=8 + ) diff --git a/tests/dev_tool/test_init_generate_developer_config.py b/tests/dev_tool/test_init_generate_developer_config.py new file mode 100644 index 0000000..7856578 --- /dev/null +++ b/tests/dev_tool/test_init_generate_developer_config.py @@ -0,0 +1,47 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import yaml + +from manifesttool.dev_tool.actions.init import generate_credentials +from manifesttool.dev_tool.actions.init import generate_developer_config + + +def test_generate_developer_config_happy_day(tmp_path): + key_file = tmp_path / 'dev.key.pem' + certificate_file = tmp_path / 'dev.cert.der' + generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False, + cred_valid_time=8 + ) + config = tmp_path / 'my_cfg.yaml' + generate_developer_config( + key_file=key_file, + certificate_file=certificate_file, + config=config, + do_overwrite=True + ) + with config.open('rb') as fh: + raw_cfg = yaml.safe_load(fh) + + assert 'key_file' in raw_cfg + assert 'vendor-id' in raw_cfg + assert len(raw_cfg['vendor-id']) == 32 + assert 'class-id' in raw_cfg + assert len(raw_cfg['class-id']) == 32 diff --git a/tests/dev_tool/test_init_generate_update_default_resources_c.py b/tests/dev_tool/test_init_generate_update_default_resources_c.py new file mode 100644 index 0000000..9b6fb12 --- /dev/null +++ b/tests/dev_tool/test_init_generate_update_default_resources_c.py @@ -0,0 +1,49 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import uuid + +from manifesttool.dev_tool.actions.init import generate_credentials +from manifesttool.dev_tool.actions.init import generate_update_default_resources_c + + +def test_generate_update_default_resources_c_happy_day(tmp_path): + key_file = tmp_path / 'dev.key.pem' + certificate_file = tmp_path / 'dev.cert.der' + generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False, + cred_valid_time=8 + ) + c_source = tmp_path / 'my_source.c' + vendor_id = uuid.uuid4() + class_id = uuid.uuid4() + + generate_update_default_resources_c( + c_source=c_source, + vendor_id=vendor_id, + class_id=class_id, + private_key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False + ) + assert c_source.is_file() + gen_data = c_source.read_text() + assert 'arm_uc_vendor_id' in gen_data + assert 'arm_uc_class_id' in gen_data + assert 'arm_uc_default_certificate' in gen_data \ No newline at end of file diff --git a/tests/mtool/test_create.py b/tests/mtool/test_create.py new file mode 100644 index 0000000..3fe5f2b --- /dev/null +++ b/tests/mtool/test_create.py @@ -0,0 +1,368 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import binascii +import uuid +from pathlib import Path +from typing import Type + +import pytest +import yaml +from cryptography.hazmat import backends +from cryptography.hazmat.primitives import hashes + +from manifesttool.mtool import mtool, ecdsa_helper +from manifesttool.mtool.actions.create import CreateAction +from manifesttool.mtool.asn1 import ManifestAsnCodecBase, ManifestVersion +from manifesttool.mtool.asn1.v1 import ManifestAsnCodecV1 +from tests.conftest import data_generator + +SCRIPT_DIR = Path(__file__).resolve().parent +GEN_DIR = SCRIPT_DIR / 'test_data' + +FILE_ID = 0 + + +@pytest.mark.parametrize('fw_size', [512, 713, 4096, 100237, 512001]) +def test_create_happy_day_full( + tmp_path_factory, + fw_size +): + global FILE_ID + GEN_DIR.mkdir(exist_ok=True) + happy_day_data = data_generator(tmp_path_factory, fw_size) + manifest = None + for manifest_codec in ManifestVersion.list_codecs(): + input_cfg = { + 'vendor': { + 'domain': 'arm.com' + }, + 'device': { + 'model-name': 'my-device' + }, + 'priority': 15, + 'payload': { + 'url': '../test_data/{}_f_payload.bin'.format(FILE_ID), + 'file-path': happy_day_data['fw_file'].as_posix(), + 'format': 'raw-binary' + } + } + if issubclass(manifest_codec, ManifestAsnCodecV1): + version = 100500 + version_file = GEN_DIR / '{}_f_version_{}.txt'.format( + FILE_ID, + manifest_codec.get_name()) + version_file.write_text(str(version)) + else: + component = 'MAIN' + if (FILE_ID % 2) == 0: + component = 'TESTCOMP' + input_cfg['component'] = component + elif (FILE_ID % 3) == 0: + input_cfg['component'] = component + version = '100.500.0' + + version_file = GEN_DIR / '{}_f_version_{}.txt'.format( + FILE_ID, manifest_codec.get_name()) + version_file.write_text('.'.join(version)) + + component_file = GEN_DIR / '{}_f_component.txt'.format(FILE_ID) + component_file.write_text(component) + + manifest = CreateAction.do_create( + pem_key_data=happy_day_data['key_file'].read_bytes(), + input_cfg=input_cfg, + fw_version=version, + update_certificate=happy_day_data['certificate_file'], + asn1_codec_class=manifest_codec + ) + GEN_DIR.mkdir(exist_ok=True) + + manifest_file = GEN_DIR / '{}_f_manifest_{}.bin'.format( + FILE_ID, manifest_codec.get_name()) + manifest_file.write_bytes(manifest) + + certificate_file = GEN_DIR / '{}_f_certificate.bin'.format(FILE_ID) + certificate_file.write_bytes( + happy_day_data['certificate_file'].read_bytes()) + + payload_file = GEN_DIR / '{}_f_payload.bin'.format(FILE_ID) + payload_file.write_bytes(happy_day_data['fw_file'].read_bytes()) + + orig_fw_file = GEN_DIR / '{}_f_curr_fw.bin'.format(FILE_ID) + orig_fw_file.write_bytes(happy_day_data['fw_file'].read_bytes()) + + new_fw_file = GEN_DIR / '{}_f_final_image.bin'.format(FILE_ID) + new_fw_file.write_bytes(happy_day_data['fw_file'].read_bytes()) + + dom = manifest_codec.decode(manifest, None) + + vendor_id_file = GEN_DIR / '{}_f_vendor_id.bin'.format(FILE_ID) + if manifest_codec.get_name() == 'v3': + vendor_id_bytes = dom['manifest']['vendor-id'] + class_id_bytes = dom['manifest']['class-id'] + elif manifest_codec.get_name() == 'v1': + vendor_id_bytes = \ + dom['resource']['resource']['manifest']['vendorId'] + class_id_bytes = dom['resource']['resource']['manifest']['classId'] + else: + raise AssertionError( + 'invalid manifest version ' + manifest_codec.get_name()) + vendor_id_file.write_bytes(vendor_id_bytes) + + class_id_file = GEN_DIR / '{}_f_class_id.bin'.format(FILE_ID) + + class_id_file.write_bytes(class_id_bytes) + + key_file = GEN_DIR / '{}_f_priv_key.bin'.format(FILE_ID) + private_key_data = happy_day_data['key_file'].read_bytes() + key_file.write_bytes(private_key_data) + + public_key = ecdsa_helper.public_key_from_private(private_key_data) + public_key_bytes = ecdsa_helper.public_key_to_bytes(public_key) + + public_key_file = GEN_DIR / '{}_f_pub_key.bin'.format(FILE_ID) + public_key_file.write_bytes(public_key_bytes) + + FILE_ID += 1 + + print( + 'Full manifest in HEX to be viewed on ' + 'https://asn1.io/asn1playground/ \n' + binascii.hexlify( + manifest).decode('utf-8')) + + +def calc_digest(payload_file): + hash_ctx = hashes.Hash(hashes.SHA256(), backends.default_backend()) + buf = payload_file.read_bytes() + hash_ctx.update(buf) + digest = hash_ctx.finalize() + + return digest.hex() + + +@pytest.mark.parametrize('fw_size', [512, 713, 4096, 100237, 512001]) +def test_create_happy_day_delta( + tmp_path_factory, + fw_size +): + global FILE_ID + GEN_DIR.mkdir(exist_ok=True) + happy_day_data = data_generator(tmp_path_factory, fw_size) + manifest = None + for manifest_version in ManifestVersion.list_codecs(): + input_cfg = { + 'vendor': { + 'domain': 'arm.com' + }, + 'device': { + 'model-name': 'my-device' + }, + 'priority': 15, + 'payload': { + 'url': '../test_data/{}_d_payload.bin'.format(FILE_ID), + 'file-path': happy_day_data['delta_file'].as_posix(), + 'format': 'arm-patch-stream' + }, + 'sign-image': 'v1' not in manifest_version.get_name() # Bool + } + if issubclass(manifest_version, ManifestAsnCodecV1): + version = 100500 + version_file = GEN_DIR / '{}_d_version_{}.txt'.format( + FILE_ID, + manifest_version.get_name()) + version_file.write_text(str(version)) + else: + component = 'MAIN' + if (FILE_ID % 2) == 0: + component = 'TESTCOMP' + input_cfg['component'] = component + elif (FILE_ID % 3) == 0: + input_cfg['component'] = component + version = '100.500.0' + + version_file = GEN_DIR / '{}_d_version_{}.txt'.format( + FILE_ID, + manifest_version.get_name()) + version_file.write_text('.'.join(version)) + + component_file = GEN_DIR / '{}_d_component.txt'.format(FILE_ID) + component_file.write_text(component) + manifest = CreateAction.do_create( + pem_key_data=happy_day_data['key_file'].read_bytes(), + input_cfg=input_cfg, + update_certificate=happy_day_data['certificate_file'], + fw_version=version, + asn1_codec_class=manifest_version + ) + + manifest_file = GEN_DIR / '{}_d_manifest_{}.bin'.format( + FILE_ID, manifest_version.get_name()) + manifest_file.write_bytes(manifest) + + certificate_file = GEN_DIR / '{}_d_certificate.bin'.format(FILE_ID) + certificate_file.write_bytes( + happy_day_data['certificate_file'].read_bytes()) + + payload_file = GEN_DIR / '{}_d_payload.bin'.format(FILE_ID) + payload_file.write_bytes(happy_day_data['delta_file'].read_bytes()) + + orig_fw_file = GEN_DIR / '{}_d_curr_fw.bin'.format(FILE_ID) + orig_fw_file.write_bytes(happy_day_data['fw_file'].read_bytes()) + + new_fw_file = GEN_DIR / '{}_d_final_image.bin'.format(FILE_ID) + new_fw_file.write_bytes(happy_day_data['new_fw_file'].read_bytes()) + + dom = manifest_version.decode(manifest, None) + + vendor_id_file = GEN_DIR / '{}_d_vendor_id.bin'.format(FILE_ID) + if manifest_version.get_name() == 'v3': + vendor_id_bytes = dom['manifest']['vendor-id'] + class_id_bytes = dom['manifest']['class-id'] + elif manifest_version.get_name() == 'v1': + vendor_id_bytes = \ + dom['resource']['resource']['manifest']['vendorId'] + class_id_bytes = dom['resource']['resource']['manifest']['classId'] + else: + raise AssertionError( + 'invalid manifest version ' + manifest_version.get_name()) + vendor_id_file.write_bytes(vendor_id_bytes) + + class_id_file = GEN_DIR / '{}_d_class_id.bin'.format(FILE_ID) + class_id_file.write_bytes(class_id_bytes) + + key_file = GEN_DIR / '{}_d_priv_key.bin'.format(FILE_ID) + private_key_data = happy_day_data['key_file'].read_bytes() + key_file.write_bytes(private_key_data) + + public_key = ecdsa_helper.public_key_from_private(private_key_data) + public_key_bytes = ecdsa_helper.public_key_to_bytes(public_key) + + public_key_file = GEN_DIR / '{}_d_pub_key.bin'.format(FILE_ID) + public_key_file.write_bytes(public_key_bytes) + + FILE_ID += 1 + + print( + 'Delta manifest in HEX to be viewed on ' + 'https://asn1.io/asn1playground/ \n' + binascii.hexlify( + manifest).decode('utf-8')) + + +@pytest.mark.parametrize('manifest_version', ManifestVersion.list_codecs()) +def test_cli_delta( + happy_day_data, manifest_version: Type[ManifestAsnCodecBase]): + cli_test_common(happy_day_data, manifest_version, is_delta=True) + + +@pytest.mark.parametrize('manifest_version', ManifestVersion.list_codecs()) +def test_cli_full( + happy_day_data, manifest_version: Type[ManifestAsnCodecBase]): + cli_test_common(happy_day_data, manifest_version, is_delta=False) + + +def cli_test_common(happy_day_data, manifest_version, is_delta): + tmp_cfg = happy_day_data['tmp_path'] / 'input.yaml' + output_manifest = happy_day_data['tmp_path'] / 'foo.bin' + with tmp_cfg.open('wt') as fh: + yaml.dump( + { + 'vendor': { + 'domain': 'arm.com' + }, + 'device': { + 'model-name': 'my-device' + }, + 'priority': 15, + 'payload': { + 'url': 'https://my.server.com/some.file?new=1', + 'file-path': happy_day_data['delta_file'].as_posix(), + 'format': 'arm-patch-stream' if is_delta else 'raw-binary' + } + }, + fh + ) + action = 'create' + if 'v1' in manifest_version.get_name(): + action = 'create-v1' + cmd = [ + '--debug', + action, + '--config', tmp_cfg.as_posix(), + '--key', happy_day_data['key_file'].as_posix(), + '--output', output_manifest.as_posix() + ] + if manifest_version.get_name() == 'v1': + cmd.extend( + [ + '--update-certificate', + happy_day_data['certificate_file'].as_posix() + ] + ) + else: + cmd.extend(['--fw-version', '100.0.500']) + assert 0 == mtool.entry_point(cmd) + +@pytest.mark.parametrize('manifest_version', ManifestVersion.list_codecs()) +def test_create_happy_day_with_ids( + happy_day_data, + manifest_version +): + tmp_cfg = happy_day_data['tmp_path'] / 'input.yaml' + output_manifest = happy_day_data['tmp_path'] / 'foo.bin' + with tmp_cfg.open('wt') as fh: + yaml.dump( + { + 'vendor': { + 'vendor-id': uuid.uuid4().hex + }, + 'device': { + 'class-id': uuid.uuid4().hex + }, + 'priority': 15, + 'payload': { + 'url': 'https://my.server.com/some.file?new=1', + 'file-path': happy_day_data['delta_file'].as_posix(), + 'format': 'arm-patch-stream' + } + }, + fh + ) + action = 'create' + if 'v1' in manifest_version.get_name(): + action = 'create-v1' + cmd = [ + '--debug', + action, + '--config', tmp_cfg.as_posix(), + '--key', happy_day_data['key_file'].as_posix(), + '--output', output_manifest.as_posix() + ] + + if manifest_version.get_name() == 'v1': + cmd.extend( + [ + '--update-certificate', + happy_day_data['certificate_file'].as_posix() + ] + ) + else: + cmd.extend(['--fw-version', '100.500.8']) + + ret_code = mtool.entry_point(cmd) + + assert ret_code == 0 diff --git a/tests/mtool/test_parse.py b/tests/mtool/test_parse.py new file mode 100644 index 0000000..392a57b --- /dev/null +++ b/tests/mtool/test_parse.py @@ -0,0 +1,204 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import logging +import os +import sys + +import pytest +from _pytest.tmpdir import TempPathFactory +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import serialization + +from manifesttool.dev_tool.actions.init import generate_credentials +from manifesttool.mtool import mtool +from manifesttool.mtool.actions.create import CreateAction +from manifesttool.mtool.actions.parse import ParseAction +from manifesttool.mtool.asn1 import ManifestVersion + +logging.basicConfig( + stream=sys.stdout, + format='%(asctime)s %(levelname)s %(message)s', + level=logging.DEBUG +) + +@pytest.fixture(params=ManifestVersion.list_codecs()) +def happy_day_data( + tmp_path_factory: TempPathFactory, + request +): + tmp_path = tmp_path_factory.mktemp("data") + key_file = tmp_path / 'dev.key.pem' + certificate_file = tmp_path / 'dev.cert.der' + manifest_version = request.param # Type[ManifestAsnCodecBase] + generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False, + cred_valid_time=8 + ) + fw_file = tmp_path / 'fw.bin' + fw_file.write_bytes(os.urandom(512)) + + input_cfg = { + "manifest-version": manifest_version.get_name(), + "vendor": { + "domain": "arm.com", + "custom-data-path": fw_file.as_posix() + + }, + "device": { + "model-name": "my-device" + }, + "priority": 15, + "payload": { + "url": "https://my.server.com/some.file?new=1", + "file-path": fw_file.as_posix(), + "format": "raw-binary" + } + } + + fw_version = '100.500.0' + if 'v1' == manifest_version.get_name(): + fw_version = 0 + else: + input_cfg['sign-image'] = True + + manifest_data = CreateAction.do_create( + pem_key_data=key_file.read_bytes(), + input_cfg=input_cfg, + fw_version=fw_version, + update_certificate=certificate_file, + asn1_codec_class=manifest_version + ) + manifest_file = tmp_path / 'fota_manifest.bin' + manifest_file.write_bytes(manifest_data) + + private_key = serialization.load_pem_private_key( + key_file.read_bytes(), + password=None, + backend=default_backend() + ) + public_key = private_key.public_key() + public_key_bytes = public_key.public_bytes( + encoding=serialization.Encoding.X962, + format=serialization.PublicFormat.UncompressedPoint + ) + public_key_file = tmp_path / 'pub_key.bin' + public_key_file.write_bytes(public_key_bytes) + + return { + 'manifest_file': manifest_file, + 'certificate_file': certificate_file, + 'pub_key_file': public_key_file, + 'priv_key_file': key_file, + 'manifest_version': manifest_version.get_name(), + } + + +def test_parse_happy_day(happy_day_data): + ParseAction.do_parse( + certificate_data=None, + manifest_data=happy_day_data['manifest_file'].read_bytes(), + public_key_data=None, + private_key_data=None + ) + + +def test_parse_and_verify_happy_day(happy_day_data): + ParseAction.do_parse( + certificate_data=happy_day_data['certificate_file'].read_bytes(), + manifest_data=happy_day_data['manifest_file'].read_bytes(), + public_key_data=None, + private_key_data=None + ) + +def test_cli_parse_and_verify_happy_day_cert(happy_day_data): + + cmd = [ + '--debug', + 'parse', + happy_day_data['manifest_file'].as_posix(), + '--certificate', happy_day_data['certificate_file'].as_posix(), + ] + + assert 0 == mtool.entry_point(cmd) + +def test_cli_parse_and_verify_happy_day_pubkey(happy_day_data): + cmd = [ + '--debug', + 'parse', + '--public-key', happy_day_data['pub_key_file'].as_posix(), + happy_day_data['manifest_file'].as_posix() + ] + + assert 0 == mtool.entry_point(cmd) + + +def test_cli_parse_and_verify_happy_day_privkey(happy_day_data): + cmd = [ + '--debug', + 'parse', + happy_day_data['manifest_file'].as_posix(), + '--private-key', happy_day_data['priv_key_file'].as_posix() + ] + + assert 0 == mtool.entry_point(cmd) + +@pytest.mark.parametrize('manifest_version', ManifestVersion.list_codecs()) +def test_parse_malformed(manifest_version): + certificate_data = os.urandom(512) + manifest_data = os.urandom(512) + with pytest.raises(AssertionError) as e: + ParseAction.do_parse( + certificate_data=certificate_data, + manifest_data=manifest_data, + public_key_data=None, + private_key_data=None + ) + assert "Malformed manifest" in str(e) + + +def test_verify_malformed_certificate(happy_day_data): + certificate_data = os.urandom(512) + with pytest.raises(AssertionError) as e: + ParseAction.do_parse( + certificate_data=certificate_data, + manifest_data=happy_day_data['certificate_file'].read_bytes(), + public_key_data=None, + private_key_data=None + ) + assert 'Malformed certificate' in str(e) + + +def test_parse_and_verify_bad_signature(tmp_path, happy_day_data): + key_file = tmp_path / 'dev.key.pem' + certificate_file = tmp_path / 'dev.cert.der' + generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False, + cred_valid_time=8 + ) + with pytest.raises(AssertionError) as e: + ParseAction.do_parse( + certificate_data=certificate_file.read_bytes(), + manifest_data=happy_day_data['manifest_file'].read_bytes(), + public_key_data=None, + private_key_data=None + ) + assert 'Signature verification failed' in str(e) diff --git a/tests/mtool/test_public_key.py b/tests/mtool/test_public_key.py new file mode 100644 index 0000000..f22e672 --- /dev/null +++ b/tests/mtool/test_public_key.py @@ -0,0 +1,95 @@ +# ---------------------------------------------------------------------------- +# Copyright 2020 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- +import logging +import sys + +import pytest +from _pytest.tmpdir import TempPathFactory +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec + +from manifesttool.dev_tool.actions.init import generate_credentials +from manifesttool.mtool import mtool +from manifesttool.mtool.actions.public_key import PublicKeyAction + +logging.basicConfig( + stream=sys.stdout, + format='%(asctime)s %(levelname)s %(message)s', + level=logging.DEBUG +) + +@pytest.fixture() +def text_fixture( + tmp_path_factory: TempPathFactory +): + tmp_path = tmp_path_factory.mktemp("data") + key_file = tmp_path / 'dev.key.pem' + certificate_file = tmp_path / 'dev.cert.der' + generate_credentials( + key_file=key_file, + certificate_file=certificate_file, + do_overwrite=False, + cred_valid_time=8 + ) + + return { + 'tmp_path': tmp_path, + 'key_file': key_file + } + + +def test_parse_happy_day(text_fixture): + PublicKeyAction.get_key( + text_fixture['key_file'].read_bytes() + ) + +def test_parse_happy_day_cli(text_fixture): + output_file = text_fixture['tmp_path'] / 'out.bin' + cmd = [ + '--debug', + 'public-key', + text_fixture['key_file'].as_posix(), + '--out', output_file.as_posix() + ] + + assert 0 == mtool.entry_point(cmd) + + assert output_file.is_file() + assert output_file.stat().st_size == 65 # 0x04 + 32B + 32B + + private_key = serialization.load_pem_private_key( + text_fixture['key_file'].read_bytes(), + password=None, + backend=default_backend() + ) + + message = b'my super duper secret data to be signed' + + signature = private_key.sign( + message, + ec.ECDSA(hashes.SHA256()) + ) + + public_key = ec.EllipticCurvePublicKey.from_encoded_point( + curve=ec.SECP256R1(), + data=output_file.read_bytes() + ) + + public_key.verify(signature, message, ec.ECDSA(hashes.SHA256())) diff --git a/tests/mtool/test_schema.py b/tests/mtool/test_schema.py new file mode 100644 index 0000000..7440919 --- /dev/null +++ b/tests/mtool/test_schema.py @@ -0,0 +1,25 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +from manifesttool.mtool import mtool + + +def test_print_schema(): + print('Schema:') + cmd = ['schema'] + assert 0 == mtool.entry_point(cmd) \ No newline at end of file diff --git a/tools/asn2py.py b/tools/asn2py.py deleted file mode 100755 index 69b3dd1..0000000 --- a/tools/asn2py.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Copyright 2016 ARM Limited or its affiliates -# -# 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. -# ---------------------------------------------------------------------------- - -import sys, os, asn1ate - -from datetime import datetime -from io import StringIO -from asn1ate.parser import parse_asn1 -from asn1ate.pyasn1gen import build_semantic_model, generate_pyasn1 - -def header(source_file, version=""): - lastmod = datetime.fromtimestamp(os.path.getmtime(source_file)) - - return """\ -#---------------------------------------------------------------------------- -# The confidential and proprietary information contained in this file may -# only be used by a person authorised under and to the extent permitted -# by a subsisting licensing agreement from ARM Limited or its affiliates. -# -# (C) COPYRIGHT 2016 ARM Limited or its affiliates. -# ALL RIGHTS RESERVED -# -# This entire notice must be reproduced on all copies of this file -# and copies of this file may only be made by a person if such person is -# permitted to do so under the terms of a subsisting license agreement -# from ARM Limited or its affiliates. -#---------------------------------------------------------------------------- -# -*- coding: utf-8 -*- -# -# This file has been generated using asn1ate (v %s) from %r -# Last Modified on %s -""" % (version, source_file, lastmod) - -def get_asn_definition(f): - with open(f, "r") as fh: - return fh.read().strip() - -def generate_pyasn_code(definition): - parse_tree = parse_asn1(definition) - modules = build_semantic_model(parse_tree) - output = StringIO() - for module in modules: - generate_pyasn1(module, output, []) - return output.getvalue() - -def write_code_to_file(code, f, definition_file): - with open(f, "w") as fh: - fh.write(header(definition_file)) - fh.write(code) - -def main(): - input_asn_definition_file = sys.argv[1] - output_pyasn_file = sys.argv[2] - - asn_defintion = get_asn_definition(input_asn_definition_file) - code = generate_pyasn_code(asn_defintion) - write_code_to_file(code, output_pyasn_file, input_asn_definition_file) - -if __name__ == "__main__": - main() diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..ef8c185 --- /dev/null +++ b/tox.ini @@ -0,0 +1,49 @@ +# ---------------------------------------------------------------------------- +# Copyright 2019 ARM Limited or its affiliates +# +# 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. +# ---------------------------------------------------------------------------- + +[pycodestyle] +exclude = manifest_schema_v3.py,manifest_schema_v1.py +ignore = E302 + +[bandit] +skips = B101 + +[tox] +envlist = + py35, + py36, + py37, + py38 + + +[testenv] +usedevelop=True +deps = -r{toxinidir}/requirements.txt + -r{toxinidir}/dev-requirements.txt + +commands = + pycodestyle manifesttool + pylint manifesttool + coverage erase + {envbindir}/pytest {posargs: tests --cov-append --cov=manifesttool --cov-report html --cov-report term} + {envpython} setup.py bdist_wheel + bandit --ini tox.ini -r manifesttool + + + +