pax_global_header 0000666 0000000 0000000 00000000064 14571175157 0014527 g ustar 00root root 0000000 0000000 52 comment=699bc85d0a0a76bd9cc96adc3199354083de26fe
osslsigncode-2.8/ 0000775 0000000 0000000 00000000000 14571175157 0014074 5 ustar 00root root 0000000 0000000 osslsigncode-2.8/.github/ 0000775 0000000 0000000 00000000000 14571175157 0015434 5 ustar 00root root 0000000 0000000 osslsigncode-2.8/.github/workflows/ 0000775 0000000 0000000 00000000000 14571175157 0017471 5 ustar 00root root 0000000 0000000 osslsigncode-2.8/.github/workflows/ci.yml 0000664 0000000 0000000 00000013253 14571175157 0020613 0 ustar 00root root 0000000 0000000 name: CI
on:
push:
pull_request:
env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
BUILD_TYPE: Release
version: osslsigncode-2.8
jobs:
build:
strategy:
fail-fast: false
matrix:
include:
- id: ubuntu-22.04
triplet: x64-linux
compiler: gcc
os: ubuntu-22.04
generator: Unix Makefiles
vcpkg_root:
- id: ubuntu-20.04
triplet: x64-linux
compiler: gcc
os: ubuntu-20.04
generator: Unix Makefiles
vcpkg_root:
- id: macOS
triplet: x64-osx
compiler: clang
os: macOS-latest
generator: Unix Makefiles
vcpkg_root: /usr/local/share/vcpkg
cache: /Users/runner/.cache/vcpkg/archives
- id: windows-x64-vs
triplet: x64-windows
compiler: vs
arch: x64
os: windows-latest
generator: Ninja
vcpkg_root: C:/vcpkg
cache: C:/Users/runneradmin/AppData/Local/vcpkg/archives
- id: windows-x86-vs
triplet: x86-windows
compiler: vs
arch: x86
os: windows-latest
generator: Ninja
vcpkg_root: C:/vcpkg
cache: C:/Users/runneradmin/AppData/Local/vcpkg/archives
- id: windows-x64-static-vs
triplet: x64-windows-static
compiler: vs
arch: x64
os: windows-latest
generator: Ninja
vcpkg_root: C:/vcpkg
cache: C:/Users/runneradmin/AppData/Local/vcpkg/archives
- id: windows-x64-mingw
triplet: x64-windows
compiler: mingw
os: windows-latest
generator: Ninja
vcpkg_root: C:/vcpkg
cache: C:/Users/runneradmin/AppData/Local/vcpkg/archives
runs-on: ${{matrix.os}}
env:
VCPKG_ROOT: ${{matrix.vcpkg_root}}
steps:
- uses: actions/checkout@v3
- name: Cache the vcpkg archives
if: matrix.cache != ''
uses: actions/cache@v3
with:
path: ${{matrix.cache}}
key: ${{matrix.id}}-${{hashFiles('vcpkg.json')}}
restore-keys: |
${{matrix.id}}-${{hashFiles('vcpkg.json')}}
${{matrix.id}}-
- name: Configure Visual Studio
if: matrix.compiler == 'vs'
uses: ilammy/msvc-dev-cmd@v1
with:
arch: ${{matrix.arch}}
- name: Install MSYS2
if: matrix.compiler == 'mingw'
uses: msys2/setup-msys2@v2
with:
update: true
install: mingw-w64-x86_64-ninja
- name: Put MSYS2_MinGW64 on PATH
if: matrix.compiler == 'mingw'
run: echo "D:/a/_temp/msys64/mingw64/bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
- name: Install apt dependencies (Linux)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libssl-dev libcurl4-openssl-dev faketime
- name: Install brew dependencies (macOS)
if: runner.os == 'macOS'
run: |
brew install python@3.8
- name: Install Xcode (macOS)
if: runner.os == 'macOS'
uses: maxim-lobanov/setup-xcode@v1
with:
xcode-version: latest-stable
- name: Setup the oldest supported version of cmake (macOS)
if: runner.os == 'macOS'
uses: jwlawson/actions-setup-cmake@v1.12
with:
cmake-version: '3.17.0'
- name: Show OpenSSL version
run: openssl version -a
- name: Configure CMake
run: cmake
-G "${{matrix.generator}}"
-S ${{github.workspace}}
-B ${{github.workspace}}/build
-DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
-DCMAKE_INSTALL_PREFIX=${{github.workspace}}/dist
-DVCPKG_TARGET_TRIPLET=${{matrix.triplet}}
- name: Build
run: cmake
--build ${{github.workspace}}/build
--config ${{env.BUILD_TYPE}}
- name: Start HTTP server (macOS)
working-directory: ${{github.workspace}}/build
if: runner.os == 'macOS'
run: |
python3.8 --version
python3.8 ./Testing/server_http.py --port 19254
while test ! -s ./Testing/logs/port.log; do sleep 1; done
- name: Start HTTP server (Windows)
working-directory: ${{github.workspace}}\build
if: runner.os == 'Windows'
run: |
python.exe --version
$Args = '.\Testing\server_http.pyw --port 19254'
$File = '.\Testing\logs\port.log'
Start-Process -FilePath pythonw.exe -ArgumentList $Args
while(-not(Test-Path -Path $File -PathType Leaf) -or [String]::IsNullOrWhiteSpace((Get-Content $File))) {Start-Sleep -Seconds 1}
Get-Content '.\Testing\logs\server.log'
- name: List files (Linux/macOS)
if: runner.os != 'Windows'
run: find .. -ls
- name: List files (Windows)
if: runner.os == 'Windows'
run: Get-ChildItem -Recurse -Name ..
- name: Test
working-directory: ${{github.workspace}}/build
run: ctest -C ${{env.BUILD_TYPE}}
- name: Upload the errors
uses: actions/upload-artifact@v3
if: failure()
with:
name: errors-${{matrix.id}}
path: |
${{github.workspace}}/build/Testing/Temporary/LastTest.log
${{github.workspace}}/build/Testing/conf/makecerts.log
${{github.workspace}}/build/Testing/logs/server.log
${{github.workspace}}/build/Testing/logs/port.log
- name: Install
run: cmake --install ${{github.workspace}}/build
- name: Upload the executables
uses: actions/upload-artifact@v3
with:
name: ${{env.version}}-${{matrix.id}}
path: ${{github.workspace}}/dist
osslsigncode-2.8/.github/workflows/codeql-analysis.yml 0000664 0000000 0000000 00000004034 14571175157 0023305 0 ustar 00root root 0000000 0000000 name: "CodeQL"
on:
push:
branches: [ "master" ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ "master" ]
schedule:
- cron: '45 1 * * 2'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'cpp' ]
steps:
- name: Checkout repository
uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# тД╣я╕П Command-line programs to run using the OS shell.
# ЁЯУЪ See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
osslsigncode-2.8/.github/workflows/coverity.yml 0000664 0000000 0000000 00000001240 14571175157 0022055 0 ustar 00root root 0000000 0000000 name: Coverity Scan
on:
push:
workflow_dispatch:
jobs:
coverity:
runs-on: ubuntu-latest
env:
token: ${{secrets.COVERITY_SCAN_TOKEN}}
steps:
- uses: actions/checkout@v3
if: env.token
- name: Get ready for scanning
if: env.token
run: |
sudo apt-get update
sudo apt-get install -y libssl-dev libcurl4-openssl-dev
cmake -S ${{github.workspace}} -B ${{github.workspace}}/build
- uses: vapier/coverity-scan-action@v1
if: env.token
with:
email: ${{secrets.COVERITY_SCAN_EMAIL}}
token: ${{secrets.COVERITY_SCAN_TOKEN}}
command: make -C ${{github.workspace}}/build
osslsigncode-2.8/.gitignore 0000664 0000000 0000000 00000000541 14571175157 0016064 0 ustar 00root root 0000000 0000000 build/
CMakeFiles/
_CPack_Packages/
Testing/
.vs/
CMakeCache.txt
cmake_install.cmake
config.h
CPackConfig.cmake
CPackSourceConfig.cmake
CTestTestfile.cmake
install_manifest.txt
Makefile
osslsigncode
osslsigncode.exe
stamp-h1
.#*#
.*.bak
.*.orig
.*.rej
.*~
#*#
*.asc
*.bak
*.bz2
*.d
*.def
*.dll
*.gz
*.la
*.lib
*.lo
*.orig
*.pc
*.pdb
*.rej
*.u
*.rc
*~
osslsigncode-2.8/CMakeLists.txt 0000664 0000000 0000000 00000006747 14571175157 0016652 0 ustar 00root root 0000000 0000000 # required cmake version
cmake_minimum_required(VERSION 3.17)
# autodetect vcpkg CMAKE_TOOLCHAIN_FILE if VCPKG_ROOT is defined
# this needs to be configured before the project() directive
if(DEFINED ENV{VCPKG_ROOT} AND NOT $ENV{VCPKG_ROOT} STREQUAL "" AND NOT DEFINED CMAKE_TOOLCHAIN_FILE)
set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" CACHE STRING "")
endif(DEFINED ENV{VCPKG_ROOT} AND NOT $ENV{VCPKG_ROOT} STREQUAL "" AND NOT DEFINED CMAKE_TOOLCHAIN_FILE)
set(BUILTIN_SOCKET ON CACHE BOOL "") # for static Python
# configure basic project information
project(osslsigncode
VERSION 2.8
DESCRIPTION "OpenSSL based Authenticode signing for PE, CAB, CAT and MSI files"
HOMEPAGE_URL "https://github.com/mtrojnar/osslsigncode"
LANGUAGES C)
# force nonstandard version format for development packages
set(DEV "")
set(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}${DEV}")
# version and contact information
set(PACKAGE_STRING "${PROJECT_NAME} ${PROJECT_VERSION}")
set(PACKAGE_BUGREPORT "Michal.Trojnara@stunnel.org")
# specify the C standard
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
# load CMake library modules
include(FindOpenSSL)
include(FindCURL)
include(FindZLIB)
# load CMake project modules
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake")
include(SetBashCompletion)
include(FindHeaders)
# define the target
add_executable(osslsigncode)
# add compiler/linker flags
include(SetCompilerFlags)
# create and use config.h
configure_file(Config.h.in config.h)
target_compile_definitions(osslsigncode PRIVATE HAVE_CONFIG_H=1)
# set sources
target_sources(osslsigncode PRIVATE osslsigncode.c helpers.c utf.c msi.c pe.c cab.c cat.c appx.c script.c)
if(NOT UNIX)
target_sources(osslsigncode PRIVATE applink.c)
endif(NOT UNIX)
# set include directories
target_include_directories(osslsigncode PRIVATE "${PROJECT_BINARY_DIR}")
# set OpenSSL includes/libraries
if(NOT OPENSSL_FOUND)
message(FATAL_ERROR "OpenSSL library not found")
endif(NOT OPENSSL_FOUND)
target_include_directories(osslsigncode PRIVATE ${OPENSSL_INCLUDE_DIR})
target_link_libraries(osslsigncode PRIVATE ${OPENSSL_LIBRARIES})
# set cURL includes/libraries
if(CURL_FOUND)
target_compile_definitions(osslsigncode PRIVATE ENABLE_CURL=1)
target_include_directories(osslsigncode PRIVATE ${CURL_INCLUDE_DIRS})
target_link_libraries(osslsigncode PRIVATE ${CURL_LIBRARIES})
message(STATUS "cURL support enabled")
else(CURL_FOUND)
message(STATUS "cURL support disabled (library not found)")
endif(CURL_FOUND)
if(NOT ZLIB_FOUND)
message(FATAL_ERROR "Zlib library not found")
endif(NOT ZLIB_FOUND)
target_include_directories(osslsigncode PRIVATE ${ZLIB_INCLUDE_DIR})
target_link_libraries(osslsigncode PRIVATE ${ZLIB_LIBRARIES})
# add paths to linker search and installed rpath
set_target_properties(osslsigncode PROPERTIES INSTALL_RPATH_USE_LINK_PATH TRUE)
# testing with CTest
include(CMakeTest)
# installation rules for a project
set(BINDIR "${CMAKE_INSTALL_PREFIX}/bin")
install(TARGETS osslsigncode RUNTIME DESTINATION ${BINDIR})
if(UNIX)
include(CMakeDist)
else(UNIX)
install(
DIRECTORY ${PROJECT_BINARY_DIR}/ DESTINATION ${BINDIR}
FILES_MATCHING
PATTERN "*.dll"
PATTERN "vcpkg_installed" EXCLUDE
PATTERN "CMakeFiles" EXCLUDE
PATTERN "Testing" EXCLUDE)
endif(UNIX)
#[[
Local Variables:
c-basic-offset: 4
tab-width: 4
indent-tabs-mode: nil
End:
vim: set ts=4 expandtab:
]]
osslsigncode-2.8/CMakeSettings.json 0000664 0000000 0000000 00000002773 14571175157 0017501 0 ustar 00root root 0000000 0000000 я╗┐{
"configurations": [
{
"name": "x86-Debug",
"generator": "Ninja",
"configurationType": "Debug",
"buildRoot": "${projectDir}\\out\\build\\${name}",
"installRoot": "${projectDir}\\out\\install\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "",
"ctestCommandArgs": "",
"inheritEnvironments": [ "msvc_x86" ]
},
{
"name": "x86-Release",
"generator": "Ninja",
"configurationType": "RelWithDebInfo",
"buildRoot": "${projectDir}\\out\\build\\${name}",
"installRoot": "${projectDir}\\out\\install\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "",
"ctestCommandArgs": "",
"inheritEnvironments": [ "msvc_x86" ]
},
{
"name": "x64-Debug",
"generator": "Ninja",
"configurationType": "Debug",
"buildRoot": "${projectDir}\\out\\build\\${name}",
"installRoot": "${projectDir}\\out\\install\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "",
"ctestCommandArgs": "",
"inheritEnvironments": [ "msvc_x64_x64" ],
"variables": []
},
{
"name": "x64-Release",
"generator": "Ninja",
"configurationType": "RelWithDebInfo",
"buildRoot": "${projectDir}\\out\\build\\${name}",
"installRoot": "${projectDir}\\out\\install\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "",
"ctestCommandArgs": "",
"inheritEnvironments": [ "msvc_x64_x64" ],
"variables": []
}
]
} osslsigncode-2.8/COPYING.txt 0000664 0000000 0000000 00000104513 14571175157 0015751 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
osslsigncode-2.8/Config.h.in 0000664 0000000 0000000 00000000623 14571175157 0016060 0 ustar 00root root 0000000 0000000 /* the configured options and settings for osslsigncode */
#define VERSION_MAJOR "@osslsigncode_VERSION_MAJOR@"
#define VERSION_MINOR "@osslsigncode_VERSION_MINOR@"
#cmakedefine PACKAGE_STRING "@PACKAGE_STRING@"
#cmakedefine PACKAGE_BUGREPORT "@PACKAGE_BUGREPORT@"
#cmakedefine HAVE_TERMIOS_H
#cmakedefine HAVE_GETPASS
#cmakedefine HAVE_SYS_MMAN_H
#cmakedefine HAVE_MMAP
#cmakedefine HAVE_MAPVIEWOFFILE
osslsigncode-2.8/Dockerfile 0000664 0000000 0000000 00000001434 14571175157 0016070 0 ustar 00root root 0000000 0000000 # Stage 1: Build osslsigncode on Alpine
FROM alpine:latest AS builder
# Install build dependencies
RUN apk add --no-cache build-base cmake openssl-dev curl-dev
# Copy osslsigncode source code into the image
COPY . /source
# Build osslsigncode
RUN cd /source && \
mkdir -p build && \
cd build && \
rm -f CMakeCache.txt && \
cmake -S .. && \
cmake --build . && \
cmake --install .
# Stage 2: Create final image without build environment
FROM alpine:latest
# Copy compiled binary from builder stage
COPY --from=builder /usr/local/bin/osslsigncode /usr/local/bin/osslsigncode
# Install necessary runtime libraries (latest version)
RUN apk add --no-cache libcrypto3 libcurl
# Set working directory
WORKDIR /workdir
# Declare volume to mount files
VOLUME [ "/workdir" ]
osslsigncode-2.8/INSTALL.W32.md 0000664 0000000 0000000 00000007653 14571175157 0016111 0 ustar 00root root 0000000 0000000 # osslsigncode Windows install notes
### Building osslsigncode source with MSYS2 MinGW 64-bit and MSYS2 packages:
1) Download and install MSYS2 from https://msys2.github.io/ and follow installation instructions.
Once up and running install even mingw-w64-x86_64-gcc, mingw-w64-x86_64-curl.
```
pacman -S mingw-w64-x86_64-gcc mingw-w64-x86_64-curl
```
mingw-w64-x86_64-openssl and mingw-w64-x86_64-zlib packages are installed with dependencies.
2) Run "MSYS2 MinGW 64-bit" and build 64-bit Windows executables.
```
cd osslsigncode-folder
x86_64-w64-mingw32-gcc *.c -o osslsigncode.exe \
-lcrypto -lssl -lcurl \
-D 'PACKAGE_STRING="osslsigncode x.y"' \
-D 'PACKAGE_BUGREPORT="Your.Email@example.com"' \
-D ENABLE_CURL
```
3) Run "Command prompt" and include "c:\msys64\mingw64\bin" folder as part of the path.
```
path=%path%;c:\msys64\mingw64\bin
cd osslsigncode-folder
osslsigncode.exe -v
osslsigncode 2.4, using:
OpenSSL 1.1.1g 21 Apr 2020 (Library: OpenSSL 1.1.1g 21 Apr 2020)
libcurl/7.70.0 OpenSSL/1.1.1g (Schannel) zlib/1.2.11 brotli/1.0.7 libidn2/2.3.0
libpsl/0.21.0 (+libidn2/2.3.0) libssh2/1.9.0 nghttp2/1.40.0
```
### Building OpenSSL, Curl and osslsigncode sources with MSYS2 MinGW 64-bit:
1) Download and install MSYS2 from https://msys2.github.io/ and follow installation instructions.
Once up and running install even: perl make autoconf automake libtool pkg-config.
```
pacman -S perl make autoconf automake libtool pkg-config
```
Make sure there are no curl, brotli, libpsl, libidn2 and nghttp2 packages installed:
```
pacman -R mingw-w64-x86_64-curl \
mingw-w64-x86_64-brotli \
mingw-w64-x86_64-libpsl \
mingw-w64-x86_64-libidn2 \
mingw-w64-x86_64-nghttp2
```
Run "MSYS2 MinGW 64-bit" in the administrator mode.
2) Build and install OpenSSL.
```
cd openssl-(version)
./config --prefix='C:/OpenSSL' --openssldir='C:/OpenSSL'
make && make install
```
3) Build and install curl.
```
cd curl-(version)
./buildconf
./configure --prefix='C:/curl' --with-ssl='C:/OpenSSL' \
--disable-ftp --disable-tftp --disable-file --disable-dict \
--disable-telnet --disable-imap --disable-smb --disable-smtp \
--disable-gopher --disable-pop --disable-pop3 --disable-rtsp \
--disable-ldap --disable-ldaps --disable-unix-sockets \
--disable-pthreads --without-zstd --without-zlib
make && make install
```
3) Build 64-bit Windows executables.
```
cd osslsigncode-folder
x86_64-w64-mingw32-gcc *.c -o osslsigncode.exe \
-L 'C:/OpenSSL/lib/' -lcrypto -lssl \
-I 'C:/OpenSSL/include/' \
-L 'C:/curl/lib' -lcurl \
-I 'C:/curl/include' \
-D 'PACKAGE_STRING="osslsigncode x.y"' \
-D 'PACKAGE_BUGREPORT="Your.Email@example.com"' \
-D ENABLE_CURL
```
4) Run "Command prompt" and copy required libraries.
```
cd osslsigncode-folder
copy C:\OpenSSL\bin\libssl-1_1-x64.dll
copy C:\OpenSSL\bin\libcrypto-1_1-x64.dll
copy C:\curl\bin\libcurl-4.dll
osslsigncode.exe -v
osslsigncode 2.4, using:
OpenSSL 1.1.1k 25 Mar 2021 (Library: OpenSSL 1.1.1k 25 Mar 2021)
libcurl/7.78.0 OpenSSL/1.1.1k
```
### Building OpenSSL, Curl and osslsigncode sources with Microsoft Visual Studio:
1) Install and integrate vcpkg: https://vcpkg.io/en/getting-started.html
2) Git clone osslsigncode: https://github.com/mtrojnar/osslsigncode/
3) Build osslsigncode with GUI or cmake.
Navigate to the build directory and run CMake to configure the osslsigncode project
and generate a native build system:
```
mkdir build && cd build && cmake -S .. -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=[installation directory] -DCMAKE_TOOLCHAIN_FILE=[path to vcpkg]/scripts/buildsystems/vcpkg.cmake
```
Then call that build system to actually compile/link the osslsigncode project:
```
cmake --build .
```
4) Make tests.
```
ctest -C Release
```
5) Make install (with administrative privileges if necessary).
```
cmake --install .
```
osslsigncode-2.8/LICENSE.txt 0000664 0000000 0000000 00000002747 14571175157 0015731 0 ustar 00root root 0000000 0000000 OpenSSL based Authenticode signing for PE/MSI/Java CAB files.
Copyright (C) 2005-2014 Per Allansson
Copyright (C) 2018-2022 Micha┼В Trojnara
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations
including the two.
You must obey the GNU General Public License in all respects
for all of the code used other than OpenSSL. If you modify
file(s) with this exception, you may extend this exception to your
version of the file(s), but you are not obligated to do so. If you
do not wish to do so, delete this exception statement from your
version. If you delete this exception statement from all source
files in the program, then also delete it here.
osslsigncode-2.8/NEWS.md 0000664 0000000 0000000 00000015612 14571175157 0015177 0 ustar 00root root 0000000 0000000 # osslsigncode change log
### 2.8 (2024.03.03)
- Microsoft PowerShell signing sponsored by Cisco Systems, Inc.
- fixed setting unauthenticated attributes (Countersignature, Unauthenticated
Data Blob) in a nested signature
- added the "-index" option to verify a specific signature or modify its
unauthenticated attributes
- added CAT file verification
- added listing the contents of a CAT file with the "-verbose" option
- added the new "extract-data" command to extract a PKCS#7 data content to be
signed with "sign" and attached with "attach-signature"
- added PKCS9_SEQUENCE_NUMBER authenticated attribute support
- added the "-ignore-cdp" option to disable CRL Distribution Points (CDP)
online verification
- unsuccessful CRL retrieval and verification changed into a critical error
- the "-p" option modified to also use to configured proxy to connect CRL
Distribution Points
- added implicit allowlisting of the Microsoft Root Authority serial number
00C1008B3C3C8811D13EF663ECDF40
- added listing of certificate chain retrieved from the signature in case of
verification failure
### 2.7 (2023.09.19)
- fixed signing CAB files (by Michael Brown)
- fixed handling of unsupported commands (by Maxim Bagryantsev)
- fixed writing DIFAT sectors
- added APPX support (by Maciej Panek and Ma┼Вgorzata Olsz├│wka)
- added a built-in TSA response generation (-TSA-certs, -TSA-key
and -TSA-time options)
### 2.6 (2023.05.29)
- modular architecture implemented to simplify adding file formats
- added verification of CRLs specified in the signing certificate
- added MSI DIFAT sectors support (by Max Bagryantsev)
- added legacy provider support for OpenSSL 3.0.0 and later
- fixed numerous bugs
### 2.5 (2022.08.12)
- fixed the Unix executable install path
- fixed the hardcoded "pkcs11" engine id
- fixed building with MinGW
- fixed testing with the python3 distributed with Ubuntu 18.04
### 2.4 (2022.08.02)
- migrated the build system from GNU Autoconf to CMake
- added the "-h" option to set the cryptographic hash function
for the "attach -signature" and "add" commands
- set the default hash function to "sha256"
- added the "attach-signature" option to compute and compare the
leaf certificate hash for the "add" command
- renamed the "-st" option "-time" (the old name is accepted for
compatibility)
- updated the "-time" option to also set explicit verification time
- added the "-ignore-timestamp" option to disable timestamp server
signature verification
- removed the "-timestamp-expiration" option
- fixed several bugs
- updated the included documentation
- enabled additional compiler/linker hardening options
- added CI based on GitHub Actions
### 2.3 (2022.03.06)
**CRITICAL SECURITY VULNERABILITIES**
This release fixes several critical memory corruption vulnerabilities.
A malicious attacker could create a file, which, when processed with
osslsigncode, triggers arbitrary code execution. Any previous version
of osslsigncode should be immediately upgraded if the tool is used for
processing of untrusted files.
- fixed several memory safety issues
- fixed non-interactive PVK (MSBLOB) key decryption
- added a bash completion script
- added CA bundle path auto-detection
### 2.2 (2021.08.15)
- CAT files support (thanks to James McKenzie)
- MSI support rewritten without libgsf dependency, which allows
for handling of all the needed MSI metadata, such as dates
- "-untrusted" option renamed to "-TSA-CAfile"
- "-CRLuntrusted" option renamed to "-TSA-CRLfile"
- numerous bug fixes and improvements
### 2.1 (2020-10-11)
- certificate chain verification support
- timestamp verification support
- CRL verification support ("-CRLfile" option)
- improved CAB signature support
- nested signatures support
- user-specified signing time ("-st" option) by vszakats
- added more tests
- fixed numerous bugs
- dropped OpenSSL 1.1.0 support
### 2.0 (2018-12-04)
- orphaned project adopted by Micha┼В Trojnara
- ported to OpenSSL 1.1.x
- ported to SoftHSM2
- add support for pkcs11-based hardware tokens
(Patch from Leif Johansson)
- improved error reporting of timestamping errors
(Patch from Carlo Teubner)
### 1.7.1 (2014-07-11)
- MSI: added -add-msi-dse option
(Patch from Mikkel Krautz)
- MSI: fix build when GSF_CAN_READ_MSI_METADATA defined
(Patch from Mikkel Krautz)
### 1.7 (2014-07-10)
- add support for nested signatures
(Patch from Mikkel Krautz)
- fix compilation problem with OpenSSL < 1.0.0
- added OpenSSL linkage exception to license
### 1.6 (2014-01-21)
- add support for reading password from file
- add support for asking for password (on systems that
provide support for it)
- add support for compiling and running on Windows
(Patch from Heiko Hund)
- fix compilation without curl
(Fix from Heiko Hund)
- added support for giving multiple timestamp servers
as arguments (first one that succeeds will be used)
- signatures on hierarchical MSI files were broken
(Fix from Mikkel Krautz)
- MSI: Add support for MsiDigitalSignatureEx signature
(Patch from Mikkel Krautz)
- add support for adding additional/cross certificates
through -ac option
(Thanks to Lars Munch for idea + testing)
- MSI: Add support for signature extract/remove/verify
(Patches from Mikkel Krautz)
- PE/MSI: Implement -require-leaf-hash for verify.
(Patch from Mikkel Krautz)
### 1.5.2 (2013-03-13)
- added support for signing with SHA-384 and SHA-512
- added support for page hashing (-ph option)
### 1.5.1 (2013-03-12)
- forgot to bump version number...
### 1.5 (2013-03-12)
- added support for signing MSI files (patch from Marc-Andr├й Lureau)
- calculate correct PE checksum instead of setting it to 0
(patch from Roland Schwingel)
- added support for RFC3161 timestamping (-ts option)
- added support for extracting/removing/verifying signature on PE files
- fixed problem with not being able to decode timestamps with no newlines
- added stricter checks for PE file validity
- added support for reading keys from PVK files (requires OpenSSL 1.0.0 or later)
- added support for reading certificates from PEM files
- renamed program option: -spc to -certs (old option name still valid)
### 1.4 (2011-08-12)
- improved build system (patch from Alon Bar-Lev)
- support reading cert+key from PKCS12 file (patch from Alon Bar-Lev)
- support reading key from PEM file
- added support for sha1/sha256 - default hash is now sha1
- added flag for commercial signing (default is individual)
### 1.3.1 (2009-08-07)
- support signing of 64-bit executables (fix from Paul Kendall)
### 1.3 (2008-01-31)
- fixed padding problem (fix from Ryan Rubley)
- allow signing of already signed files (fix from Ryan Rubley)
- added Ryan Rubley's PVK-to-DER guide into the README
### 1.2 (2005-01-21)
- autoconf:ed (Thanks to Roy Keene)
- added documentation
- don't override PKCS7_get_signed_attribute, it wasn't
actually needed, it was me being confused.
- compiles without curl, which means no timestamping
- version number output
### 1.1 (2005-01-19)
- Initial release
osslsigncode-2.8/README.md 0000664 0000000 0000000 00000016175 14571175157 0015365 0 ustar 00root root 0000000 0000000 osslsigncode
============
## BUILD STATUS
[](https://github.com/mtrojnar/osslsigncode/actions/workflows/ci.yml)
## WHAT IS IT?
osslsigncode is a small tool that implements part of the functionality
of the Microsoft tool signtool.exe - more exactly the Authenticode
signing and timestamping. But osslsigncode is based on OpenSSL and cURL,
and thus should be able to compile on most platforms where these exist.
## WHY?
Why not use signtool.exe? Because I don't want to go to a Windows
machine every time I need to sign a binary - I can compile and build
the binaries using Wine on my Linux machine, but I can't sign them
since the signtool.exe makes good use of the CryptoAPI in Windows, and
these APIs aren't (yet?) fully implemented in Wine, so the signtool.exe
tool would fail. And, so, osslsigncode was born.
## WHAT CAN IT DO?
It can sign and timestamp PE (EXE/SYS/DLL/etc), CAB, CAT and MSI files.
It supports the equivalent of signtool.exe's "-j javasign.dll -jp low",
i.e. add a valid signature for a CAB file containing Java files.
It supports getting the timestamp through a proxy as well. It also
supports signature verification, removal and extraction.
## BUILDING
This section covers building osslsigncode for [Unix-like](https://en.wikipedia.org/wiki/Unix-like) operating systems.
See [INSTALL.W32.md](https://github.com/mtrojnar/osslsigncode/blob/master/INSTALL.W32.md) for Windows notes.
We highly recommend downloading a [release tarball](https://github.com/mtrojnar/osslsigncode/releases) instead of cloning from a git repository.
### Configure, build, make tests and install osslsigncode
* Install prerequisites on a Debian-based distributions, such as Ubuntu:
```
sudo apt update && sudo apt install cmake libssl-dev libcurl4-openssl-dev zlib1g-dev python3
```
* Install prerequisites on macOS with Homebrew:
```
brew install cmake pkg-config openssl@1.1
export PKG_CONFIG_PATH="/usr/local/opt/openssl@1.1/lib/pkgconfig"
```
**NOTE:** osslsigncode requires CMake 3.17 or newer.
You may need to use `cmake3` instead of `cmake` to complete the following steps on your system.
* Navigate to the build directory and run CMake to configure the osslsigncode project
and generate a native build system:
```
mkdir build && cd build && cmake -S ..
```
optional CMake parameters:
```
-DCMAKE_BUILD_TYPE=Debug
-DCMAKE_C_COMPILER=clang
-DCMAKE_PREFIX_PATH=[openssl directory];[curl directory]
-DCMAKE_INSTALL_PREFIX=[installation directory]
-DBASH_COMPLETION_USER_DIR=[bash completion installation directory]
```
* Then call that build system to actually compile/link the osslsigncode project (alias `make`):
```
cmake --build .
```
* Make test:
```
ctest -C Release
```
* Make install:
```
sudo cmake --install .
```
* Make tarball (simulate autotools' `make dist`):
```
cmake --build . --target package_source
```
## USAGE
Before you can sign a file you need a Software Publishing
Certificate (spc) and a corresponding private key.
This article provides a good starting point as to how
to do the signing with the Microsoft signtool.exe:
http://www.matthew-jones.com/articles/codesigning.html
To sign with osslsigncode you need the certificate file mentioned in the
article above, in SPC or PEM format, and you will also need the private
key which must be a key file in DER or PEM format, or if osslsigncode was
compiled against OpenSSL 1.0.0 or later, in PVK format.
To sign a PE or MSI file you can now do:
```
osslsigncode sign -certs -key \
-n "Your Application" -i http://www.yourwebsite.com/ \
-in yourapp.exe -out yourapp-signed.exe
```
or if you are using a PEM or PVK key file with a password together
with a PEM certificate:
```
osslsigncode sign -certs \
-key -pass \
-n "Your Application" -i http://www.yourwebsite.com/ \
-in yourapp.exe -out yourapp-signed.exe
```
or if you want to add a timestamp as well:
```
osslsigncode sign -certs -key \
-n "Your Application" -i http://www.yourwebsite.com/ \
-t http://timestamp.digicert.com \
-in yourapp.exe -out yourapp-signed.exe
```
You can use a certificate and key stored in a PKCS#12 container:
```
osslsigncode sign -pkcs12 -pass \
-n "Your Application" -i http://www.yourwebsite.com/ \
-in yourapp.exe -out yourapp-signed.exe
```
To sign a CAB file containing java class files:
```
osslsigncode sign -certs -key \
-n "Your Application" -i http://www.yourwebsite.com/ \
-jp low \
-in yourapp.cab -out yourapp-signed.cab
```
Only the 'low' parameter is currently supported.
If you want to use PKCS11 token, you should indicate PKCS11 engine and module.
An example of using osslsigncode with SoftHSM:
```
osslsigncode sign \
-pkcs11engine /usr/lib64/engines-1.1/pkcs11.so \
-pkcs11module /usr/lib64/pkcs11/libsofthsm2.so \
-pkcs11cert 'pkcs11:token=softhsm-token;object=cert' \
-key 'pkcs11:token=softhsm-token;object=key' \
-in yourapp.exe -out yourapp-signed.exe
```
You can check that the signed file is correct by right-clicking
on it in Windows and choose Properties --> Digital Signatures,
and then choose the signature from the list, and click on
Details. You should then be presented with a dialog that says
amongst other things that "This digital signature is OK".
## UNAUTHENTICATED BLOBS
The "-addUnauthenticatedBlob" parameter adds a 1024-byte unauthenticated blob
of data to the signature in the same area as the timestamp. This can be used
while signing, while timestamping, after a file has been code signed, or by
itself. This technique (but not this project) is used by Dropbox, GoToMeeting,
and Summit Route.
### Example 1. Sign and add blob to unsigned file
```shell
osslsigncode sign -addUnauthenticatedBlob -pkcs12 yourcert.pfx -pass your_password -n "Your Company" -i https://YourSite.com/ -in srepp.msi -out srepp_added.msi
```
### Example 2. Timestamp and add blob to signed file
```shell
osslsigncode.exe add -addUnauthenticatedBlob -t http://timestamp.digicert.com -in your_signed_file.exe -out out.exe
```
### Example 3. Add blob to signed and time-stamped file
```shell
osslsigncode.exe add -addUnauthenticatedBlob -in your_signed_file.exe -out out.exe
```
### WARNING
This feature allows for doing dumb things. Be very careful with what you put
in the unauthenticated blob, as an attacker could modify this. Do NOT, under
any circumstances, put a URL here that you will use to download an additional
file. If you do do that, you would need to check the newly downloaded file is
code signed AND that it has been signed with your cert AND that it is the
version you expect.
## BUGS, QUESTIONS etc.
Check whether your your question or suspected bug was already
discussed on https://github.com/mtrojnar/osslsigncode/issues.
Otherwise, open a new issue.
BUT, if you have questions related to generating spc files,
converting between different formats and so on, *please*
spend a few minutes searching on google for your particular
problem since many people probably already have had your
problem and solved it as well.
osslsigncode-2.8/TODO.md 0000664 0000000 0000000 00000000272 14571175157 0015164 0 ustar 00root root 0000000 0000000 - signature extraction/removal/verificaton on MSI/CAB files
- clean up / untangle code
- separate timestamping
- remove mmap usage to increase portability
- fix other stuff marked 'XXX'
osslsigncode-2.8/applink.c 0000664 0000000 0000000 00000007171 14571175157 0015704 0 ustar 00root root 0000000 0000000 /*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#define APPLINK_STDIN 1
#define APPLINK_STDOUT 2
#define APPLINK_STDERR 3
#define APPLINK_FPRINTF 4
#define APPLINK_FGETS 5
#define APPLINK_FREAD 6
#define APPLINK_FWRITE 7
#define APPLINK_FSETMOD 8
#define APPLINK_FEOF 9
#define APPLINK_FCLOSE 10 /* should not be used */
#define APPLINK_FOPEN 11 /* solely for completeness */
#define APPLINK_FSEEK 12
#define APPLINK_FTELL 13
#define APPLINK_FFLUSH 14
#define APPLINK_FERROR 15
#define APPLINK_CLEARERR 16
#define APPLINK_FILENO 17 /* to be used with below */
#define APPLINK_OPEN 18 /* formally can't be used, as flags can vary */
#define APPLINK_READ 19
#define APPLINK_WRITE 20
#define APPLINK_LSEEK 21
#define APPLINK_CLOSE 22
#define APPLINK_MAX 22 /* always same as last macro */
#ifndef APPMACROS_ONLY
# include
# include
# include
# ifdef __BORLANDC__
/* _lseek in is a function-like macro so we can't take its address */
# undef _lseek
# define _lseek lseek
# endif
static void *app_stdin(void)
{
return stdin;
}
static void *app_stdout(void)
{
return stdout;
}
static void *app_stderr(void)
{
return stderr;
}
static int app_feof(FILE *fp)
{
return feof(fp);
}
static int app_ferror(FILE *fp)
{
return ferror(fp);
}
static void app_clearerr(FILE *fp)
{
clearerr(fp);
}
static int app_fileno(FILE *fp)
{
return _fileno(fp);
}
static int app_fsetmod(FILE *fp, char mod)
{
return _setmode(_fileno(fp), mod == 'b' ? _O_BINARY : _O_TEXT);
}
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport)
void **
# if defined(__BORLANDC__)
/*
* __stdcall appears to be the only way to get the name
* decoration right with Borland C. Otherwise it works
* purely incidentally, as we pass no parameters.
*/
__stdcall
# else
__cdecl
# endif
#pragma warning(push, 2)
OPENSSL_Applink(void)
{
static int once = 1;
static void *OPENSSL_ApplinkTable[APPLINK_MAX + 1] =
{ (void *)APPLINK_MAX };
if (once) {
OPENSSL_ApplinkTable[APPLINK_STDIN] = app_stdin;
OPENSSL_ApplinkTable[APPLINK_STDOUT] = app_stdout;
OPENSSL_ApplinkTable[APPLINK_STDERR] = app_stderr;
OPENSSL_ApplinkTable[APPLINK_FPRINTF] = fprintf;
OPENSSL_ApplinkTable[APPLINK_FGETS] = fgets;
OPENSSL_ApplinkTable[APPLINK_FREAD] = fread;
OPENSSL_ApplinkTable[APPLINK_FWRITE] = fwrite;
OPENSSL_ApplinkTable[APPLINK_FSETMOD] = app_fsetmod;
OPENSSL_ApplinkTable[APPLINK_FEOF] = app_feof;
OPENSSL_ApplinkTable[APPLINK_FCLOSE] = fclose;
OPENSSL_ApplinkTable[APPLINK_FOPEN] = fopen;
OPENSSL_ApplinkTable[APPLINK_FSEEK] = fseek;
OPENSSL_ApplinkTable[APPLINK_FTELL] = ftell;
OPENSSL_ApplinkTable[APPLINK_FFLUSH] = fflush;
OPENSSL_ApplinkTable[APPLINK_FERROR] = app_ferror;
OPENSSL_ApplinkTable[APPLINK_CLEARERR] = app_clearerr;
OPENSSL_ApplinkTable[APPLINK_FILENO] = app_fileno;
OPENSSL_ApplinkTable[APPLINK_OPEN] = _open;
OPENSSL_ApplinkTable[APPLINK_READ] = _read;
OPENSSL_ApplinkTable[APPLINK_WRITE] = _write;
OPENSSL_ApplinkTable[APPLINK_LSEEK] = _lseek;
OPENSSL_ApplinkTable[APPLINK_CLOSE] = _close;
once = 0;
}
return OPENSSL_ApplinkTable;
}
#pragma warning(pop)
#ifdef __cplusplus
}
#endif
#endif
osslsigncode-2.8/appx.c 0000664 0000000 0000000 00000276142 14571175157 0015224 0 ustar 00root root 0000000 0000000 /*
* APPX file support library
* https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
*
* Copyright (C) Maciej Panek
* Copyright (C) 2023 Micha┼В Trojnara
* Author: Ma┼Вgorzata Olsz├│wka
*
* APPX files do not support nesting (multiple signature)
*/
#define _FILE_OFFSET_BITS 64
#include "osslsigncode.h"
#include "helpers.h"
#include
#include
#ifndef PRIX64
#if defined(_MSC_VER)
#define PRIX64 "I64X"
#else /* _MSC_VER */
#if ULONG_MAX == 0xFFFFFFFFFFFFFFFF
#define PRIX64 "lX"
#else /* ULONG_MAX == 0xFFFFFFFFFFFFFFFF */
#define PRIX64 "llX"
#endif /* ULONG_MAX == 0xFFFFFFFFFFFFFFFF */
#endif /* _MSC_VER */
#endif /* PRIX64 */
#if defined(_MSC_VER)
#define fseeko _fseeki64
#define ftello _ftelli64
#endif /* _MSC_VER */
#define EOCDR_SIZE 22
#define ZIP64_EOCD_LOCATOR_SIZE 20
#define ZIP64_HEADER 0x01
#define COMPRESSION_NONE 0
#define COMPRESSION_DEFLATE 8
#define DATA_DESCRIPTOR_BIT (1 << 3)
static const char PKZIP_LH_SIGNATURE[4] = { 'P', 'K', 3, 4 };
static const char PKZIP_CD_SIGNATURE[4] = { 'P', 'K', 1, 2 };
static const char PKZIP_EOCDR_SIGNATURE[4] = { 'P', 'K', 5, 6 };
static const char PKZIP_DATA_DESCRIPTOR_SIGNATURE[4] = { 'P', 'K', 7, 8 };
static const char PKZIP64_EOCD_LOCATOR_SIGNATURE[4] = { 'P', 'K', 6, 7 };
static const char PKZIP64_EOCDR_SIGNATURE[4] = { 'P', 'K', 6, 6 };
static const char *APP_SIGNATURE_FILENAME = "AppxSignature.p7x";
static const char *CONTENT_TYPES_FILENAME = "[Content_Types].xml";
static const char *BLOCK_MAP_FILENAME = "AppxBlockMap.xml";
static const char *APPXBUNDLE_MANIFEST_FILENAME = "AppxMetadata/AppxBundleManifest.xml";
static const char *CODE_INTEGRITY_FILENAME = "AppxMetadata/CodeIntegrity.cat";
static const char *SIGNATURE_CONTENT_TYPES_ENTRY = "";
static const char *SIGNATURE_CONTENT_TYPES_CLOSING_TAG = "";
static const u_char APPX_UUID[] = { 0x4B, 0xDF, 0xC5, 0x0A, 0x07, 0xCE, 0xE2, 0x4D, 0xB7, 0x6E, 0x23, 0xC8, 0x39, 0xA0, 0x9F, 0xD1 };
static const u_char APPXBUNDLE_UUID[] = { 0xB3, 0x58, 0x5F, 0x0F, 0xDE, 0xAA, 0x9A, 0x4B, 0xA4, 0x34, 0x95, 0x74, 0x2D, 0x92, 0xEC, 0xEB };
static const char PKCX_SIGNATURE[4] = { 'P', 'K', 'C', 'X' }; /* P7X format header */
static const char APPX_SIGNATURE[4] = { 'A', 'P', 'P', 'X' }; /* APPX header */
static const char AXPC_SIGNATURE[4] = { 'A', 'X', 'P', 'C' }; /* digest of zip file records */
static const char AXCD_SIGNATURE[4] = { 'A', 'X', 'C', 'D' }; /* digest zip file central directory */
static const char AXCT_SIGNATURE[4] = { 'A', 'X', 'C', 'T' }; /* digest of uncompressed [ContentTypes].xml */
static const char AXBM_SIGNATURE[4] = { 'A', 'X', 'B', 'M' }; /* digest of uncompressed AppxBlockMap.xml */
static const char AXCI_SIGNATURE[4] = { 'A', 'X', 'C', 'I' }; /* digest of uncompressed AppxMetadata/CodeIntegrity.cat (optional) */
static const char *HASH_METHOD_TAG = "HashMethod";
static const char *HASH_METHOD_SHA256 = "http://www.w3.org/2001/04/xmlenc#sha256";
static const char *HASH_METHOD_SHA384 = "http://www.w3.org/2001/04/xmldsig-more#sha384";
static const char *HASH_METHOD_SHA512 = "http://www.w3.org/2001/04/xmlenc#sha512";
/*
* Overall .ZIP file format:
*
* [local file header 1]
* [encryption header 1]
* [file data 1]
* [data descriptor 1]
* .
* .
* .
* [local file header n]
* [encryption header n]
* [file data n]
* [data descriptor n]
* [archive decryption header]
* [archive extra data record]
* [central directory header 1]
* .
* .
* .
* [central directory header n]
* [zip64 end of central directory record]
* [zip64 end of central directory locator]
* [end of central directory record]
*/
/* Local file header */
typedef struct {
uint16_t version;
uint16_t flags;
uint16_t compression;
uint16_t modTime;
uint16_t modDate;
uint32_t crc32;
uint64_t compressedSize;
uint64_t uncompressedSize;
uint16_t fileNameLen;
uint16_t extraFieldLen;
char *fileName;
uint8_t *extraField;
int compressedSizeInZip64;
int uncompressedSizeInZip64;
} ZIP_LOCAL_HEADER;
/* Data descriptor */
typedef struct {
uint32_t crc32;
uint64_t compressedSize;
uint64_t uncompressedSize;
uint8_t *data;
} ZIP_OVERRIDE_DATA;
/* Central directory structure */
typedef struct zipCentralDirectoryEntry_struct {
uint16_t creatorVersion;
uint16_t viewerVersion;
uint16_t flags;
uint16_t compression;
uint16_t modTime;
uint16_t modDate;
uint32_t crc32;
uint64_t compressedSize;
uint64_t uncompressedSize;
uint16_t fileNameLen;
uint16_t extraFieldLen;
uint16_t fileCommentLen;
uint32_t diskNoStart;
uint16_t internalAttr;
uint32_t externalAttr;
uint64_t offsetOfLocalHeader;
char *fileName;
uint8_t *extraField;
char *fileComment;
int64_t fileOffset;
int64_t entryLen;
int compressedSizeInZip64;
int uncompressedSizeInZip64;
int offsetInZip64;
int diskNoInZip64;
ZIP_OVERRIDE_DATA *overrideData;
struct zipCentralDirectoryEntry_struct *next;
} ZIP_CENTRAL_DIRECTORY_ENTRY;
/* Zip64 end of central directory record */
typedef struct {
uint64_t eocdrSize;
uint16_t creatorVersion;
uint16_t viewerVersion;
uint32_t diskNumber;
uint32_t diskWithCentralDirectory;
uint64_t diskEntries;
uint64_t totalEntries;
uint64_t centralDirectorySize;
uint64_t centralDirectoryOffset;
uint64_t commentLen;
char *comment;
} ZIP64_EOCDR;
/* Zip64 end of central directory locator */
typedef struct {
uint32_t diskWithEOCD;
uint64_t eocdOffset;
uint32_t totalNumberOfDisks;
} ZIP64_EOCD_LOCATOR;
/* End of central directory record */
typedef struct {
uint16_t diskNumber;
uint16_t centralDirectoryDiskNumber;
uint16_t diskEntries;
uint16_t totalEntries;
uint32_t centralDirectorySize;
uint32_t centralDirectoryOffset;
uint16_t commentLen;
char *comment;
} ZIP_EOCDR;
typedef struct {
FILE *file;
ZIP_CENTRAL_DIRECTORY_ENTRY *centralDirectoryHead;
uint64_t centralDirectorySize;
uint64_t centralDirectoryOffset;
uint64_t centralDirectoryRecordCount;
uint64_t eocdrOffset;
int64_t eocdrLen;
int64_t fileSize;
int isZip64;
/* this will come handy to rewrite the eocdr */
ZIP_EOCDR eocdr;
ZIP64_EOCD_LOCATOR locator;
ZIP64_EOCDR eocdr64;
} ZIP_FILE;
typedef struct {
ASN1_INTEGER *a;
ASN1_OCTET_STRING *string;
ASN1_INTEGER *b;
ASN1_INTEGER *c;
ASN1_INTEGER *d;
ASN1_INTEGER *e;
ASN1_INTEGER *f;
} AppxSpcSipInfo;
DECLARE_ASN1_FUNCTIONS(AppxSpcSipInfo)
ASN1_SEQUENCE(AppxSpcSipInfo) = {
ASN1_SIMPLE(AppxSpcSipInfo, a, ASN1_INTEGER),
ASN1_SIMPLE(AppxSpcSipInfo, string, ASN1_OCTET_STRING),
ASN1_SIMPLE(AppxSpcSipInfo, b, ASN1_INTEGER),
ASN1_SIMPLE(AppxSpcSipInfo, c, ASN1_INTEGER),
ASN1_SIMPLE(AppxSpcSipInfo, d, ASN1_INTEGER),
ASN1_SIMPLE(AppxSpcSipInfo, e, ASN1_INTEGER),
ASN1_SIMPLE(AppxSpcSipInfo, f, ASN1_INTEGER),
} ASN1_SEQUENCE_END(AppxSpcSipInfo)
IMPLEMENT_ASN1_FUNCTIONS(AppxSpcSipInfo)
struct appx_ctx_st {
ZIP_FILE *zip;
u_char *calculatedBMHash;
u_char *calculatedCTHash;
u_char *calculatedCDHash;
u_char *calculatedDataHash;
u_char *calculatedCIHash;
u_char *existingBMHash;
u_char *existingCTHash;
u_char *existingCDHash;
u_char *existingDataHash;
u_char *existingCIHash;
int isBundle;
const EVP_MD *md;
int hashlen;
} appx_ctx_t;
/* FILE_FORMAT method prototypes */
static FILE_FORMAT_CTX *appx_ctx_new(GLOBAL_OPTIONS *options, BIO *hash, BIO *outdata);
static const EVP_MD *appx_md_get(FILE_FORMAT_CTX *ctx);
static ASN1_OBJECT *appx_spc_sip_info_get(u_char **p, int *plen, FILE_FORMAT_CTX *ctx);
static PKCS7 *appx_pkcs7_contents_get(FILE_FORMAT_CTX *ctx, BIO *hash, const EVP_MD *md);
static int appx_hash_length_get(FILE_FORMAT_CTX *ctx);
static int appx_verify_digests(FILE_FORMAT_CTX *ctx, PKCS7 *p7);
static PKCS7 *appx_pkcs7_extract(FILE_FORMAT_CTX *ctx);
static int appx_remove_pkcs7(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata);
static int appx_process_data(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata);
static PKCS7 *appx_pkcs7_signature_new(FILE_FORMAT_CTX *ctx, BIO *hash);
static int appx_append_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7);
static void appx_bio_free(BIO *hash, BIO *outdata);
static void appx_ctx_cleanup(FILE_FORMAT_CTX *ctx);
FILE_FORMAT file_format_appx = {
.ctx_new = appx_ctx_new,
.md_get = appx_md_get,
.data_blob_get = appx_spc_sip_info_get,
.pkcs7_contents_get = appx_pkcs7_contents_get,
.hash_length_get = appx_hash_length_get,
.verify_digests = appx_verify_digests,
.pkcs7_extract = appx_pkcs7_extract,
.remove_pkcs7 = appx_remove_pkcs7,
.process_data = appx_process_data,
.pkcs7_signature_new = appx_pkcs7_signature_new,
.append_pkcs7 = appx_append_pkcs7,
.bio_free = appx_bio_free,
.ctx_cleanup = appx_ctx_cleanup,
};
/* Prototypes */
static BIO *appx_calculate_hashes(FILE_FORMAT_CTX *ctx);
static BIO *appx_hash_blob_get(FILE_FORMAT_CTX *ctx);
static uint8_t *appx_calc_zip_central_directory_hash(ZIP_FILE *zip, const EVP_MD *md, uint64_t cdOffset);
static int appx_write_central_directory(BIO *bio, ZIP_FILE *zip, int removeSignature, uint64_t cdOffset);
static uint8_t *appx_calc_zip_data_hash(uint64_t *cdOffset, ZIP_FILE *zip, const EVP_MD *md);
static int appx_extract_hashes(FILE_FORMAT_CTX *ctx, SpcIndirectDataContent *content);
static int appx_compare_hashes(FILE_FORMAT_CTX *ctx);
static int appx_remove_ct_signature_entry(ZIP_FILE *zip, ZIP_CENTRAL_DIRECTORY_ENTRY *entry);
static int appx_append_ct_signature_entry(ZIP_FILE *zip, ZIP_CENTRAL_DIRECTORY_ENTRY *entry);
static const EVP_MD *appx_get_md(ZIP_FILE *zip);
static ZIP_CENTRAL_DIRECTORY_ENTRY *zipGetCDEntryByName(ZIP_FILE *zip, const char *name);
static void zipWriteCentralDirectoryEntry(BIO *bio, uint64_t *sizeOnDisk, ZIP_CENTRAL_DIRECTORY_ENTRY *entry, uint64_t offsetDiff);
static int zipAppendSignatureFile(BIO *bio, ZIP_FILE *zip, uint8_t *data, uint64_t dataSize);
static int zipOverrideFileData(ZIP_CENTRAL_DIRECTORY_ENTRY *entry, uint8_t *data, uint64_t dataSize);
static int zipRewriteData(ZIP_FILE *zip, ZIP_CENTRAL_DIRECTORY_ENTRY *entry, BIO *bio, uint64_t *sizeOnDisk);
static void zipWriteLocalHeader(BIO *bio, uint64_t *sizeonDisk, ZIP_LOCAL_HEADER *heade);
static int zipEntryExist(ZIP_FILE *zip, const char *name);
static u_char *zipCalcDigest(ZIP_FILE *zip, const char *fileName, const EVP_MD *md);
static size_t zipReadFileDataByName(uint8_t **pData, ZIP_FILE *zip, const char *name);
static size_t zipReadFileData(ZIP_FILE *zip, uint8_t **pData, ZIP_CENTRAL_DIRECTORY_ENTRY *entry);
static int zipReadLocalHeader(ZIP_LOCAL_HEADER *header, ZIP_FILE *zip, uint64_t compressedSize);
static int zipInflate(uint8_t *dest, uint64_t *destLen, uint8_t *source, uLong *sourceLen);
static int zipDeflate(uint8_t *dest, uint64_t *destLen, uint8_t *source, uLong sourceLen);
static ZIP_FILE *openZip(const char *filename);
static void freeZip(ZIP_FILE *zip);
static void zipPrintCentralDirectory(ZIP_FILE *zip);
static int zipReadCentralDirectory(ZIP_FILE *zip, FILE *file);
static ZIP_CENTRAL_DIRECTORY_ENTRY *zipReadNextCentralDirectoryEntry(FILE *file);
static void freeZipCentralDirectoryEntry(ZIP_CENTRAL_DIRECTORY_ENTRY *entry);
static int readZipEOCDR(ZIP_EOCDR *eocdr, FILE *file);
static int readZip64EOCDLocator(ZIP64_EOCD_LOCATOR *locator, FILE *file);
static int readZip64EOCDR(ZIP64_EOCDR *eocdr, FILE *file, uint64_t offset);
static int get_current_position(BIO *bio, uint64_t *offset);
static uint64_t fileGetU64(FILE *file);
static uint32_t fileGetU32(FILE *file);
static uint16_t fileGetU16(FILE *file);
static uint64_t bufferGetU64(uint8_t *buffer, uint64_t *pos);
static uint32_t bufferGetU32(uint8_t *buffer, uint64_t *pos);
static uint16_t bufferGetU16(uint8_t *buffer, uint64_t *pos);
static void bioAddU64(BIO *bio, uint64_t v);
static void bioAddU32(BIO *bio, uint32_t v);
static void bioAddU16(BIO *bio, uint16_t v);
/*
* FILE_FORMAT method definitions
*/
/*
* Allocate and return a PE file format context.
* [in, out] options: structure holds the input data
* [out] hash: message digest BIO
* [in] outdata: outdata file BIO
* [returns] pointer to PE file format context
*/
static FILE_FORMAT_CTX *appx_ctx_new(GLOBAL_OPTIONS *options, BIO *hash, BIO *outdata)
{
FILE_FORMAT_CTX *ctx;
const EVP_MD *md;
ZIP_FILE *zip = openZip(options->infile);
/* squash unused parameter warnings */
(void)hash;
(void)outdata;
if (!zip) {
return NULL; /* FAILED */
}
if (options->verbose) {
zipPrintCentralDirectory(zip);
}
md = appx_get_md(zip);
if (!md) {
freeZip(zip);
return NULL; /* FAILED */
}
ctx = OPENSSL_malloc(sizeof(FILE_FORMAT_CTX));
ctx->appx_ctx = OPENSSL_zalloc(sizeof(appx_ctx_t));
ctx->appx_ctx->zip = zip;
ctx->format = &file_format_appx;
ctx->options = options;
ctx->appx_ctx->md = md;
if (zipGetCDEntryByName(zip, APPXBUNDLE_MANIFEST_FILENAME)) {
ctx->appx_ctx->isBundle = 1;
}
if (options->cmd == CMD_SIGN || options->cmd==CMD_ATTACH
|| options->cmd==CMD_ADD || options->cmd == CMD_EXTRACT_DATA) {
printf("Warning: Ignore -h option, use the hash algorithm specified in AppxBlockMap.xml\n");
}
if (options->pagehash == 1)
printf("Warning: -ph option is only valid for PE files\n");
if (options->jp >= 0)
printf("Warning: -jp option is only valid for CAB files\n");
if (options->add_msi_dse == 1)
printf("Warning: -add-msi-dse option is only valid for MSI files\n");
return ctx;
}
/*
* Return a hash algorithm specified in the AppxBlockMap.xml file.
* [in] ctx: structure holds input and output data
* [returns] hash algorithm
*/
static const EVP_MD *appx_md_get(FILE_FORMAT_CTX *ctx)
{
return ctx->appx_ctx->md;
}
/*
* Allocate and return SpcSipInfo object.
* [out] p: SpcSipInfo data
* [out] plen: SpcSipInfo data length
* [in] ctx: structure holds input and output data
* [returns] pointer to ASN1_OBJECT structure corresponding to SPC_SIPINFO_OBJID
*/
static ASN1_OBJECT *appx_spc_sip_info_get(u_char **p, int *plen, FILE_FORMAT_CTX *ctx)
{
ASN1_OBJECT *dtype;
AppxSpcSipInfo *si = AppxSpcSipInfo_new();
ASN1_INTEGER_set(si->a, 0x01010000);
ASN1_INTEGER_set(si->b, 0);
ASN1_INTEGER_set(si->c, 0);
ASN1_INTEGER_set(si->d, 0);
ASN1_INTEGER_set(si->e, 0);
ASN1_INTEGER_set(si->f, 0);
if (ctx->appx_ctx->isBundle) {
printf("Signing as a bundle\n");
ASN1_OCTET_STRING_set(si->string, APPXBUNDLE_UUID, sizeof(APPXBUNDLE_UUID));
} else {
printf("Signing as a package\n");
ASN1_OCTET_STRING_set(si->string, APPX_UUID, sizeof(APPX_UUID));
}
*plen = i2d_AppxSpcSipInfo(si, NULL);
*p = OPENSSL_malloc((size_t)*plen);
i2d_AppxSpcSipInfo(si, p);
*p -= *plen;
dtype = OBJ_txt2obj(SPC_SIPINFO_OBJID, 1);
AppxSpcSipInfo_free(si);
return dtype; /* OK */
}
/*
* Allocate and return a data content to be signed.
* [in] ctx: structure holds input and output data
* [in] hash: message digest BIO
* [in] md: message digest algorithm
* [returns] data content
*/
static PKCS7 *appx_pkcs7_contents_get(FILE_FORMAT_CTX *ctx, BIO *hash, const EVP_MD *md)
{
ASN1_OCTET_STRING *content;
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
BIO *bhash;
/* squash unused parameter warnings */
(void)md;
(void)hash;
/* Create and append a new signature content types entry */
entry = zipGetCDEntryByName(ctx->appx_ctx->zip, CONTENT_TYPES_FILENAME);
if (!entry) {
printf("Not a valid .appx file: content types file missing\n");
return NULL; /* FAILED */
}
if (!appx_append_ct_signature_entry(ctx->appx_ctx->zip, entry)) {
return NULL; /* FAILED */
}
bhash = appx_calculate_hashes(ctx);
if (!bhash) {
return NULL; /* FAILED */
}
content = spc_indirect_data_content_get(bhash, ctx);
BIO_free_all(bhash);
return pkcs7_set_content(content);
}
/*
* Get concatenated hashes length.
* [in] ctx: structure holds input and output data
* [returns] the length of concatenated hashes
*/
static int appx_hash_length_get(FILE_FORMAT_CTX *ctx)
{
return ctx->appx_ctx->hashlen;
}
/*
* Calculate message digest and compare to value retrieved from PKCS#7 signedData.
* [in] ctx: structure holds input and output data
* [in] p7: PKCS#7 signature
* [returns] 0 on error or 1 on success
*/
static int appx_verify_digests(FILE_FORMAT_CTX *ctx, PKCS7 *p7)
{
if (is_content_type(p7, SPC_INDIRECT_DATA_OBJID)) {
ASN1_STRING *content_val = p7->d.sign->contents->d.other->value.sequence;
const u_char *p = content_val->data;
SpcIndirectDataContent *idc = d2i_SpcIndirectDataContent(NULL, &p, content_val->length);
if (idc) {
BIO *hashes;
if (!appx_extract_hashes(ctx, idc)) {
printf("Failed to extract hashes from the signature\n");
SpcIndirectDataContent_free(idc);
return 0; /* FAILED */
}
hashes = appx_calculate_hashes(ctx);
if (!hashes) {
SpcIndirectDataContent_free(idc);
return 0; /* FAILED */
}
BIO_free_all(hashes);
if (!appx_compare_hashes(ctx)) {
printf("Signature hash verification failed\n");
SpcIndirectDataContent_free(idc);
return 0; /* FAILED */
}
SpcIndirectDataContent_free(idc);
}
}
return 1; /* OK */
}
/*
* Extract existing signature in DER format.
* [in] ctx: structure holds input and output data
* [returns] pointer to PKCS#7 structure
*/
static PKCS7 *appx_pkcs7_extract(FILE_FORMAT_CTX *ctx)
{
PKCS7 *p7;
uint8_t *data = NULL;
const u_char *blob;
size_t dataSize;
/* Check if the signature exists */
if (!zipEntryExist(ctx->appx_ctx->zip, APP_SIGNATURE_FILENAME)) {
printf("%s does not exist\n", APP_SIGNATURE_FILENAME);
return NULL; /* FAILED */
}
dataSize = zipReadFileDataByName(&data, ctx->appx_ctx->zip, APP_SIGNATURE_FILENAME);
if (dataSize <= 0) {
return NULL; /* FAILED */
}
/* P7X format is just 0x504B4358 (PKCX) followed by PKCS#7 data in the DER format */
if (memcmp(data, PKCX_SIGNATURE, 4)) {
printf("Invalid PKCX header\n");
OPENSSL_free(data);
return NULL; /* FAILED */
}
blob = (u_char *)data + 4;
p7 = d2i_PKCS7(NULL, &blob, (int)dataSize - 4);
OPENSSL_free(data);
return p7;
}
/*
* Remove existing signature.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO
* [out] outdata: outdata file BIO
* [returns] 1 on error or 0 on success
*/
static int appx_remove_pkcs7(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata)
{
uint8_t *data = NULL;
size_t dataSize;
uint64_t cdOffset, noEntries = 0;
ZIP_FILE *zip = ctx->appx_ctx->zip;
ZIP_CENTRAL_DIRECTORY_ENTRY *entry = zipGetCDEntryByName(zip, CONTENT_TYPES_FILENAME);
/* squash the unused parameter warning */
(void)hash;
if (!entry) {
printf("Not a valid .appx file: content types file missing\n");
return 1; /* FAILED */
}
/* read signature data */
dataSize = zipReadFileDataByName(&data, ctx->appx_ctx->zip, APP_SIGNATURE_FILENAME);
if (dataSize <= 0) {
return 1; /* FAILED, no signature */
}
OPENSSL_free(data);
if (!appx_remove_ct_signature_entry(zip, entry)) {
printf("Failed to remove signature entry\n");
return 1; /* FAILED */
}
for (entry = zip->centralDirectoryHead; entry != NULL; entry = entry->next) {
if (noEntries == zip->centralDirectoryRecordCount) {
printf("Warning: Corrupted central directory structure\n");
return 1; /* FAILED */
}
noEntries++;
if (!entry->fileName || (entry->fileNameLen == 0)) {
printf("Warning: Corrupted file name\n");
return 1; /* FAILED */
}
if (strcmp(entry->fileName, APP_SIGNATURE_FILENAME)) {
uint64_t dummy;
if (!zipRewriteData(zip, entry, outdata, &dummy)) {
return 1; /* FAILED */
}
}
}
if (!get_current_position(outdata, &cdOffset)) {
printf("Unable to get offset\n");
return 1; /* FAILED */
}
if (!appx_write_central_directory(outdata, zip, 1, cdOffset)) {
printf("Unable to write central directory\n");
return 1; /* FAILED */
}
return 0; /* OK */
}
/*
* Modify specific type data.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO (unused)
* [out] outdata: outdata file BIO (unused)
* [returns] 1 on error or 0 on success
*/
static int appx_process_data(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
/* squash unused parameter warnings */
(void)outdata;
(void)hash;
/* Create and append a new signature content types entry */
entry = zipGetCDEntryByName(ctx->appx_ctx->zip, CONTENT_TYPES_FILENAME);
if (!entry) {
printf("Not a valid .appx file: content types file missing\n");
return 1; /* FAILED */
}
if (!appx_append_ct_signature_entry(ctx->appx_ctx->zip, entry)) {
return 1; /* FAILED */
}
return 0; /* OK */
}
/*
* Create a new PKCS#7 signature.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO (unused)
* [returns] pointer to PKCS#7 structure
*/
static PKCS7 *appx_pkcs7_signature_new(FILE_FORMAT_CTX *ctx, BIO *hash)
{
ASN1_OCTET_STRING *content;
PKCS7 *p7 = NULL;
BIO *hashes;
/* squash unused parameter warnings */
(void)hash;
/* Create hash blob from concatenated APPX hashes */
hashes = appx_calculate_hashes(ctx);
if (!hashes) {
return NULL; /* FAILED */
}
p7 = pkcs7_create(ctx);
if (!p7) {
printf("Creating a new signature failed\n");
BIO_free_all(hashes);
return NULL; /* FAILED */
}
if (!add_indirect_data_object(p7)) {
printf("Adding SPC_INDIRECT_DATA_OBJID failed\n");
PKCS7_free(p7);
BIO_free_all(hashes);
return NULL; /* FAILED */
}
content = spc_indirect_data_content_get(hashes, ctx);
BIO_free_all(hashes);
if (!content) {
printf("Failed to get spcIndirectDataContent\n");
PKCS7_free(p7);
return NULL; /* FAILED */
}
if (!sign_spc_indirect_data_content(p7, content)) {
printf("Failed to set signed content\n");
PKCS7_free(p7);
ASN1_OCTET_STRING_free(content);
return NULL; /* FAILED */
}
ASN1_OCTET_STRING_free(content);
return p7; /* OK */
}
/*
* Append signature to the outfile.
* [in, out] ctx: structure holds input and output data
* [out] outdata: outdata file BIO
* [in] p7: PKCS#7 signature
* [returns] 1 on error or 0 on success
*/
static int appx_append_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7)
{
ZIP_FILE *zip = ctx->appx_ctx->zip;
ZIP_CENTRAL_DIRECTORY_ENTRY *prev = NULL;
ZIP_CENTRAL_DIRECTORY_ENTRY *last = NULL;
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
u_char *blob, *der = NULL;
int len;
uint64_t cdOffset, noEntries = 0;
for (entry = zip->centralDirectoryHead; entry != NULL;) {
if (noEntries >= zip->centralDirectoryRecordCount) {
printf("Warning: Corrupted central directory structure\n");
return 1; /* FAILED */
}
noEntries++;
last = entry;
if (!entry->fileName || (entry->fileNameLen == 0)) {
printf("Warning: Corrupted file name\n");
return 1; /* FAILED */
}
if (strcmp(entry->fileName, APP_SIGNATURE_FILENAME)) {
uint64_t dummy = 0;
if (!zipRewriteData(zip, entry, outdata, &dummy)) {
return 1; /* FAILED */
}
prev = entry;
entry = entry->next;
} else {
/* remove the entry
* actually this code is pretty naive - if you remove the entry that was not at the end
* everything will go south - the offsets in the CD will not match the local header offsets.
* that can be fixed here or left as is - signtool and this tool always appends the signature file at the end.
* Might be a problem when someone decides to unpack & repack the .appx zip file */
ZIP_CENTRAL_DIRECTORY_ENTRY *current = entry;
entry = entry->next;
if (prev) {
prev->next = entry;
}
freeZipCentralDirectoryEntry(current);
}
}
if (!last) {
/* not really possible unless an empty zip file, but who knows */
return 1; /* FAILED */
}
/* create the signature entry */
if (((len = i2d_PKCS7(p7, NULL)) <= 0) ||
(der = OPENSSL_malloc((size_t)len)) == NULL)
return 1; /* FAILED */
i2d_PKCS7(p7, &der);
der -= len;
blob = OPENSSL_malloc((size_t)(len + 4));
memcpy(blob, PKCX_SIGNATURE, 4);
memcpy(blob + 4, der, (size_t)len);
len += 4;
if (!zipAppendSignatureFile(outdata, zip, blob, (uint64_t)len)) {
OPENSSL_free(blob);
printf("Failed to append zip file\n");
return 1; /* FAILED */
}
OPENSSL_free(der);
OPENSSL_free(blob);
if (!get_current_position(outdata, &cdOffset)) {
printf("Unable to get offset\n");
return 1; /* FAILED */
}
if (!appx_write_central_directory(outdata, zip, 0, cdOffset)) {
printf("Unable to write central directory\n");
return 1; /* FAILED */
}
return 0; /* OK */
}
/*
* Free up an entire message digest BIO chain.
* [out] hash: message digest BIO
* [out] outdata: outdata file BIO
* [returns] none
*/
static void appx_bio_free(BIO *hash, BIO *outdata)
{
BIO_free_all(outdata);
BIO_free_all(hash);
}
/*
* Deallocate a FILE_FORMAT_CTX structure and PE format specific structure.
* [out] ctx: structure holds input and output data
* [out] hash: message digest BIO
* [in] outdata: outdata file BIO
* [returns] none
*/
static void appx_ctx_cleanup(FILE_FORMAT_CTX *ctx)
{
freeZip(ctx->appx_ctx->zip);
OPENSSL_free(ctx->appx_ctx->calculatedBMHash);
OPENSSL_free(ctx->appx_ctx->calculatedCTHash);
OPENSSL_free(ctx->appx_ctx->calculatedCDHash);
OPENSSL_free(ctx->appx_ctx->calculatedDataHash);
OPENSSL_free(ctx->appx_ctx->calculatedCIHash);
OPENSSL_free(ctx->appx_ctx->existingBMHash);
OPENSSL_free(ctx->appx_ctx->existingCTHash);
OPENSSL_free(ctx->appx_ctx->existingCDHash);
OPENSSL_free(ctx->appx_ctx->existingDataHash);
OPENSSL_free(ctx->appx_ctx->existingCIHash);
OPENSSL_free(ctx->appx_ctx);
OPENSSL_free(ctx);
}
/*
* APPX helper functions
*/
/*
* Calculate ZIP hashes.
* [in, out] ctx: structure holds input and output data
* [returns] pointer to BIO with calculated APPX hashes
*/
static BIO *appx_calculate_hashes(FILE_FORMAT_CTX *ctx)
{
uint64_t cdOffset = 0;
ctx->appx_ctx->calculatedBMHash = zipCalcDigest(ctx->appx_ctx->zip, BLOCK_MAP_FILENAME, ctx->appx_ctx->md);
ctx->appx_ctx->calculatedCTHash = zipCalcDigest(ctx->appx_ctx->zip, CONTENT_TYPES_FILENAME, ctx->appx_ctx->md);
ctx->appx_ctx->calculatedDataHash = appx_calc_zip_data_hash(&cdOffset, ctx->appx_ctx->zip, ctx->appx_ctx->md);
ctx->appx_ctx->calculatedCDHash = appx_calc_zip_central_directory_hash(ctx->appx_ctx->zip, ctx->appx_ctx->md, cdOffset);
ctx->appx_ctx->calculatedCIHash = zipCalcDigest(ctx->appx_ctx->zip, CODE_INTEGRITY_FILENAME, ctx->appx_ctx->md);
if (!ctx->appx_ctx->calculatedBMHash || !ctx->appx_ctx->calculatedCTHash
|| !ctx->appx_ctx->calculatedCDHash || !ctx->appx_ctx->calculatedDataHash) {
printf("One or more hashes calculation failed\n");
return NULL; /* FAILED */
}
if (zipEntryExist(ctx->appx_ctx->zip, CODE_INTEGRITY_FILENAME) && !ctx->appx_ctx->calculatedCIHash) {
printf("Code integrity file exists, but CI hash calculation failed\n");
return NULL; /* FAILED */
}
return appx_hash_blob_get(ctx);
}
/*
* Create hash blob from concatenated APPX hashes.
* [in] ctx: structure holds input and output data
* [returns] pointer to BIO with calculated APPX hashes
*/
static BIO *appx_hash_blob_get(FILE_FORMAT_CTX *ctx)
{
int mdlen = EVP_MD_size(ctx->appx_ctx->md);
int dataSize = ctx->appx_ctx->calculatedCIHash ? 4 + 5 * (mdlen + 4) : 4 + 4 * (mdlen + 4);
u_char *data = OPENSSL_malloc((size_t)dataSize);
int pos = 0;
BIO *hashes = BIO_new(BIO_s_mem());
memcpy(data + pos, APPX_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, AXPC_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, ctx->appx_ctx->calculatedDataHash, (size_t)mdlen);
pos += mdlen;
memcpy(data + pos, AXCD_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, ctx->appx_ctx->calculatedCDHash, (size_t)mdlen);
pos += mdlen;
memcpy(data + pos, AXCT_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, ctx->appx_ctx->calculatedCTHash, (size_t)mdlen);
pos += mdlen;
memcpy(data + pos, AXBM_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, ctx->appx_ctx->calculatedBMHash, (size_t)mdlen);
pos += mdlen;
if (ctx->appx_ctx->calculatedCIHash) {
memcpy(data + pos, AXCI_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, ctx->appx_ctx->calculatedCIHash, (size_t)mdlen);
pos += mdlen;
}
if (ctx->options->verbose) {
print_hash("Hash of file: ", "\n", data, pos);
}
ctx->appx_ctx->hashlen = BIO_write(hashes, data, pos);
OPENSSL_free(data);
return hashes;
}
/*
* Calculate ZIP central directory hash.
* [in] zip: structure holds specific ZIP data
* [in] md: message digest algorithm type
* [in] cdOffset: central directory offset
* [returns] hash
*/
static uint8_t *appx_calc_zip_central_directory_hash(ZIP_FILE *zip, const EVP_MD *md, uint64_t cdOffset)
{
u_char *mdbuf = NULL;
BIO *bhash = BIO_new(BIO_f_md());
if (!BIO_set_md(bhash, md)) {
printf("Unable to set the message digest of BIO\n");
BIO_free_all(bhash);
return NULL; /* FAILED */
}
BIO_push(bhash, BIO_new(BIO_s_null()));
if (!appx_write_central_directory(bhash, zip, 1, cdOffset)) {
printf("Unable to write central directory\n");
BIO_free_all(bhash);
return NULL; /* FAILED */
}
mdbuf = OPENSSL_malloc((size_t)EVP_MD_size(md));
BIO_gets(bhash, (char*)mdbuf, EVP_MD_size(md));
BIO_free_all(bhash);
return mdbuf;
}
/*
* Write central directory structure.
* [out] bio: outdata file BIO
* [in] zip: structure holds specific ZIP data
* [in] removeSignature: remove signature switch
* [in] cdOffset: central directory offset
* [returns] 0 on error or 1 on success
*/
static int appx_write_central_directory(BIO *bio, ZIP_FILE *zip, int removeSignature, uint64_t cdOffset)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
uint64_t offsetDiff = 0, cdSize = 0;
uint16_t noEntries = 0;
for (entry = zip->centralDirectoryHead; entry != NULL; entry = entry->next) {
/* the signature file is considered non existent for hashing purposes */
uint64_t sizeOnDisk = 0;
if (noEntries > zip->centralDirectoryRecordCount) {
printf("Warning: Corrupted central directory structure\n");
return 0; /* FAILED */
}
if (!entry->fileName || (entry->fileNameLen == 0)) {
printf("Warning: Corrupted file name\n");
return 0; /* FAILED */
}
if (removeSignature && !strcmp(entry->fileName, APP_SIGNATURE_FILENAME)) {
continue;
}
/* APP_SIGNATURE is nt 'tainted' by offset shift after replacing the contents of [content_types] */
zipWriteCentralDirectoryEntry(bio, &sizeOnDisk, entry, strcmp(entry->fileName, APP_SIGNATURE_FILENAME) ? offsetDiff : 0);
cdSize += sizeOnDisk;
if (entry->overrideData) {
offsetDiff += entry->overrideData->compressedSize - entry->compressedSize;
}
noEntries++;
}
if (zip->isZip64) {
/* eocdr */
BIO_write(bio, PKZIP64_EOCDR_SIGNATURE, 4);
bioAddU64(bio, zip->eocdr64.eocdrSize);
bioAddU16(bio, zip->eocdr64.creatorVersion);
bioAddU16(bio, zip->eocdr64.viewerVersion);
bioAddU32(bio, zip->eocdr64.diskNumber);
bioAddU32(bio, zip->eocdr64.diskWithCentralDirectory);
bioAddU64(bio, (uint64_t)noEntries);
bioAddU64(bio, (uint64_t)noEntries);
bioAddU64(bio, cdSize);
bioAddU64(bio, cdOffset);
if (zip->eocdr64.commentLen > 0) {
size_t check;
if (!BIO_write_ex(bio, zip->eocdr64.comment, zip->eocdr64.commentLen, &check)
|| check != zip->eocdr64.commentLen) {
return 0; /* FAILED */
}
}
/* eocdr locator */
BIO_write(bio, PKZIP64_EOCD_LOCATOR_SIGNATURE, 4);
bioAddU32(bio, zip->locator.diskWithEOCD);
bioAddU64(bio, cdOffset + cdSize);
bioAddU32(bio, zip->locator.totalNumberOfDisks);
}
BIO_write(bio, PKZIP_EOCDR_SIGNATURE, 4);
/* those need to be 0s even though packaging tool writes FFFFs here
* it will fail verification if not zeros */
bioAddU16(bio, 0);
bioAddU16(bio, 0);
if (zip->eocdr.diskEntries != UINT16_MAX) {
bioAddU16(bio, noEntries);
} else {
bioAddU16(bio, UINT16_MAX);
}
if (zip->eocdr.totalEntries != UINT16_MAX) {
bioAddU16(bio, noEntries);
} else {
bioAddU16(bio, UINT16_MAX);
}
if (zip->eocdr.centralDirectorySize != UINT32_MAX) {
bioAddU32(bio, (uint32_t)cdSize);
} else {
bioAddU32(bio, UINT32_MAX);
}
if (zip->eocdr.centralDirectoryOffset != UINT32_MAX) {
bioAddU32(bio, (uint32_t)cdOffset);
} else {
bioAddU32(bio, UINT32_MAX);
}
bioAddU16(bio, zip->eocdr.commentLen);
if (zip->eocdr.commentLen > 0) {
BIO_write(bio, zip->eocdr.comment, zip->eocdr.commentLen);
}
return 1; /* OK */
}
/*
* Calculate ZIP data hash.
* [out] cdOffset: central directory offset
* [in] zip: structure holds specific ZIP data
* [in] md: message digest algorithm type
* [returns] hash
*/
static uint8_t *appx_calc_zip_data_hash(uint64_t *cdOffset, ZIP_FILE *zip, const EVP_MD *md)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
u_char *mdbuf = NULL;
BIO *bhash = BIO_new(BIO_f_md());
uint64_t noEntries = 0;
if (!BIO_set_md(bhash, md)) {
printf("Unable to set the message digest of BIO\n");
BIO_free_all(bhash);
return NULL; /* FAILED */
}
BIO_push(bhash, BIO_new(BIO_s_null()));
*cdOffset = 0;
for (entry = zip->centralDirectoryHead; entry != NULL; entry = entry->next) {
/* the signature file is considered not existent for hashing purposes */
uint64_t sizeOnDisk = 0;
if (noEntries >= zip->centralDirectoryRecordCount) {
printf("Warning: Corrupted central directory structure\n");
BIO_free_all(bhash);
return NULL; /* FAILED */
}
noEntries++;
if (!entry->fileName || (entry->fileNameLen == 0)) {
printf("Warning: Corrupted file name\n");
BIO_free_all(bhash);
return NULL; /* FAILED */
}
if (!strcmp(entry->fileName, APP_SIGNATURE_FILENAME)) {
continue;
}
if (!zipRewriteData(zip, entry, bhash, &sizeOnDisk)) {
printf("Rewrite data error\n");
BIO_free_all(bhash);
return NULL; /* FAILED */
}
*cdOffset += sizeOnDisk;
}
mdbuf = OPENSSL_malloc((size_t)EVP_MD_size(md));
BIO_gets(bhash, (char*)mdbuf, EVP_MD_size(md));
BIO_free_all(bhash);
return mdbuf;
}
/*
* Extract hashes from SpcIndirectDataContent.
* [in, out] ctx: structure holds input and output data
* [out] content: SpcIndirectDataContent
* [returns] 0 on error or 1 on success
*/
static int appx_extract_hashes(FILE_FORMAT_CTX *ctx, SpcIndirectDataContent *content)
{
#if 0
AppxSpcSipInfo *si = NULL;
const unsigned char *blob = content->data->value->value.sequence->data;
d2i_AppxSpcSipInfo(&si, &blob, content->data->value->value.sequence->length);
long a = ASN1_INTEGER_get(si->a);
long b = ASN1_INTEGER_get(si->b);
long c = ASN1_INTEGER_get(si->c);
long d = ASN1_INTEGER_get(si->d);
long e = ASN1_INTEGER_get(si->e);
long f = ASN1_INTEGER_get(si->f);
BIO *stdbio = BIO_new_fp(stdout, BIO_NOCLOSE);
printf("a: 0x%lX b: 0x%lX c: 0x%lX d: 0x%lX e: 0x%lX f: 0x%lX\n", a, b, c, d, e, f);
printf("string: ");
ASN1_STRING_print_ex(stdbio, si->string, ASN1_STRFLGS_RFC2253);
printf("\n\n");
AppxSpcSipInfo_free(si);
BIO_free_all(stdbio);
#endif
int length = content->messageDigest->digest->length;
uint8_t *data = content->messageDigest->digest->data;
int mdlen = EVP_MD_size(ctx->appx_ctx->md);
int pos = 4;
/* we are expecting at least 4 hashes + 4 byte header */
if (length < 4 * mdlen + 4) {
printf("Hash too short\n");
return 0; /* FAILED */
}
if (memcmp(data, APPX_SIGNATURE, 4)) {
printf("Hash signature does not match\n");
return 0; /* FAILED */
}
while (pos + mdlen + 4 <= length) {
if (!memcmp(data + pos, AXPC_SIGNATURE, 4)) {
ctx->appx_ctx->existingDataHash = OPENSSL_malloc((size_t)mdlen);
memcpy(ctx->appx_ctx->existingDataHash, data + pos + 4, (size_t)mdlen);
} else if (!memcmp(data + pos, AXCD_SIGNATURE, 4)) {
ctx->appx_ctx->existingCDHash = OPENSSL_malloc((size_t)mdlen);
memcpy(ctx->appx_ctx->existingCDHash, data + pos + 4, (size_t)mdlen);
} else if (!memcmp(data + pos, AXCT_SIGNATURE, 4)) {
ctx->appx_ctx->existingCTHash = OPENSSL_malloc((size_t)mdlen);
memcpy(ctx->appx_ctx->existingCTHash, data + pos + 4, (size_t)mdlen);
} else if (!memcmp(data + pos, AXBM_SIGNATURE, 4)) {
ctx->appx_ctx->existingBMHash = OPENSSL_malloc((size_t)mdlen);
memcpy(ctx->appx_ctx->existingBMHash, data + pos + 4, (size_t)mdlen);
} else if (!memcmp(data + pos, AXCI_SIGNATURE, 4)) {
ctx->appx_ctx->existingCIHash = OPENSSL_malloc((size_t)mdlen);
memcpy(ctx->appx_ctx->existingCIHash, data + pos + 4, (size_t)mdlen);
} else {
printf("Invalid hash signature\n");
return 0; /* FAILED */
}
pos += mdlen + 4;
}
if (!ctx->appx_ctx->existingDataHash) {
printf("File hash missing\n");
return 0; /* FAILED */
}
if (!ctx->appx_ctx->existingCDHash) {
printf("Central directory hash missing\n");
return 0; /* FAILED */
}
if (!ctx->appx_ctx->existingBMHash) {
printf("Block map hash missing\n");
return 0; /* FAILED */
}
if (!ctx->appx_ctx->existingCTHash) {
printf("Content types hash missing\n");
return 0; /* FAILED */
}
if (zipEntryExist(ctx->appx_ctx->zip, CODE_INTEGRITY_FILENAME) && !ctx->appx_ctx->existingCIHash) {
printf("Code integrity hash missing\n");
return 0; /* FAILED */
}
return 1; /* OK */
}
/*
* Compare extracted and calculated hashes.
* [in, out] ctx: structure holds input and output data
* [returns] 0 on error or 1 on success
*/
static int appx_compare_hashes(FILE_FORMAT_CTX *ctx)
{
int mdtype = EVP_MD_nid(ctx->appx_ctx->md);
if (ctx->appx_ctx->calculatedBMHash && ctx->appx_ctx->existingBMHash) {
printf("Checking Block Map hashes:\n");
if (!compare_digests(ctx->appx_ctx->existingBMHash, ctx->appx_ctx->calculatedBMHash, mdtype)) {
return 0; /* FAILED */
}
} else {
printf("Block map hash missing\n");
return 0; /* FAILED */
}
if (ctx->appx_ctx->calculatedCTHash && ctx->appx_ctx->existingCTHash) {
printf("Checking Content Types hashes:\n");
if (!compare_digests(ctx->appx_ctx->existingCTHash, ctx->appx_ctx->calculatedCTHash, mdtype)) {
return 0; /* FAILED */
}
} else {
printf("Content Types hash missing\n");
return 0; /* FAILED */
}
if (ctx->appx_ctx->calculatedDataHash && ctx->appx_ctx->existingDataHash) {
printf("Checking Data hashes:\n");
if (!compare_digests(ctx->appx_ctx->existingDataHash, ctx->appx_ctx->calculatedDataHash, mdtype)) {
return 0; /* FAILED */
}
} else {
printf("Central Directory hash missing\n");
return 0; /* FAILED */
}
if (ctx->appx_ctx->calculatedCDHash && ctx->appx_ctx->existingCDHash) {
printf("Checking Central Directory hashes:\n");
if (!compare_digests(ctx->appx_ctx->existingCDHash, ctx->appx_ctx->calculatedCDHash, mdtype)) {
return 0; /* FAILED */
}
} else {
printf("Central Directory hash missing\n");
return 0; /* FAILED */
}
if (ctx->appx_ctx->calculatedCIHash && ctx->appx_ctx->existingCIHash) {
printf("Checking Code Integrity hashes:\n");
if (!compare_digests(ctx->appx_ctx->existingCIHash, ctx->appx_ctx->calculatedCIHash, mdtype)) {
return 0; /* FAILED */
}
} else if (!ctx->appx_ctx->calculatedCIHash && !ctx->appx_ctx->existingCIHash) {
/* this is fine, CI file is optional -> if it is missing we expect both hashes to be non existent */
} else {
printf("Code Integrity hash missing\n");
return 0; /* FAILED */
}
return 1; /* OK */
}
/*
* Remove signature content types entry.
* [in] zip: structure holds specific ZIP data
* [in, out] entry: central directory structure
* [returns] 0 on error or 1 on success
*/
static int appx_remove_ct_signature_entry(ZIP_FILE *zip, ZIP_CENTRAL_DIRECTORY_ENTRY *entry)
{
uint8_t *data;
const char *cpos;
size_t dataSize, ipos, len;
int ret;
dataSize = zipReadFileData(zip, &data, entry);
if (dataSize <= 0) {
return 0; /* FAILED */
}
cpos = strstr((const char *)data, SIGNATURE_CONTENT_TYPES_ENTRY);
if (!cpos) {
printf("Did not find existing signature entry in %s\n", entry->fileName);
OPENSSL_free(data);
return 1; /* do not treat as en error */
}
/* *cpos > *data */
ipos = (size_t)(cpos - (char *)data);
len = strlen(SIGNATURE_CONTENT_TYPES_ENTRY);
memmove(data + ipos, data + ipos + len, dataSize - ipos - len);
dataSize -= len;
ret = zipOverrideFileData(entry, data, (uint64_t)dataSize);
OPENSSL_free(data);
return ret;
}
/*
* Append signature content types entry.
* [in] zip: structure holds specific ZIP data
* [in, out] entry: central directory structure
* [returns] 0 on error or 1 on success
*/
static int appx_append_ct_signature_entry(ZIP_FILE *zip, ZIP_CENTRAL_DIRECTORY_ENTRY *entry)
{
uint8_t *data, *newData;
const char *existingEntry, *cpos;
size_t dataSize, newSize, ipos, len;
int ret;
dataSize = zipReadFileData(zip, &data, entry);
if (dataSize <= 0) {
return 0; /* FAILED */
}
existingEntry = strstr((const char *)data, SIGNATURE_CONTENT_TYPES_ENTRY);
if (existingEntry) {
OPENSSL_free(data);
return 1; /* do not append it twice */
}
cpos = strstr((const char *)data, SIGNATURE_CONTENT_TYPES_CLOSING_TAG);
if (!cpos) {
printf("%s parsing error\n", entry->fileName);
OPENSSL_free(data);
return 0; /* FAILED */
}
ipos = (size_t)(cpos - (char *)data);
len = strlen(SIGNATURE_CONTENT_TYPES_ENTRY);
newSize = dataSize + len;
newData = OPENSSL_malloc(newSize);
memcpy(newData, data, ipos);
memcpy(newData + ipos, SIGNATURE_CONTENT_TYPES_ENTRY, len);
memcpy(newData + ipos + len, data + ipos, dataSize - ipos);
ret = zipOverrideFileData(entry, newData, (uint64_t)newSize);
OPENSSL_free(data);
OPENSSL_free(newData);
return ret;
}
/*
* Get a hash algorithm specified in the AppxBlockMap.xml file.
* [in] zip: structure holds specific ZIP data
* [returns] one of SHA256/SHA384/SHA512 digest algorithms
*/
static const EVP_MD *appx_get_md(ZIP_FILE *zip)
{
uint8_t *data = NULL;
char *start, *end, *pos;
char *valueStart = NULL, *valueEnd = NULL;
const EVP_MD *md = NULL;
size_t slen, dataSize;
dataSize = zipReadFileDataByName(&data, zip, BLOCK_MAP_FILENAME);
if (dataSize <= 0) {
printf("Could not read: %s\n", BLOCK_MAP_FILENAME);
return NULL; /* FAILED */
}
start = strstr((const char *)data, HASH_METHOD_TAG);
if (!start) {
printf("Parse error: tag: %s not found in %s\n", HASH_METHOD_TAG, BLOCK_MAP_FILENAME);
OPENSSL_free(data);
return NULL; /* FAILED */
}
start += strlen(HASH_METHOD_TAG);
if ((uint8_t *)start >= data + dataSize) {
printf("Parse error: data too short in %s\n", BLOCK_MAP_FILENAME);
OPENSSL_free(data);
return NULL; /* FAILED */
}
end = strstr((const char *)start, ">");
if (!end) {
printf("Parse error: end of tag not found in %s\n", BLOCK_MAP_FILENAME);
OPENSSL_free(data);
return NULL; /* FAILED */
}
for (pos = start; pos != end; pos++) {
if (*pos == '"') {
if (!valueStart) {
valueStart = pos + 1;
} else {
valueEnd = pos - 1;
}
}
}
if (!valueStart || !valueEnd || valueEnd <= valueStart) {
printf("Parse error: value parse error in %s\n", BLOCK_MAP_FILENAME);
OPENSSL_free(data);
return NULL; /* FAILED */
}
slen = (size_t)(valueEnd - valueStart + 1);
if (strlen(HASH_METHOD_SHA256) == slen && !memcmp(valueStart, HASH_METHOD_SHA256, slen)) {
printf("Hash method is SHA256\n");
md = EVP_sha256();
} else if (strlen(HASH_METHOD_SHA384) == slen && !memcmp(valueStart, HASH_METHOD_SHA384, slen)) {
printf("Hash method is SHA384\n");
md = EVP_sha384();
} else if (strlen(HASH_METHOD_SHA512) == slen && !memcmp(valueStart, HASH_METHOD_SHA512, slen)) {
printf("Hash method is SHA512\n");
md = EVP_sha512();
} else {
printf("Unsupported hash method\n");
OPENSSL_free(data);
return NULL; /* FAILED */
}
OPENSSL_free(data);
return md;
}
/*
* Get central directory structure entry.
* [in] zip: structure holds specific ZIP data
* [in] name: APPXBUNDLE_MANIFEST_FILENAME or CONTENT_TYPES_FILENAME
* [returns] pointer to central directory structure
*/
static ZIP_CENTRAL_DIRECTORY_ENTRY *zipGetCDEntryByName(ZIP_FILE *zip, const char *name)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
uint64_t noEntries = 0;
for (entry = zip->centralDirectoryHead; entry != NULL; entry = entry->next) {
if (noEntries >= zip->centralDirectoryRecordCount) {
printf("Warning: Corrupted central directory structure\n");
return NULL; /* FAILED */
}
noEntries++;
if (!entry->fileName || (entry->fileNameLen == 0)) {
printf("Warning: Corrupted file name\n");
return NULL; /* FAILED */
}
if (!strcmp(entry->fileName, name)) {
return entry;
}
}
return NULL; /* FAILED */
}
/*
* Write central directory entry.
* [out] bio: outdata file BIO
* [out] sizeOnDisk: size of central directory structure
* [in] entry: central directory structure
* [in] offsetDiff: central directory offset
* [returns] none
*/
static void zipWriteCentralDirectoryEntry(BIO *bio, uint64_t *sizeOnDisk, ZIP_CENTRAL_DIRECTORY_ENTRY *entry, uint64_t offsetDiff)
{
uint16_t zip64ChunkSize = 0;
BIO_write(bio, PKZIP_CD_SIGNATURE, 4);
bioAddU16(bio, entry->creatorVersion);
bioAddU16(bio, entry->viewerVersion);
bioAddU16(bio, entry->flags);
bioAddU16(bio, entry->compression);
bioAddU16(bio, entry->modTime);
bioAddU16(bio, entry->modDate);
bioAddU32(bio, entry->overrideData ? entry->overrideData->crc32 : entry->crc32);
bioAddU32(bio, entry->compressedSizeInZip64 ? UINT32_MAX : entry->overrideData ? (uint32_t)entry->overrideData->compressedSize : (uint32_t)entry->compressedSize);
bioAddU32(bio, entry->uncompressedSizeInZip64 ? UINT32_MAX : entry->overrideData ? (uint32_t)entry->overrideData->uncompressedSize : (uint32_t)entry->uncompressedSize);
bioAddU16(bio, entry->fileNameLen);
bioAddU16(bio, entry->extraFieldLen);
bioAddU16(bio, entry->fileCommentLen);
bioAddU16(bio, entry->diskNoInZip64 ? UINT16_MAX : (uint16_t)entry->diskNoStart);
bioAddU16(bio, entry->internalAttr);
bioAddU32(bio, entry->externalAttr);
bioAddU32(bio, entry->offsetInZip64 ? UINT32_MAX : (uint32_t)(entry->offsetOfLocalHeader + offsetDiff));
if (entry->fileNameLen > 0 && entry->fileName) {
BIO_write(bio, entry->fileName, entry->fileNameLen);
}
if (entry->uncompressedSizeInZip64) {
zip64ChunkSize += 8;
}
if (entry->compressedSizeInZip64) {
zip64ChunkSize += 8;
}
if (entry->offsetInZip64) {
zip64ChunkSize += 8;
}
if (entry->diskNoInZip64) {
zip64ChunkSize += 4;
}
if (zip64ChunkSize > 0) {
bioAddU16(bio, ZIP64_HEADER);
bioAddU16(bio, zip64ChunkSize);
if (entry->uncompressedSizeInZip64) {
bioAddU64(bio, entry->overrideData ? entry->overrideData->uncompressedSize : entry->uncompressedSize);
}
if (entry->compressedSizeInZip64) {
bioAddU64(bio, entry->overrideData ? entry->overrideData->compressedSize : entry->compressedSize);
}
if (entry->offsetInZip64) {
bioAddU64(bio, entry->offsetOfLocalHeader + offsetDiff);
}
if (entry->diskNoInZip64) {
bioAddU32(bio, entry->diskNoStart);
}
}
#if 0
if (entry->extraFieldLen > 0 && entry->extraField)
{
/* TODO, if override daata, need to rewrite the extra field */
BIO_write(bio, entry->extraField, entry->extraFieldLen);
}
#endif
if (entry->fileCommentLen > 0 && entry->fileComment) {
BIO_write(bio, entry->fileComment, entry->fileCommentLen);
}
*sizeOnDisk = (uint64_t)46 + entry->fileNameLen + entry->extraFieldLen + entry->fileCommentLen;
}
/*
* Append signature file blob to outdata bio.
* [out] bio: outdata file BIO
* [in] zip: structure holds specific ZIP data
* [in] data: pointer to signature file blob
* [in] dataSize: signature file blob length
* [returns] 0 on error or 1 on success
*/
static int zipAppendSignatureFile(BIO *bio, ZIP_FILE *zip, uint8_t *data, uint64_t dataSize)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
ZIP_LOCAL_HEADER header;
time_t tim;
struct tm *timeinfo;
uint64_t offset, crc, len, pos = 0, dummy = 0, written = 0;
uint64_t size = dataSize, sizeToWrite = dataSize;
uint8_t *dataToWrite = data;
int ret;
memset(&header, 0, sizeof(ZIP_LOCAL_HEADER));
dataToWrite = OPENSSL_malloc(dataSize);
ret = zipDeflate(dataToWrite, &size, data, dataSize);
if (ret != Z_OK) {
printf("Zip deflate failed: %d\n", ret);
OPENSSL_free(dataToWrite);
return 0; /* FAILED */
}
sizeToWrite = size;
time(&tim);
timeinfo = localtime(&tim);
header.version = 0x14;
header.flags = 0;
header.compression = COMPRESSION_DEFLATE;
header.modTime = (uint16_t)(timeinfo->tm_hour << 11 | \
timeinfo->tm_min << 5 | \
timeinfo->tm_sec >> 1);
header.modDate = (uint16_t)((timeinfo->tm_year - 80) << 9 | \
(timeinfo->tm_mon + 1) << 5 | \
timeinfo->tm_mday);
size = dataSize;
crc = crc32(0L, Z_NULL, 0);
while (size > 0) {
len = MIN(size, UINT32_MAX);
crc = crc32(crc, data + pos, (uint32_t)len);
pos += len;
size -= len;
}
header.crc32 = (uint32_t)crc;
header.uncompressedSize = dataSize;
header.compressedSize = sizeToWrite;
header.fileNameLen = (uint16_t)strlen(APP_SIGNATURE_FILENAME);
/* this will be reassigned to CD entry and freed there */
header.fileName = OPENSSL_zalloc(header.fileNameLen + 1);
memcpy(header.fileName, APP_SIGNATURE_FILENAME, header.fileNameLen);
header.extraField = NULL;
header.extraFieldLen = 0;
if (!get_current_position(bio, &offset)) {
printf("Unable to get offset\n");
OPENSSL_free(dataToWrite);
return 0; /* FAILED */
}
zipWriteLocalHeader(bio, &dummy, &header);
while (sizeToWrite > 0) {
uint64_t toWrite = sizeToWrite < SIZE_64K ? sizeToWrite : SIZE_64K;
size_t check;
if (!BIO_write_ex(bio, dataToWrite + written, toWrite, &check)
|| check != toWrite) {
OPENSSL_free(dataToWrite);
return 0; /* FAILED */
}
sizeToWrite -= toWrite;
written += toWrite;
}
OPENSSL_free(dataToWrite);
entry = OPENSSL_zalloc(sizeof(ZIP_CENTRAL_DIRECTORY_ENTRY));
entry->creatorVersion = 0x2D;
entry->viewerVersion = header.version;
entry->flags = header.flags;
entry->compression = header.compression;
entry->modTime = header.modTime;
entry->modDate = header.modDate;
entry->crc32 = header.crc32;
entry->uncompressedSize = header.uncompressedSize;
entry->compressedSize = header.compressedSize;
/* take ownership of the fileName pointer */
entry->fileName = header.fileName;
entry->fileNameLen = header.fileNameLen;
entry->extraField = header.extraField;
entry->extraFieldLen = header.extraFieldLen;
entry->fileCommentLen = 0;
entry->fileComment = NULL;
entry->diskNoStart = 0;
entry->offsetOfLocalHeader = offset;
entry->next = NULL;
entry->entryLen = entry->fileNameLen + entry->extraFieldLen + entry->fileCommentLen + 46;
if (!zip->centralDirectoryHead) {
zip->centralDirectoryHead = entry;
} else {
ZIP_CENTRAL_DIRECTORY_ENTRY *last = zip->centralDirectoryHead;
while (last->next) {
last = last->next;
}
last->next = entry;
}
return 1; /* OK */
}
/*
* Override file data.
* [out] entry: central directory structure
* [in] data: pointer to data
* [in] dataSize: data size
* [returns] 0 on error or 1 on success
*/
static int zipOverrideFileData(ZIP_CENTRAL_DIRECTORY_ENTRY *entry, uint8_t *data, uint64_t dataSize)
{
uint64_t crc, len, pos = 0, size = dataSize;
int ret;
if (entry->overrideData) {
OPENSSL_free(entry->overrideData->data);
OPENSSL_free(entry->overrideData);
entry->overrideData = NULL;
}
entry->overrideData = OPENSSL_malloc(sizeof(ZIP_OVERRIDE_DATA));
entry->overrideData->data = OPENSSL_malloc(dataSize);
crc = crc32(0L, Z_NULL, 0);
while (size > 0) {
len = MIN(size, UINT32_MAX);
crc = crc32(crc, data + pos, (uint32_t)len);
pos += len;
size -= len;
}
entry->overrideData->crc32 = (uint32_t)crc;
entry->overrideData->uncompressedSize = dataSize;
size = dataSize;
ret = zipDeflate(entry->overrideData->data, &size, data, dataSize);
if (ret != Z_OK) {
printf("Zip deflate failed: %d\n", ret);
return 0; /* FAILED */
}
entry->overrideData->compressedSize = size;
return 1; /* OK */
}
/*
* Rewrite data to outdata bio.
* [in, out] zip: structure holds specific ZIP data
* [out] entry: central directory structure
* [out] bio: outdata file BIO
* [out] sizeOnDisk: outdata size
* [returns] 0 on error or 1 on success
*/
static int zipRewriteData(ZIP_FILE *zip, ZIP_CENTRAL_DIRECTORY_ENTRY *entry, BIO *bio, uint64_t *sizeOnDisk)
{
size_t check;
ZIP_LOCAL_HEADER header;
memset(&header, 0, sizeof(header));
if (entry->offsetOfLocalHeader >= (uint64_t)zip->fileSize) {
printf("Corrupted relative offset of local header : 0x%08" PRIX64 "\n", entry->offsetOfLocalHeader);
return 0; /* FAILED */
}
if (fseeko(zip->file, (int64_t)entry->offsetOfLocalHeader, SEEK_SET) < 0) {
return 0; /* FAILED */
}
if (!zipReadLocalHeader(&header, zip, entry->compressedSize)) {
return 0; /* FAILED */
}
if (entry->overrideData) {
header.compressedSize = entry->overrideData->compressedSize;
header.uncompressedSize = entry->overrideData->uncompressedSize;
header.crc32 = entry->overrideData->crc32;
}
zipWriteLocalHeader(bio, sizeOnDisk, &header);
if (entry->overrideData) {
if (!BIO_write_ex(bio, entry->overrideData->data, entry->overrideData->compressedSize, &check)
|| check != entry->overrideData->compressedSize) {
return 0; /* FAILED */
}
if (entry->compressedSize > (uint64_t)zip->fileSize - entry->offsetOfLocalHeader) {
printf("Corrupted compressedSize : 0x%08" PRIX64 "\n", entry->compressedSize);
return 0; /* FAILED */
}
if (fseeko(zip->file, (int64_t)entry->compressedSize, SEEK_CUR) < 0) {
return 0; /* FAILED */
}
*sizeOnDisk += entry->overrideData->compressedSize;
} else {
uint64_t len = entry->compressedSize;
uint8_t *data = OPENSSL_malloc(SIZE_64K);
while (len > 0) {
uint64_t toWrite = len < SIZE_64K ? len : SIZE_64K;
size_t size = fread(data, 1, toWrite, zip->file);
if (size != toWrite) {
OPENSSL_free(data);
return 0; /* FAILED */
}
if (!BIO_write_ex(bio, data, toWrite, &check)
|| check != toWrite) {
OPENSSL_free(data);
return 0; /* FAILED */
}
*sizeOnDisk += toWrite;
len -= toWrite;
}
OPENSSL_free(data);
}
if (header.flags & DATA_DESCRIPTOR_BIT) {
BIO_write(bio, PKZIP_DATA_DESCRIPTOR_SIGNATURE, 4);
bioAddU32(bio, header.crc32);
if (zip->isZip64) {
bioAddU64(bio, header.compressedSize);
bioAddU64(bio, header.uncompressedSize);
} else {
bioAddU32(bio, (uint32_t)header.compressedSize);
bioAddU32(bio, (uint32_t)header.uncompressedSize);
}
if (zip->isZip64) {
if (fseeko(zip->file, 24, SEEK_CUR) < 0) {
return 0; /* FAILED */
}
*sizeOnDisk += 24;
} else {
if (fseeko(zip->file, 16, SEEK_CUR) < 0) {
return 0; /* FAILED */
}
*sizeOnDisk += 16;
}
}
OPENSSL_free(header.fileName);
OPENSSL_free(header.extraField);
return 1; /* OK */
}
/*
* Write local file header to outdata bio.
* [out] bio: outdata file BIO
* [out] sizeonDisk: data size
* [in] header: local file header structure
* [returns] none
*/
static void zipWriteLocalHeader(BIO *bio, uint64_t *sizeonDisk, ZIP_LOCAL_HEADER *header)
{
BIO_write(bio, PKZIP_LH_SIGNATURE, 4);
bioAddU16(bio, header->version);
bioAddU16(bio, header->flags);
bioAddU16(bio, header->compression);
bioAddU16(bio, header->modTime);
bioAddU16(bio, header->modDate);
if (header->flags & DATA_DESCRIPTOR_BIT) {
bioAddU32(bio, 0);
bioAddU32(bio, 0);
bioAddU32(bio, 0);
} else {
bioAddU32(bio, header->crc32);
bioAddU32(bio, header->compressedSizeInZip64 ? UINT32_MAX : (uint32_t)header->compressedSize);
bioAddU32(bio, header->uncompressedSizeInZip64 ? UINT32_MAX : (uint32_t)header->uncompressedSize);
}
bioAddU16(bio, header->fileNameLen);
bioAddU16(bio, header->extraFieldLen);
if (header->fileNameLen > 0) {
BIO_write(bio, header->fileName, header->fileNameLen);
}
if (header->extraFieldLen > 0) {
BIO_write(bio, header->extraField, header->extraFieldLen);
}
*sizeonDisk = (uint64_t)30 + header->fileNameLen + header->extraFieldLen;
}
/*
* Check if a given ZIP file exists.
* [in] zip: structure holds specific ZIP data
* [in] name: APP_SIGNATURE_FILENAME or CODE_INTEGRITY_FILENAME
* [returns] 0 on error or 1 on success
*/
static int zipEntryExist(ZIP_FILE *zip, const char *name)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
uint64_t noEntries = 0;
for (entry = zip->centralDirectoryHead; entry != NULL; entry = entry->next) {
if (noEntries >= zip->centralDirectoryRecordCount) {
printf("Warning: Corrupted central directory structure\n");
return 0; /* FAILED */
}
noEntries++;
if (!entry->fileName || (entry->fileNameLen == 0)) {
printf("Warning: Corrupted file name\n");
return 0; /* FAILED */
}
if (!strcmp(entry->fileName, name)) {
return 1; /* OK */
}
}
return 0; /* FAILED */
}
/*
* Calculate ZIP container file hash.
* [in] zip: structure holds specific ZIP data
* [in] fileName: one of ZIP container file
* [in] md: message digest algorithm type
* [returns] hash
*/
static u_char *zipCalcDigest(ZIP_FILE *zip, const char *fileName, const EVP_MD *md)
{
uint8_t *data = NULL;
size_t dataSize;
u_char *mdbuf = NULL;
BIO *bhash;
dataSize = zipReadFileDataByName(&data, zip, fileName);
if (dataSize <= 0) {
return NULL; /* FAILED */
}
bhash = BIO_new(BIO_f_md());
if (!BIO_set_md(bhash, md)) {
printf("Unable to set the message digest of BIO\n");
OPENSSL_free(data);
BIO_free_all(bhash);
return NULL; /* FAILED */
}
BIO_push(bhash, BIO_new(BIO_s_null()));
if (!bio_hash_data(bhash, (char *)data, 0, dataSize)) {
OPENSSL_free(data);
BIO_free_all(bhash);
return NULL; /* FAILED */
}
mdbuf = OPENSSL_malloc((size_t)EVP_MD_size(md));
BIO_gets(bhash, (char*)mdbuf, EVP_MD_size(md));
OPENSSL_free(data);
BIO_free_all(bhash);
return mdbuf;
}
/*
* Read file data by name.
* [out] pData: pointer to data
* [in] zip: structure holds specific ZIP data
* [in] name: one of ZIP container file
* [returns] 0 on error or data size on success
*/
static size_t zipReadFileDataByName(uint8_t **pData, ZIP_FILE *zip, const char *name)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
uint64_t noEntries = 0;
for (entry = zip->centralDirectoryHead; entry != NULL; entry = entry->next) {
if (noEntries >= zip->centralDirectoryRecordCount) {
printf("Warning: Corrupted central directory structure\n");
return 0; /* FAILED */
}
noEntries++;
if (!entry->fileName || (entry->fileNameLen == 0)) {
printf("Warning: Corrupted file name\n");
return 0; /* FAILED */
}
if (!strcmp(entry->fileName, name)) {
return zipReadFileData(zip, pData, entry);
}
}
return 0; /* FAILED */
}
/*
* Read file data.
* [in, out] zip: structure holds specific ZIP data
* [out] pData: pointer to data
* [in] entry: central directory structure
* [returns] 0 on error or data size on success
*/
static size_t zipReadFileData(ZIP_FILE *zip, uint8_t **pData, ZIP_CENTRAL_DIRECTORY_ENTRY *entry)
{
FILE *file = zip->file;
uint8_t *compressedData = NULL;
uint64_t compressedSize = 0;
uint64_t uncompressedSize = 0;
size_t size, dataSize = 0;
if (entry->offsetOfLocalHeader >= (uint64_t)zip->fileSize) {
printf("Corrupted relative offset of local header : 0x%08" PRIX64 "\n", entry->offsetOfLocalHeader);
return 0; /* FAILED */
}
if (fseeko(file, (int64_t)entry->offsetOfLocalHeader, SEEK_SET) < 0) {
return 0; /* FAILED */
}
if (entry->overrideData) {
compressedSize = entry->overrideData->compressedSize;
uncompressedSize = entry->overrideData->uncompressedSize;
compressedData = OPENSSL_zalloc(compressedSize + 1);
memcpy(compressedData, entry->overrideData->data, compressedSize);
} else {
ZIP_LOCAL_HEADER header;
compressedSize = entry->compressedSize;
uncompressedSize = entry->uncompressedSize;
memset(&header, 0, sizeof(header));
if (!zipReadLocalHeader(&header, zip, compressedSize)) {
return 0; /* FAILED */
}
if (header.fileNameLen != entry->fileNameLen
|| memcmp(header.fileName, entry->fileName, header.fileNameLen)
|| header.compressedSize != compressedSize
|| header.uncompressedSize != uncompressedSize
|| header.compression != entry->compression) {
printf("Local header does not match central directory entry\n");
return 0; /* FAILED */
}
/* we don't really need those */
OPENSSL_free(header.fileName);
OPENSSL_free(header.extraField);
if (compressedSize > (uint64_t)zip->fileSize - entry->offsetOfLocalHeader) {
printf("Corrupted compressedSize : 0x%08" PRIX64 "\n", entry->compressedSize);
return 0; /* FAILED */
}
compressedData = OPENSSL_zalloc(compressedSize + 1);
size = fread(compressedData, 1, compressedSize, file);
if (size != compressedSize) {
OPENSSL_free(compressedData);
return 0; /* FAILED */
}
compressedData[compressedSize] = 0;
}
if (entry->compression == COMPRESSION_NONE) {
if (compressedSize == 0) {
OPENSSL_free(compressedData);
return 0; /* FAILED */
}
*pData = compressedData;
dataSize = compressedSize;
} else if (entry->compression == COMPRESSION_DEFLATE) {
uint8_t *uncompressedData = OPENSSL_zalloc(uncompressedSize + 1);
uint64_t destLen = uncompressedSize;
uint64_t sourceLen = compressedSize;
int ret;
ret = zipInflate(uncompressedData, &destLen, compressedData, (uLong *)&sourceLen);
OPENSSL_free(compressedData);
if (ret != Z_OK) {
printf("Data decompresssion failed, zlib error: %d\n", ret);
OPENSSL_free(uncompressedData);
return 0; /* FAILED */
} else {
if (destLen == 0) {
OPENSSL_free(uncompressedData);
return 0; /* FAILED */
}
*pData = uncompressedData;
dataSize = destLen;
}
} else {
printf("Unsupported compression mode: %d\n", entry->compression);
OPENSSL_free(compressedData);
return 0; /* FAILED */
}
return dataSize;
}
/*
* Read local file header from a ZIP file.
* [out] header: local file header
* [in, out] zip: structure holds specific ZIP data
* [in] compressedSize: compressed size
* [returns] 0 on error or 1 on success
*/
static int zipReadLocalHeader(ZIP_LOCAL_HEADER *header, ZIP_FILE *zip, uint64_t compressedSize)
{
char signature[4];
size_t size;
FILE *file = zip->file;
size = fread(signature, 1, 4, file);
if (size != 4) {
return 0; /* FAILED */
}
if (memcmp(signature, PKZIP_LH_SIGNATURE, 4)) {
printf("The input file is not a valid zip file - local header signature does not match\n");
return 0; /* FAILED */
}
/* version needed to extract (2 bytes) */
header->version = fileGetU16(file);
/* general purpose bit flag (2 bytes) */
header->flags = fileGetU16(file);
/* compression method (2 bytes) */
header->compression = fileGetU16(file);
/* last mod file time (2 bytes) */
header->modTime = fileGetU16(file);
/* last mod file date (2 bytes) */
header->modDate = fileGetU16(file);
/* crc-32 (4 bytes) */
header->crc32 = fileGetU32(file);
/* compressed size (4 bytes) */
header->compressedSize = fileGetU32(file);
/* uncompressed size (4 bytes) */
header->uncompressedSize = fileGetU32(file);
/* file name length (2 bytes) */
header->fileNameLen = fileGetU16(file);
/* extra file name length (2 bytes) */
header->extraFieldLen = fileGetU16(file);
/* file name (variable size) */
if (header->fileNameLen > 0) {
header->fileName = OPENSSL_zalloc(header->fileNameLen + 1);
size = fread(header->fileName, 1, header->fileNameLen, file);
if (size != header->fileNameLen) {
return 0; /* FAILED */
}
header->fileName[header->fileNameLen] = 0;
} else {
header->fileName = NULL;
}
/* extra field (variable size) */
if (header->extraFieldLen > 0) {
header->extraField = OPENSSL_zalloc(header->extraFieldLen + 1);
size = fread(header->extraField, 1, header->extraFieldLen, file);
if (size != header->extraFieldLen) {
return 0; /* FAILED */
}
header->extraField[header->extraFieldLen] = 0;
} else {
header->extraField = NULL;
}
if (header->flags & DATA_DESCRIPTOR_BIT) {
/* Read data descriptor */
int64_t offset = ftello(file);
if (offset < 0 || offset >= zip->fileSize) {
return 0; /* FAILED */
}
if (compressedSize > (uint64_t)(zip->fileSize - offset)) {
printf("Corrupted compressedSize : 0x%08" PRIX64 "\n", compressedSize);
return 0; /* FAILED */
}
if (fseeko(file, (int64_t)compressedSize, SEEK_CUR) < 0) {
return 0; /* FAILED */
}
size = fread(signature, 1, 4, file);
if (size != 4) {
return 0; /* FAILED */
}
if (memcmp(signature, PKZIP_DATA_DESCRIPTOR_SIGNATURE, 4)) {
printf("The input file is not a valid zip file - flags indicate data descriptor, but data descriptor signature does not match\n");
OPENSSL_free(header->fileName);
OPENSSL_free(header->extraField);
return 0; /* FAILED */
}
header->crc32 = fileGetU32(file);
if (zip->isZip64) {
header->compressedSize = fileGetU64(file);
header->uncompressedSize = fileGetU64(file);
} else {
header->compressedSize = fileGetU32(file);
header->uncompressedSize = fileGetU32(file);
}
if (fseeko(file, offset, SEEK_SET) < 0) {
return 0; /* FAILED */
}
}
if (header->uncompressedSize == UINT32_MAX || header->compressedSize == UINT32_MAX) {
if (header->extraFieldLen > 4) {
uint64_t pos = 0;
uint16_t len;
uint16_t op = bufferGetU16(header->extraField, &pos);
if (op != ZIP64_HEADER) {
printf("Expected zip64 header in local header extra field, got : 0x%X\n", op);
OPENSSL_free(header->fileName);
OPENSSL_free(header->extraField);
header->fileName = NULL;
header->extraField = NULL;
return 0; /* FAILED */
}
len = bufferGetU16(header->extraField, &pos);
if (header->uncompressedSize == UINT32_MAX) {
if (len >= 8) {
header->uncompressedSize = bufferGetU64(header->extraField, &pos);
header->uncompressedSizeInZip64 = 1;
} else {
printf("Invalid zip64 local header entry\n");
OPENSSL_free(header->fileName);
OPENSSL_free(header->extraField);
header->fileName = NULL;
header->extraField = NULL;
return 0; /* FAILED */
}
}
if (header->compressedSize == UINT32_MAX) {
if (len >= 16) {
header->compressedSize = bufferGetU64(header->extraField, &pos);
header->compressedSizeInZip64 = 1;
} else {
printf("Invalid zip64 local header entry\n");
OPENSSL_free(header->fileName);
OPENSSL_free(header->extraField);
header->fileName = NULL;
header->extraField = NULL;
return 0; /* FAILED */
}
}
} else {
OPENSSL_free(header->fileName);
OPENSSL_free(header->extraField);
header->fileName = NULL;
header->extraField = NULL;
return 0; /* FAILED */
}
}
return 1; /* OK */
}
/*
* Decompresses the source buffer into the destination buffer.
* see: uncompress2(), but windowBits is set to тАУ15 for raw inflate
* https://github.com/madler/zlib/blob/09155eaa2f9270dc4ed1fa13e2b4b2613e6e4851/uncompr.c#L27
* [out] dest: destination buffer
* [out] destLen: size of the decompressed data
* [in] source: source buffer
* [in] sourceLen: length of the source buffer
* [returns] returns ZIP error or Z_OK if success
*/
static int zipInflate(uint8_t *dest, uint64_t *destLen, uint8_t *source, uLong *sourceLen)
{
z_stream stream;
int err;
const uInt max = (uInt)-1; /* 0xFFFFFFFF */
uLong len, left;
/* for detection of incomplete stream when *destLen == 0 */
static u_char buf[] = { 0x00 };
/* reset stream */
memset(&stream, 0, sizeof stream);
len = *sourceLen;
if (*destLen) {
left = *destLen;
*destLen = 0;
} else {
left = 1;
dest = buf;
}
stream.next_in = source;
stream.avail_in = 0;
stream.zalloc = (alloc_func)0;
stream.zfree = (free_func)0;
stream.opaque = (voidpf)0;
err = inflateInit2(&stream, -MAX_WBITS);
if (err != Z_OK) {
return err;
}
stream.next_out = dest;
stream.avail_out = 0;
do {
if (stream.avail_out == 0) {
stream.avail_out = left > (uLong)max ? max : (uInt)left;
left -= stream.avail_out;
}
if (stream.avail_in == 0) {
stream.avail_in = len > (uLong)max ? max : (uInt)len;
len -= stream.avail_in;
}
/* coverity[overrun-buffer-arg] max value 0xFFFFFFFF is intended */
err = inflate(&stream, Z_NO_FLUSH);
} while (err == Z_OK);
*sourceLen -= len + stream.avail_in;
if (dest != buf) {
*destLen = stream.total_out;
} else if (stream.total_out && err == Z_BUF_ERROR) {
left = 1;
}
inflateEnd(&stream);
return err == Z_STREAM_END ? Z_OK :
err == Z_NEED_DICT ? Z_DATA_ERROR :
err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR :
err;
}
/*
* Compresses the source buffer into the destination buffer.
* see: compress2(), but windowBits is set to -15 for raw deflate
* https://github.com/madler/zlib/blob/09155eaa2f9270dc4ed1fa13e2b4b2613e6e4851/compress.c#L22
* [out] dest: destination buffer
* [out] destLen: actual size of the compressed buffer
* [in] source: source buffer
* [in] sourceLen: length of the source buffer
* [in] level: deflateInit2 parameter (8)
* [returns] returns ZIP error or Z_OK if success
*/
static int zipDeflate(uint8_t *dest, uint64_t *destLen, uint8_t *source, uLong sourceLen)
{
z_stream stream;
int err;
const uInt max = (uInt)-1; /* 0xFFFFFFFF */
uLong left;
/* reset stream */
memset(&stream, 0, sizeof stream);
left = *destLen;
*destLen = 0;
stream.zalloc = (alloc_func)0;
stream.zfree = (free_func)0;
stream.opaque = (voidpf)0;
err = deflateInit2(&stream, 8, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
if (err != Z_OK) {
return err;
}
stream.next_out = dest;
stream.avail_out = 0;
stream.next_in = source;
stream.avail_in = 0;
do {
if (stream.avail_out == 0) {
stream.avail_out = left > (uLong)max ? max : (uInt)left;
left -= stream.avail_out;
}
if (stream.avail_in == 0) {
stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen;
sourceLen -= stream.avail_in;
}
/* coverity[overrun-buffer-arg] max value 0xFFFFFFFF is intended */
err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH);
} while (err == Z_OK);
#if 0
deflate(&stream, Z_SYNC_FLUSH);
#endif
*destLen = stream.total_out;
deflateEnd(&stream);
return err == Z_STREAM_END ? Z_OK : err;
}
/*
* Open input file and create ZIP_FILE structure.
* [in] filename: input file
* [returns] pointer to ZIP_FILE structure
*/
static ZIP_FILE *openZip(const char *filename)
{
ZIP_FILE *zip;
FILE *file = fopen(filename, "rb");
if (!file) {
return NULL; /* FAILED */
}
/* oncde we read eocdr, comment might be allocated and we need to take care of it
-> create the ZIP_FILE structure */
zip = OPENSSL_zalloc(sizeof(ZIP_FILE));
zip->file = file;
if (!readZipEOCDR(&zip->eocdr, file)) {
freeZip(zip);
return NULL; /* FAILED */
}
if (fseeko(file, 0, SEEK_END) < 0) {
freeZip(zip);
return NULL; /* FAILED */
}
zip->fileSize = ftello(file);
if (zip->fileSize < 0) {
freeZip(zip);
return NULL; /* FAILED */
}
if (zip->eocdr.centralDirectoryOffset == UINT32_MAX || zip->eocdr.centralDirectorySize == UINT32_MAX) {
/* probably a zip64 file */
if (!readZip64EOCDLocator(&zip->locator, file)) {
freeZip(zip);
return NULL; /* FAILED */
}
if (zip->locator.eocdOffset >= (uint64_t)zip->fileSize) {
printf("Corrupted end of central directory locator offset : 0x%08" PRIX64 "\n", zip->locator.eocdOffset);
freeZip(zip);
return 0; /* FAILED */
}
if (!readZip64EOCDR(&zip->eocdr64, file, zip->locator.eocdOffset)) {
freeZip(zip);
return NULL; /* FAILED */
}
zip->isZip64 = 1;
zip->eocdrOffset = zip->locator.eocdOffset;
zip->eocdrLen = zip->fileSize - (int64_t)zip->eocdrOffset;
if (zip->eocdrLen < 0) {
freeZip(zip);
return NULL; /* FAILED */
}
zip->centralDirectoryOffset = zip->eocdr64.centralDirectoryOffset;
zip->centralDirectorySize = zip->eocdr64.centralDirectorySize;
zip->centralDirectoryRecordCount = zip->eocdr64.totalEntries;
} else {
if (zip->fileSize < EOCDR_SIZE) {
freeZip(zip);
return NULL; /* FAILED */
}
zip->eocdrOffset = (uint64_t)zip->fileSize - EOCDR_SIZE;
zip->eocdrLen = EOCDR_SIZE;
zip->centralDirectoryOffset = zip->eocdr.centralDirectoryOffset;
zip->centralDirectorySize = zip->eocdr.centralDirectorySize;
zip->centralDirectoryRecordCount = (uint64_t)zip->eocdr.totalEntries;
if (zip->centralDirectoryRecordCount > UINT16_MAX) {
printf("Corrupted total number of entries in the central directory : 0x%08" PRIX64 "\n", zip->centralDirectoryRecordCount);
freeZip(zip);
return NULL; /* FAILED */
}
}
if (zip->centralDirectoryOffset >= (uint64_t)zip->fileSize) {
printf("Corrupted central directory offset : 0x%08" PRIX64 "\n", zip->centralDirectoryOffset);
freeZip(zip);
return NULL; /* FAILED */
}
if (!zipReadCentralDirectory(zip, file)) {
freeZip(zip);
return NULL; /* FAILED */
}
return zip;
}
/*
* Free up ZIP_FILE structure.
* [in] ZIP_FILE structure
* [returns] none
*/
static void freeZip(ZIP_FILE *zip)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry, *next = NULL;
uint64_t noEntries = 0;
fclose(zip->file);
OPENSSL_free(zip->eocdr.comment);
OPENSSL_free(zip->eocdr64.comment);
for (entry = zip->centralDirectoryHead; entry != NULL; entry = next) {
if (noEntries > zip->centralDirectoryRecordCount) {
printf("Warning: Corrupted central directory structure\n");
freeZipCentralDirectoryEntry(entry);
return;
}
noEntries++;
next = entry->next;
freeZipCentralDirectoryEntry(entry);
}
OPENSSL_free(zip);
}
/*
* Log additional output.
* [in] ZIP_FILE structure
* [returns] none
*/
static void zipPrintCentralDirectory(ZIP_FILE *zip)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
uint64_t noEntries = 0;
printf("Central directory entry count: %" PRIu64"\n", zip->centralDirectoryRecordCount);
for (entry = zip->centralDirectoryHead; entry != NULL; entry = entry->next) {
if (noEntries >= zip->centralDirectoryRecordCount) {
printf("Warning: Corrupted central directory structure\n");
}
noEntries++;
printf("Name: %s Compressed: %" PRIu64" Uncompressed: %" PRIu64" Offset: %" PRIu64"\n", entry->fileName,
entry->compressedSize, entry->uncompressedSize, entry->offsetOfLocalHeader);
}
}
/*
* Read central directory.
* [in, out] zip: structure holds specific ZIP data
* [in, out] file: FILE pointer to the input file
* [returns] 0 on error or 1 on success
*/
static int zipReadCentralDirectory(ZIP_FILE *zip, FILE *file)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *prev = NULL;
uint64_t i;
if (fseeko(file, (int64_t)zip->centralDirectoryOffset, SEEK_SET) < 0) {
return 0; /* FAILED */
}
for (i = 0; i < zip->centralDirectoryRecordCount; i++) {
ZIP_CENTRAL_DIRECTORY_ENTRY *entry = zipReadNextCentralDirectoryEntry(file);
if (!entry) {
return 0; /* FAILED */
}
if (prev) {
prev->next = entry;
} else if (!zip->centralDirectoryHead) {
zip->centralDirectoryHead = entry;
} else {
printf("Corrupted central directory structure\n");
OPENSSL_free(entry);
return 0; /* FAILED */
}
prev = entry;
}
return 1; /* OK */
}
/*
* Initialize central directory structure.
* [in] file: FILE pointer to the input file
* [returns] pointer to the central directory structure
*/
static ZIP_CENTRAL_DIRECTORY_ENTRY *zipReadNextCentralDirectoryEntry(FILE *file)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
char signature[4];
size_t size = fread(signature, 1, 4, file);
if (size != 4) {
return NULL; /* FAILED */
}
if (memcmp(signature, PKZIP_CD_SIGNATURE, 4)) {
printf("The input file is not a valid zip file - could not find Central Directory record\n");
return NULL; /* FAILED */
}
entry = OPENSSL_zalloc(sizeof(ZIP_CENTRAL_DIRECTORY_ENTRY));
entry->fileOffset = ftello(file) - 4;
if (entry->fileOffset < 0) {
freeZipCentralDirectoryEntry(entry);
return NULL; /* FAILED */
}
/* version made by (2 bytes) */
entry->creatorVersion = fileGetU16(file);
/* version needed to extract (2 bytes) */
entry->viewerVersion = fileGetU16(file);
/* general purpose bit flag (2 bytes) */
entry->flags = fileGetU16(file);
/* compression method (2 bytes) */
entry->compression = fileGetU16(file);
/* last mod file time (2 bytes) */
entry->modTime = fileGetU16(file);
/* last mod file date (2 bytes) */
entry->modDate = fileGetU16(file);
/* crc-32 (4 bytes) */
entry->crc32 = fileGetU32(file);
/* compressed size (4 bytes), 0xFFFFFFFF for ZIP64 format */
entry->compressedSize = fileGetU32(file);
/* uncompressed size (4 bytes), 0xFFFFFFFF for ZIP64 format */
entry->uncompressedSize = fileGetU32(file);
/* file name length (2 bytes) */
entry->fileNameLen = fileGetU16(file);
/* extra field length (2 bytes) */
entry->extraFieldLen = fileGetU16(file);
/* file comment length (2 bytes) */
entry->fileCommentLen = fileGetU16(file);
/* disk number start (2 bytes), 0xFFFFFFFF for ZIP64 format */
entry->diskNoStart = fileGetU16(file);
/* internal file attributes (2 bytes) */
entry->internalAttr = fileGetU16(file);
/* external file attributes (4 bytes) */
entry->externalAttr = fileGetU32(file);
/* relative offset of local header (4 bytes), 0xFFFFFFFF for ZIP64 format */
entry->offsetOfLocalHeader = fileGetU32(file);
/* file name (variable size) */
if (entry->fileNameLen > 0) {
entry->fileName = OPENSSL_zalloc(entry->fileNameLen + 1);
size = fread(entry->fileName, 1, entry->fileNameLen, file);
if (size != entry->fileNameLen) {
freeZipCentralDirectoryEntry(entry);
return NULL; /* FAILED */
}
entry->fileName[entry->fileNameLen] = 0;
}
/* extra field (variable size) */
if (entry->extraFieldLen > 0) {
entry->extraField = OPENSSL_zalloc(entry->extraFieldLen + 1);
size = fread(entry->extraField, 1, entry->extraFieldLen, file);
if (size != entry->extraFieldLen) {
freeZipCentralDirectoryEntry(entry);
return NULL; /* FAILED */
}
entry->extraField[entry->extraFieldLen] = 0;
}
/* file comment (variable size) */
if (entry->fileCommentLen > 0) {
entry->fileComment = OPENSSL_zalloc(entry->fileCommentLen + 1);
size = fread(entry->fileComment, 1, entry->fileCommentLen, file);
if (size != entry->fileCommentLen) {
freeZipCentralDirectoryEntry(entry);
return NULL; /* FAILED */
}
entry->fileComment[entry->fileCommentLen] = 0;
}
if (entry->uncompressedSize == UINT32_MAX || entry->compressedSize == UINT32_MAX ||
entry->offsetOfLocalHeader == UINT32_MAX || entry->diskNoStart == UINT16_MAX) {
if (entry->extraFieldLen > 4) {
uint64_t pos = 0;
uint64_t len;
uint16_t header = bufferGetU16(entry->extraField, &pos);
if (header != ZIP64_HEADER) {
printf("Expected zip64 header in central directory extra field, got : 0x%X\n", header);
freeZipCentralDirectoryEntry(entry);
return NULL; /* FAILED */
}
len = bufferGetU16(entry->extraField, &pos);
if (entry->uncompressedSize == UINT32_MAX) {
if (len >= 8) {
entry->uncompressedSize = bufferGetU64(entry->extraField, &pos);
entry->uncompressedSizeInZip64 = 1;
} else {
printf("Invalid zip64 central directory entry\n");
freeZipCentralDirectoryEntry(entry);
return NULL; /* FAILED */
}
}
if (entry->compressedSize == UINT32_MAX) {
if (len >= 16) {
entry->compressedSize = bufferGetU64(entry->extraField, &pos);
entry->compressedSizeInZip64 = 1;
} else {
printf("Invalid zip64 central directory entry\n");
freeZipCentralDirectoryEntry(entry);
return NULL; /* FAILED */
}
}
if (entry->offsetOfLocalHeader == UINT32_MAX) {
if (len >= 24) {
entry->offsetOfLocalHeader = bufferGetU64(entry->extraField, &pos);
entry->offsetInZip64 = 1;
} else {
printf("Invalid zip64 central directory entry\n");
freeZipCentralDirectoryEntry(entry);
return NULL; /* FAILED */
}
}
if (entry->diskNoStart == UINT16_MAX) {
if (len >= 28) {
entry->diskNoStart = bufferGetU32(entry->extraField, &pos);
entry->diskNoInZip64 = 1;
} else {
printf("Invalid zip64 central directory entry\n");
freeZipCentralDirectoryEntry(entry);
return NULL; /* FAILED */
}
}
} else {
freeZipCentralDirectoryEntry(entry);
return NULL; /* FAILED */
}
}
entry->entryLen = ftello(file) - entry->fileOffset;
if (entry->entryLen < 0) {
freeZipCentralDirectoryEntry(entry);
return NULL; /* FAILED */
}
return entry;
}
/*
* Free up central directory structure.
* [in] central directory structure
* [returns] none
*/
static void freeZipCentralDirectoryEntry(ZIP_CENTRAL_DIRECTORY_ENTRY *entry)
{
OPENSSL_free(entry->fileName);
OPENSSL_free(entry->extraField);
OPENSSL_free(entry->fileComment);
if (entry->overrideData) {
OPENSSL_free(entry->overrideData->data);
}
OPENSSL_free(entry->overrideData);
OPENSSL_free(entry);
}
/*
* Read Zip end of central directory record.
* [out] eocdr: end of central directory record
* [in, out] file: FILE pointer to the input file
* [returns] 0 on error or 1 on success
*/
static int readZipEOCDR(ZIP_EOCDR *eocdr, FILE *file)
{
char signature[4];
size_t size;
if (fseeko(file, -EOCDR_SIZE, SEEK_END) < 0) {
return 0; /* FAILED */
}
size = fread(signature, 1, 4, file);
if (size != 4) {
return 0; /* FAILED */
}
if (memcmp(signature, PKZIP_EOCDR_SIGNATURE, 4)) {
/* Not a valid ZIP file - could not find End of Central Directory record */
return 0; /* FAILED */
}
/* number of this disk (2 bytes) */
eocdr->diskNumber = fileGetU16(file);
/* number of the disk with the start of the central directory (2 bytes) */
eocdr->centralDirectoryDiskNumber = fileGetU16(file);
/* total number of entries in the central directory on this disk (2 bytes) */
eocdr->diskEntries = fileGetU16(file);
/* total number of entries in the central directory (2 bytes) */
eocdr->totalEntries = fileGetU16(file);
/* size of the central directory (4 bytes) */
eocdr->centralDirectorySize = fileGetU32(file);
/* offset of start of central directory with respect
* to the starting disk number (4 bytes) */
eocdr->centralDirectoryOffset = fileGetU32(file);
/* .ZIP file comment length (2 bytes) */
eocdr->commentLen = fileGetU16(file);
#if 0
if (eocdr->centralDirectoryDiskNumber > 1 || eocdr->diskNumber > 1 ||
eocdr->centralDirectoryDiskNumber != eocdr->diskNumber ||
eocdr->diskEntries != eocdr->totalEntries)
{
printf("The input file is a multipart archive - not supported\n");
return 0; /* FAILED */
}
#endif
if (eocdr->commentLen > 0) {
eocdr->comment = OPENSSL_zalloc(eocdr->commentLen + 1);
size = fread(eocdr->comment, 1, eocdr->commentLen, file);
if (size != eocdr->commentLen) {
return 0; /* FAILED */
}
eocdr->comment[eocdr->commentLen] = 0;
} else {
eocdr->comment = NULL;
}
return 1; /* OK */
}
/*
* Read Zip64 end of central directory locator.
* [out] locator: Zip64 end of central directory locator
* [in, out] file: FILE pointer to the input file
* [returns] 0 on error or 1 on success
*/
static int readZip64EOCDLocator(ZIP64_EOCD_LOCATOR *locator, FILE *file)
{
char signature[4];
size_t size;
if (fseeko(file, -(EOCDR_SIZE + ZIP64_EOCD_LOCATOR_SIZE), SEEK_END) < 0) {
return 0; /* FAILED */
}
size = fread(signature, 1, 4, file);
if (size != 4) {
return 0; /* FAILED */
}
if (memcmp(signature, PKZIP64_EOCD_LOCATOR_SIGNATURE, 4)) {
printf("The input file is not a valid zip file - could not find zip64 EOCD locator\n");
return 0; /* FAILED */
}
locator->diskWithEOCD = fileGetU32(file);
locator->eocdOffset = fileGetU64(file);
locator->totalNumberOfDisks = fileGetU32(file);
return 1; /* OK */
}
/*
* Read Zip64 end of central directory record
* [out] eocdr: Zip64 end of central directory record
* [in, out] file: FILE pointer to the input file
* [in] offset: eocdr struct offset in the file
* [returns] 0 on error or 1 on success
*/
static int readZip64EOCDR(ZIP64_EOCDR *eocdr, FILE *file, uint64_t offset)
{
char signature[4];
size_t size;
if (fseeko(file, (int64_t)offset, SEEK_SET) < 0) {
return 0; /* FAILED */
}
size = fread(signature, 1, 4, file);
if (size != 4) {
return 0; /* FAILED */
}
if (memcmp(signature, PKZIP64_EOCDR_SIGNATURE, 4)) {
printf("The input file is not a valid zip file - could not find zip64 End of Central Directory record\n");
return 0; /* FAILED */
}
/* size of zip64 end of central directory record (8 bytes) */
eocdr->eocdrSize = fileGetU64(file);
/* version made by (2 bytes) */
eocdr->creatorVersion = fileGetU16(file);
/* version needed to extract (2 bytes) */
eocdr->viewerVersion = fileGetU16(file);
/* number of this disk (4 bytes) */
eocdr->diskNumber = fileGetU32(file);
/* number of the disk with the start of the central directory (4 bytes) */
eocdr->diskWithCentralDirectory = fileGetU32(file);
/* total number of entries in the central directory on this disk (8 bytes) */
eocdr->diskEntries = fileGetU64(file);
/* total number of entries in the central directory (8 bytes) */
eocdr->totalEntries = fileGetU64(file);
/* size of the central directory (8 bytes) */
eocdr->centralDirectorySize = fileGetU64(file);
/* offset of start of central directory with respect
* to the starting disk number (8 bytes) */
eocdr->centralDirectoryOffset = fileGetU64(file);
/* zip64 extensible data sector (comment) */
eocdr->commentLen = eocdr->eocdrSize - 44;
if (eocdr->commentLen > UINT16_MAX) {
printf("Corrupted file comment length : 0x%08" PRIX64 "\n", eocdr->commentLen);
return 0; /* FAILED */
}
if (eocdr->commentLen > 0) {
eocdr->comment = OPENSSL_malloc(eocdr->commentLen);
size = fread(eocdr->comment, 1, eocdr->commentLen, file);
if (size != eocdr->commentLen) {
return 0; /* FAILED */
}
}
if (eocdr->diskWithCentralDirectory > 1 || eocdr->diskNumber > 1 ||
eocdr->diskWithCentralDirectory != eocdr->diskNumber ||
eocdr->totalEntries != eocdr->diskEntries) {
printf("The input file is a multipart archive - not supported\n");
return 0; /* FAILED */
}
return 1; /* OK */
}
static int get_current_position(BIO *bio, uint64_t *offset)
{
FILE *file = NULL;
int64_t pos;
BIO_get_fp(bio, &file);
pos = ftello(file);
if (pos < 0) {
return 0; /* FAILED */
}
*offset = (uint64_t)pos;
return 1; /* OK */
}
static uint64_t fileGetU64(FILE *file)
{
uint64_t l = fileGetU32(file);
uint64_t h = fileGetU32(file);
/* coverity[byte_swapping] */
return h << 32 | l;
}
/* coverity[ -tainted_data_return ] */
static uint32_t fileGetU32(FILE *file)
{
uint8_t b[4];
size_t size = fread(b, 1, 4, file);
if (size != 4) {
return 0; /* FAILED */
}
return (uint32_t)(b[3] << 24 | b[2] << 16 | b[1] << 8 | b[0]);
}
/* coverity[ -tainted_data_return ] */
static uint16_t fileGetU16(FILE *file)
{
uint8_t b[2];
size_t size = fread(b, 1, 2, file);
if (size != 2) {
return 0; /* FAILED */
}
return (uint16_t)(b[1] << 8 | b[0]);
}
static uint64_t bufferGetU64(uint8_t *buffer, uint64_t *pos)
{
uint64_t l = bufferGetU32(buffer, pos);
uint64_t h = bufferGetU32(buffer, pos);
return h << 32 | l;
}
static uint32_t bufferGetU32(uint8_t *buffer, uint64_t *pos)
{
uint32_t ret = (uint32_t)(buffer[*pos + 3] << 24 | \
buffer[*pos + 2] << 16 | \
buffer[*pos + 1] << 8 | \
buffer[*pos]);
*pos += 4;
return ret;
}
static uint16_t bufferGetU16(uint8_t *buffer, uint64_t *pos)
{
uint16_t ret = (uint16_t)(buffer[*pos + 1] << 8 | buffer[*pos]);
*pos += 2;
return ret;
}
void bioAddU64(BIO *bio, uint64_t v)
{
uint32_t l = v & UINT32_MAX;
uint32_t h = (uint32_t)(v >> 32);
bioAddU32(bio, l);
bioAddU32(bio, h);
}
static void bioAddU32(BIO *bio, uint32_t v)
{
uint8_t b[4];
b[0] = (u_char)((v) & UINT8_MAX);
b[1] = (u_char)(((v) >> 8) & UINT8_MAX);
b[2] = (u_char)(((v) >> 16) & UINT8_MAX);
b[3] = (u_char)(((v) >> 24) & UINT8_MAX);
BIO_write(bio, b, 4);
}
static void bioAddU16(BIO *bio, uint16_t v)
{
uint8_t b[2];
b[0] = (u_char)((v) & UINT8_MAX);
b[1] = (u_char)(((v) >> 8) & UINT8_MAX);
BIO_write(bio, b, 2);
}
/*
Local Variables:
c-basic-offset: 4
tab-width: 4
indent-tabs-mode: nil
End:
vim: set ts=4 expandtab:
*/
osslsigncode-2.8/cab.c 0000664 0000000 0000000 00000077254 14571175157 0015004 0 ustar 00root root 0000000 0000000 /*
* CAB file support library
*
* Copyright (C) 2021-2023 Micha┼В Trojnara
* Author: Ma┼Вgorzata Olsz├│wka
*
* Reference specifications:
* https://www.file-recovery.com/cab-signature-format.htm
* https://learn.microsoft.com/en-us/previous-versions/ms974336(v=msdn.10)
*/
#include "osslsigncode.h"
#include "helpers.h"
/*
* FLAG_PREV_CABINET is set if the cabinet file is not the first in a set
* of cabinet files. When this bit is set, the szCabinetPrev and szDiskPrev
* fields are present in this CFHEADER.
*/
#define FLAG_PREV_CABINET 0x0001
/*
* FLAG_NEXT_CABINET is set if the cabinet file is not the last in a set of
* cabinet files. When this bit is set, the szCabinetNext and szDiskNext
* fields are present in this CFHEADER.
*/
#define FLAG_NEXT_CABINET 0x0002
/*
* FLAG_RESERVE_PRESENT is set if the cabinet file contains any reserved
* fields. When this bit is set, the cbCFHeader, cbCFFolder, and cbCFData
* fields are present in this CFHEADER.
*/
#define FLAG_RESERVE_PRESENT 0x0004
struct cab_ctx_st {
uint32_t header_size;
uint32_t sigpos;
uint32_t siglen;
uint32_t fileend;
uint16_t flags;
};
/* FILE_FORMAT method prototypes */
static FILE_FORMAT_CTX *cab_ctx_new(GLOBAL_OPTIONS *options, BIO *hash, BIO *outdata);
static ASN1_OBJECT *cab_obsolete_link_get(u_char **p, int *plen, FILE_FORMAT_CTX *ctx);
static PKCS7 *cab_pkcs7_contents_get(FILE_FORMAT_CTX *ctx, BIO *hash, const EVP_MD *md);
static int cab_hash_length_get(FILE_FORMAT_CTX *ctx);
static u_char *cab_digest_calc(FILE_FORMAT_CTX *ctx, const EVP_MD *md);
static int cab_verify_digests(FILE_FORMAT_CTX *ctx, PKCS7 *p7);
static PKCS7 *cab_pkcs7_extract(FILE_FORMAT_CTX *ctx);
static PKCS7 *cab_pkcs7_extract_to_nest(FILE_FORMAT_CTX *ctx);
static int cab_remove_pkcs7(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata);
static int cab_process_data(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata);
static PKCS7 *cab_pkcs7_signature_new(FILE_FORMAT_CTX *ctx, BIO *hash);
static int cab_append_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7);
static void cab_update_data_size(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7);
static void cab_bio_free(BIO *hash, BIO *outdata);
static void cab_ctx_cleanup(FILE_FORMAT_CTX *ctx);
static int cab_is_detaching_supported(void);
FILE_FORMAT file_format_cab = {
.ctx_new = cab_ctx_new,
.data_blob_get = cab_obsolete_link_get,
.pkcs7_contents_get = cab_pkcs7_contents_get,
.hash_length_get = cab_hash_length_get,
.digest_calc = cab_digest_calc,
.verify_digests = cab_verify_digests,
.pkcs7_extract = cab_pkcs7_extract,
.pkcs7_extract_to_nest = cab_pkcs7_extract_to_nest,
.remove_pkcs7 = cab_remove_pkcs7,
.process_data = cab_process_data,
.pkcs7_signature_new = cab_pkcs7_signature_new,
.append_pkcs7 = cab_append_pkcs7,
.update_data_size = cab_update_data_size,
.bio_free = cab_bio_free,
.ctx_cleanup = cab_ctx_cleanup,
.is_detaching_supported = cab_is_detaching_supported
};
/* Prototypes */
static CAB_CTX *cab_ctx_get(char *indata, uint32_t filesize);
static int cab_add_jp_attribute(PKCS7 *p7, int jp);
static size_t cab_write_optional_names(BIO *outdata, char *indata, size_t len, uint16_t flags);
static int cab_modify_header(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata);
static int cab_add_header(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata);
static int cab_check_file(FILE_FORMAT_CTX *ctx);
/*
* FILE_FORMAT method definitions
*/
/*
* Allocate and return a CAB file format context.
* [in, out] options: structure holds the input data
* [out] hash: message digest BIO
* [in] outdata: outdata file BIO
* [returns] pointer to CAB file format context
*/
static FILE_FORMAT_CTX *cab_ctx_new(GLOBAL_OPTIONS *options, BIO *hash, BIO *outdata)
{
FILE_FORMAT_CTX *ctx;
CAB_CTX *cab_ctx;
uint32_t filesize;
filesize = get_file_size(options->infile);
if (filesize == 0)
return NULL; /* FAILED */
options->indata = map_file(options->infile, filesize);
if (!options->indata) {
return NULL; /* FAILED */
}
if (memcmp(options->indata, "MSCF", 4)) {
unmap_file(options->indata, filesize);
return NULL; /* FAILED */
}
cab_ctx = cab_ctx_get(options->indata, filesize);
if (!cab_ctx) {
unmap_file(options->indata, filesize);
return NULL; /* FAILED */
}
ctx = OPENSSL_malloc(sizeof(FILE_FORMAT_CTX));
ctx->format = &file_format_cab;
ctx->options = options;
ctx->cab_ctx = cab_ctx;
/* Push hash on outdata, if hash is NULL the function does nothing */
BIO_push(hash, outdata);
if (options->pagehash == 1)
printf("Warning: -ph option is only valid for PE files\n");
if (options->add_msi_dse == 1)
printf("Warning: -add-msi-dse option is only valid for MSI files\n");
return ctx;
}
/*
* Allocate and return SpcLink object.
* [out] p: SpcLink data
* [out] plen: SpcLink data length
* [in] ctx: structure holds input and output data (unused)
* [returns] pointer to ASN1_OBJECT structure corresponding to SPC_CAB_DATA_OBJID
*/
static ASN1_OBJECT *cab_obsolete_link_get(u_char **p, int *plen, FILE_FORMAT_CTX *ctx)
{
ASN1_OBJECT *dtype;
SpcLink *link = spc_link_obsolete_get();
/* squash the unused parameter warning */
(void)ctx;
*plen = i2d_SpcLink(link, NULL);
*p = OPENSSL_malloc((size_t)*plen);
i2d_SpcLink(link, p);
*p -= *plen;
dtype = OBJ_txt2obj(SPC_CAB_DATA_OBJID, 1);
SpcLink_free(link);
return dtype; /* OK */
}
/*
* Allocate and return a data content to be signed.
* [in] ctx: structure holds input and output data
* [in] hash: message digest BIO
* [in] md: message digest algorithm
* [returns] data content
*/
static PKCS7 *cab_pkcs7_contents_get(FILE_FORMAT_CTX *ctx, BIO *hash, const EVP_MD *md)
{
ASN1_OCTET_STRING *content;
/* squash the unused parameter warning, use initialized message digest BIO */
(void)md;
/* Strip current signature and modify header */
if (ctx->cab_ctx->header_size == 20) {
if (!cab_modify_header(ctx, hash, NULL))
return NULL; /* FAILED */
} else {
if (!cab_add_header(ctx, hash, NULL))
return NULL; /* FAILED */
}
content = spc_indirect_data_content_get(hash, ctx);
return pkcs7_set_content(content);
}
/*
* [in] ctx: structure holds input and output data
* [returns] the size of the message digest when passed an EVP_MD structure (the size of the hash)
*/
static int cab_hash_length_get(FILE_FORMAT_CTX *ctx)
{
return EVP_MD_size(ctx->options->md);
}
/*
* Compute a message digest value of the signed or unsigned CAB file.
* [in] ctx: structure holds input and output data
* [in] md: message digest algorithm
* [returns] pointer to calculated message digest
*/
static u_char *cab_digest_calc(FILE_FORMAT_CTX *ctx, const EVP_MD *md)
{
uint32_t idx, fileend, coffFiles;
u_char *mdbuf = NULL;
BIO *bhash = BIO_new(BIO_f_md());
if (!BIO_set_md(bhash, md)) {
printf("Unable to set the message digest of BIO\n");
BIO_free_all(bhash);
return 0; /* FAILED */
}
BIO_push(bhash, BIO_new(BIO_s_null()));
/* u1 signature[4] 4643534D MSCF: 0-3 */
BIO_write(bhash, ctx->options->indata, 4);
/* u4 reserved1 00000000: 4-7 skipped */
if (ctx->cab_ctx->sigpos) {
uint16_t nfolders, flags;
/*
* u4 cbCabinet - size of this cabinet file in bytes: 8-11
* u4 reserved2 00000000: 12-15
*/
BIO_write(bhash, ctx->options->indata + 8, 8);
/* u4 coffFiles - offset of the first CFFILE entry: 16-19 */
coffFiles = GET_UINT32_LE(ctx->options->indata + 16);
BIO_write(bhash, ctx->options->indata + 16, 4);
/*
* u4 reserved3 00000000: 20-23
* u1 versionMinor 03: 24
* u1 versionMajor 01: 25
*/
BIO_write(bhash, ctx->options->indata + 20, 6);
/* u2 cFolders - number of CFFOLDER entries in this cabinet: 26-27 */
nfolders = GET_UINT16_LE(ctx->options->indata + 26);
BIO_write(bhash, ctx->options->indata + 26, 2);
/* u2 cFiles - number of CFFILE entries in this cabinet: 28-29 */
BIO_write(bhash, ctx->options->indata + 28, 2);
/* u2 flags: 30-31 */
flags = GET_UINT16_LE(ctx->options->indata + 30);
BIO_write(bhash, ctx->options->indata + 30, 2);
/* u2 setID must be the same for all cabinets in a set: 32-33 */
BIO_write(bhash, ctx->options->indata + 32, 2);
/*
* u2 iCabinet - number of this cabinet file in a set: 34-35 skipped
* u2 cbCFHeader: 36-37 skipped
* u1 cbCFFolder: 38 skipped
* u1 cbCFData: 39 skipped
* u22 abReserve: 40-55 skipped
* - Additional data offset: 44-47 skipped
* - Additional data size: 48-51 skipped
*/
/* u22 abReserve: 56-59 */
BIO_write(bhash, ctx->options->indata + 56, 4);
idx = 60;
fileend = ctx->cab_ctx->sigpos;
/* TODO */
if (flags & FLAG_PREV_CABINET) {
uint8_t byte;
/* szCabinetPrev */
do {
byte = GET_UINT8_LE(ctx->options->indata + idx);
BIO_write(bhash, ctx->options->indata + idx, 1);
idx++;
} while (byte && idx < fileend);
/* szDiskPrev */
do {
byte = GET_UINT8_LE(ctx->options->indata + idx);
BIO_write(bhash, ctx->options->indata + idx, 1);
idx++;
} while (byte && idx < fileend);
}
if (flags & FLAG_NEXT_CABINET) {
uint8_t byte;
/* szCabinetNext */
do {
byte = GET_UINT8_LE(ctx->options->indata + idx);
BIO_write(bhash, ctx->options->indata + idx, 1);
idx++;
} while (byte && idx < fileend);
/* szDiskNext */
do {
byte = GET_UINT8_LE(ctx->options->indata + idx);
BIO_write(bhash, ctx->options->indata + idx, 1);
idx++;
} while (byte && idx < fileend);
}
/*
* (u8 * cFolders) CFFOLDER - structure contains information about
* one of the folders or partial folders stored in this cabinet file
*/
while (nfolders && idx < fileend) {
BIO_write(bhash, ctx->options->indata + idx, 8);
idx += 8;
nfolders--;
}
if (idx != coffFiles) {
printf("Corrupt coffFiles value: 0x%08X\n", coffFiles);
BIO_free_all(bhash);
return 0; /* FAILED */
}
} else {
/* read what's left of the unsigned CAB file */
idx = 8;
fileend = ctx->cab_ctx->fileend;
}
/* (variable) ab - the compressed data bytes */
if (!bio_hash_data(bhash, ctx->options->indata, idx, fileend)) {
printf("Unable to calculate digest\n");
BIO_free_all(bhash);
return 0; /* FAILED */
}
mdbuf = OPENSSL_malloc((size_t)EVP_MD_size(md));
BIO_gets(bhash, (char*)mdbuf, EVP_MD_size(md));
BIO_free_all(bhash);
return mdbuf; /* OK */
}
/*
* Calculate message digest and compare to value retrieved from PKCS#7 signedData.
* [in] ctx: structure holds input and output data
* [in] p7: PKCS#7 signature
* [returns] 0 on error or 1 on success
*/
static int cab_verify_digests(FILE_FORMAT_CTX *ctx, PKCS7 *p7)
{
int mdtype = -1;
const EVP_MD *md;
u_char mdbuf[EVP_MAX_MD_SIZE];
u_char *cmdbuf;
if (is_content_type(p7, SPC_INDIRECT_DATA_OBJID)) {
ASN1_STRING *content_val = p7->d.sign->contents->d.other->value.sequence;
const u_char *p = content_val->data;
SpcIndirectDataContent *idc = d2i_SpcIndirectDataContent(NULL, &p, content_val->length);
if (idc) {
if (idc->messageDigest && idc->messageDigest->digest && idc->messageDigest->digestAlgorithm) {
mdtype = OBJ_obj2nid(idc->messageDigest->digestAlgorithm->algorithm);
memcpy(mdbuf, idc->messageDigest->digest->data, (size_t)idc->messageDigest->digest->length);
}
SpcIndirectDataContent_free(idc);
}
}
if (mdtype == -1) {
printf("Failed to extract current message digest\n\n");
return 0; /* FAILED */
}
md = EVP_get_digestbynid(mdtype);
cmdbuf = cab_digest_calc(ctx, md);
if (!cmdbuf) {
printf("Failed to calculate message digest\n\n");
return 0; /* FAILED */
}
if (!compare_digests(mdbuf, cmdbuf, mdtype)) {
printf("Signature verification: failed\n\n");
OPENSSL_free(cmdbuf);
return 0; /* FAILED */
}
OPENSSL_free(cmdbuf);
return 1; /* OK */
}
/*
* Extract existing signature in DER format.
* [in] ctx: structure holds input and output data
* pointer to PKCS#7 structure
*/
static PKCS7 *cab_pkcs7_extract(FILE_FORMAT_CTX *ctx)
{
const u_char *blob;
if (!cab_check_file(ctx)) {
return NULL; /* FAILED */
}
blob = (u_char *)ctx->options->indata + ctx->cab_ctx->sigpos;
return d2i_PKCS7(NULL, &blob, ctx->cab_ctx->siglen);
}
/*
* Extract existing signature in DER format.
* [in] ctx: structure holds input and output data
* pointer to PKCS#7 structure
*/
static PKCS7 *cab_pkcs7_extract_to_nest(FILE_FORMAT_CTX *ctx)
{
return cab_pkcs7_extract(ctx);
}
/*
* Remove existing signature.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO (unused)
* [out] outdata: outdata file BIO
* [returns] 1 on error or 0 on success
*/
static int cab_remove_pkcs7(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata)
{
size_t i, written, len;
uint32_t tmp;
uint16_t nfolders, flags;
char *buf;
/* squash the unused parameter warning */
(void)hash;
if (!cab_check_file(ctx)) {
return 1; /* FAILED, no signature */
}
buf = OPENSSL_malloc(SIZE_64K);
/*
* u1 signature[4] 4643534D MSCF: 0-3
* u4 reserved1 00000000: 4-7
*/
BIO_write(outdata, ctx->options->indata, 8);
/* u4 cbCabinet - size of this cabinet file in bytes: 8-11 */
tmp = GET_UINT32_LE(ctx->options->indata + 8) - 24;
PUT_UINT32_LE(tmp, buf);
BIO_write(outdata, buf, 4);
/* u4 reserved2 00000000: 12-15 */
BIO_write(outdata, ctx->options->indata + 12, 4);
/* u4 coffFiles - offset of the first CFFILE entry: 16-19 */
tmp = GET_UINT32_LE(ctx->options->indata + 16) - 24;
PUT_UINT32_LE(tmp, buf);
BIO_write(outdata, buf, 4);
/*
* u4 reserved3 00000000: 20-23
* u1 versionMinor 03: 24
* u1 versionMajor 01: 25
* u2 cFolders - number of CFFOLDER entries in this cabinet: 26-27
* u2 cFiles - number of CFFILE entries in this cabinet: 28-29
*/
BIO_write(outdata, ctx->options->indata + 20, 10);
/* u2 flags: 30-31 */
flags = GET_UINT16_LE(ctx->options->indata + 30);
/* coverity[result_independent_of_operands] only least significant byte is affected */
PUT_UINT16_LE(flags & (FLAG_PREV_CABINET | FLAG_NEXT_CABINET), buf);
BIO_write(outdata, buf, 2);
/*
* u2 setID must be the same for all cabinets in a set: 32-33
* u2 iCabinet - number of this cabinet file in a set: 34-35
*/
BIO_write(outdata, ctx->options->indata + 32, 4);
i = cab_write_optional_names(outdata, ctx->options->indata, 60, flags);
/*
* (u8 * cFolders) CFFOLDER - structure contains information about
* one of the folders or partial folders stored in this cabinet file
*/
nfolders = GET_UINT16_LE(ctx->options->indata + 26);
while (nfolders) {
tmp = GET_UINT32_LE(ctx->options->indata + i);
tmp -= 24;
PUT_UINT32_LE(tmp, buf);
BIO_write(outdata, buf, 4);
BIO_write(outdata, ctx->options->indata + i + 4, 4);
i+=8;
nfolders--;
}
OPENSSL_free(buf);
/* Write what's left - the compressed data bytes */
len = ctx->cab_ctx->fileend - ctx->cab_ctx->siglen - i;
while (len > 0) {
if (!BIO_write_ex(outdata, ctx->options->indata + i, len, &written))
return 1; /* FAILED */
len -= written;
i += written;
}
return 0; /* OK */
}
/*
* Modify specific type data and calculate a hash (message digest) of data.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO
* [out] outdata: outdata file BIO
* [returns] 1 on error or 0 on success
*/
static int cab_process_data(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata)
{
/* Strip current signature and modify header */
if (ctx->cab_ctx->header_size == 20) {
if (!cab_modify_header(ctx, hash, outdata))
return 1; /* FAILED */
} else {
if (!cab_add_header(ctx, hash, outdata))
return 1; /* FAILED */
}
return 0; /* OK */
}
/*
* Create a new PKCS#7 signature.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO
* [returns] pointer to PKCS#7 structure
*/
static PKCS7 *cab_pkcs7_signature_new(FILE_FORMAT_CTX *ctx, BIO *hash)
{
ASN1_OCTET_STRING *content;
PKCS7 *p7 = pkcs7_create(ctx);
if (!p7) {
printf("Creating a new signature failed\n");
return NULL; /* FAILED */
}
if (ctx->options->jp >= 0 && !cab_add_jp_attribute(p7, ctx->options->jp)) {
printf("Adding jp attribute failed\n");
PKCS7_free(p7);
return NULL; /* FAILED */
}
if (!add_indirect_data_object(p7)) {
printf("Adding SPC_INDIRECT_DATA_OBJID failed\n");
PKCS7_free(p7);
return NULL; /* FAILED */
}
content = spc_indirect_data_content_get(hash, ctx);
if (!content) {
printf("Failed to get spcIndirectDataContent\n");
return NULL; /* FAILED */
}
if (!sign_spc_indirect_data_content(p7, content)) {
printf("Failed to set signed content\n");
PKCS7_free(p7);
ASN1_OCTET_STRING_free(content);
return NULL; /* FAILED */
}
ASN1_OCTET_STRING_free(content);
return p7;
}
/*
* Append signature to the outfile.
* [in, out] ctx: structure holds input and output data (unused)
* [out] outdata: outdata file BIO
* [in] p7: PKCS#7 signature
* [returns] 1 on error or 0 on success
*/
static int cab_append_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7)
{
u_char *p = NULL;
int len; /* signature length */
int padlen; /* signature padding length */
/* squash the unused parameter warning */
(void)ctx;
if (((len = i2d_PKCS7(p7, NULL)) <= 0)
|| (p = OPENSSL_malloc((size_t)len)) == NULL) {
printf("i2d_PKCS memory allocation failed: %d\n", len);
return 1; /* FAILED */
}
i2d_PKCS7(p7, &p);
p -= len;
padlen = len % 8 ? 8 - len % 8 : 0;
BIO_write(outdata, p, len);
/* pad (with 0's) asn1 blob to 8 byte boundary */
if (padlen > 0) {
memset(p, 0, (size_t)padlen);
BIO_write(outdata, p, padlen);
}
OPENSSL_free(p);
return 0; /* OK */
}
/*
* Update additional data size.
* Additional data size is located at offset 0x30 (from file beginning)
* and consist of 4 bytes (little-endian order).
* [in, out] ctx: structure holds input and output data
* [out] outdata: outdata file BIO
* [in] p7: PKCS#7 signature
* [returns] none
*/
static void cab_update_data_size(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7)
{
int len, padlen;
u_char buf[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
/* squash the unused parameter warning */
(void)ctx;
if (!p7) {
/* CMD_REMOVE
* additional header does not exist so additional data size is unused */
return;
}
(void)BIO_seek(outdata, 0x30);
len = i2d_PKCS7(p7, NULL);
padlen = len % 8 ? 8 - len % 8 : 0;
PUT_UINT32_LE(len + padlen, buf);
BIO_write(outdata, buf, 4);
}
/*
* Free up an entire message digest BIO chain.
* [out] hash: message digest BIO
* [out] outdata: outdata file BIO (unused)
* [returns] none
*/
static void cab_bio_free(BIO *hash, BIO *outdata)
{
/* squash the unused parameter warning */
(void)outdata;
BIO_free_all(hash);
}
/*
* Deallocate a FILE_FORMAT_CTX structure and CAB format specific structure,
* unmap indata file.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO
* [in] outdata: outdata file BIO
* [returns] none
*/
static void cab_ctx_cleanup(FILE_FORMAT_CTX *ctx)
{
unmap_file(ctx->options->indata, ctx->cab_ctx->fileend);
OPENSSL_free(ctx->cab_ctx);
OPENSSL_free(ctx);
}
static int cab_is_detaching_supported(void)
{
return 1; /* OK */
}
/*
* CAB helper functions
*/
/*
* Verify mapped CAB file and create CAB format specific structure.
* [in] indata: mapped CAB file
* [in] filesize: size of CAB file
* [returns] pointer to CAB format specific structure
*/
static CAB_CTX *cab_ctx_get(char *indata, uint32_t filesize)
{
CAB_CTX *cab_ctx;
uint32_t reserved, header_size = 0, sigpos = 0, siglen = 0;
uint16_t flags;
if (filesize < 44) {
printf("CAB file is too short\n");
return NULL; /* FAILED */
}
reserved = GET_UINT32_LE(indata + 4);
if (reserved) {
printf("Reserved1: 0x%08X\n", reserved);
return NULL; /* FAILED */
}
/* flags specify bit-mapped values that indicate the presence of optional data */
flags = GET_UINT16_LE(indata + 30);
if (flags & FLAG_PREV_CABINET) {
/* FLAG_NEXT_CABINET works */
printf("Multivolume cabinet file is unsupported: flags 0x%04X\n", flags);
return NULL; /* FAILED */
}
if (flags & FLAG_RESERVE_PRESENT) {
/*
* Additional headers is located at offset 36 (cbCFHeader, cbCFFolder, cbCFData);
* size of header (4 bytes, little-endian order) must be 20 (checkpoint).
*/
header_size = GET_UINT32_LE(indata + 36);
if (header_size != 20) {
printf("Additional header size: 0x%08X\n", header_size);
return NULL; /* FAILED */
}
reserved = GET_UINT32_LE(indata + 40);
if (reserved != 0x00100000) {
printf("abReserved: 0x%08X\n", reserved);
return NULL; /* FAILED */
}
/*
* File size is defined at offset 8, however if additional header exists, this size is not valid.
* sigpos - additional data offset is located at offset 44 (from file beginning)
* and consist of 4 bytes (little-endian order)
* siglen - additional data size is located at offset 48 (from file beginning)
* and consist of 4 bytes (little-endian order)
* If there are additional headers, size of the CAB archive file is calcualted
* as additional data offset plus additional data size.
*/
sigpos = GET_UINT32_LE(indata + 44);
siglen = GET_UINT32_LE(indata + 48);
if ((sigpos < filesize && sigpos + siglen != filesize) || (sigpos >= filesize)) {
printf("Additional data offset:\t%u bytes\nAdditional data size:\t%u bytes\n",
sigpos, siglen);
printf("File size:\t\t%u bytes\n", filesize);
return NULL; /* FAILED */
}
if ((sigpos > 0 && siglen == 0) || (sigpos == 0 && siglen > 0)) {
printf("Corrupt signature\n");
return NULL; /* FAILED */
}
}
cab_ctx = OPENSSL_zalloc(sizeof(CAB_CTX));
cab_ctx->header_size = header_size;
cab_ctx->sigpos = sigpos;
cab_ctx->siglen = siglen;
cab_ctx->fileend = filesize;
cab_ctx->flags = flags;
return cab_ctx; /* OK */
}
/*
* Add level of permissions in Microsoft Internet Explorer 4.x for CAB files,
* only low level is supported.
* [in, out] p7: PKCS#7 signature
* [in] jp: low (0) level
* [returns] 0 on error or 1 on success
*/
static int cab_add_jp_attribute(PKCS7 *p7, int jp)
{
STACK_OF(PKCS7_SIGNER_INFO) *signer_info;
PKCS7_SIGNER_INFO *si;
ASN1_STRING *astr;
const u_char *attrs = NULL;
const u_char java_attrs_low[] = {
0x30, 0x06, 0x03, 0x02, 0x00, 0x01, 0x30, 0x00
};
signer_info = PKCS7_get_signer_info(p7);
if (!signer_info)
return 0; /* FAILED */
si = sk_PKCS7_SIGNER_INFO_value(signer_info, 0);
if (!si)
return 0; /* FAILED */
switch (jp) {
case 0:
attrs = java_attrs_low;
break;
case 1:
/* XXX */
case 2:
/* XXX */
default:
break;
}
if (attrs) {
astr = ASN1_STRING_new();
ASN1_STRING_set(astr, attrs, sizeof java_attrs_low);
return PKCS7_add_signed_attribute(si, OBJ_txt2nid(MS_JAVA_SOMETHING),
V_ASN1_SEQUENCE, astr);
}
return 1; /* OK */
}
/*
* Write name of previous and next cabinet file.
* Multivolume cabinet file is unsupported TODO.
* [out] outdata: outdata file BIO
* [in] indata: mapped CAB file
* [in] len: offset
* [in] flags: FLAG_PREV_CABINET, FLAG_NEXT_CABINET
* [returns] offset
*/
static size_t cab_write_optional_names(BIO *outdata, char *indata, size_t i, uint16_t flags)
{
if (flags & FLAG_PREV_CABINET) {
/* szCabinetPrev */
while (GET_UINT8_LE(indata + i)) {
BIO_write(outdata, indata + i, 1);
i++;
}
BIO_write(outdata, indata + i, 1);
i++;
/* szDiskPrev */
while (GET_UINT8_LE(indata + i)) {
BIO_write(outdata, indata + i, 1);
i++;
}
BIO_write(outdata, indata + i, 1);
i++;
}
if (flags & FLAG_NEXT_CABINET) {
/* szCabinetNext */
while (GET_UINT8_LE(indata + i)) {
BIO_write(outdata, indata + i, 1);
i++;
}
BIO_write(outdata, indata + i, 1);
i++;
/* szDiskNext */
while (GET_UINT8_LE(indata + i)) {
BIO_write(outdata, indata + i, 1);
i++;
}
BIO_write(outdata, indata + i, 1);
i++;
}
return i;
}
/*
* Modify CAB header.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO
* [out] outdata: outdata file BIO
* [returns] 0 on error or 1 on success
*/
static int cab_modify_header(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata)
{
size_t i, written, len;
uint16_t nfolders, flags;
u_char buf[] = {0x00, 0x00};
/* u1 signature[4] 4643534D MSCF: 0-3 */
BIO_write(hash, ctx->options->indata, 4);
/* u4 reserved1 00000000: 4-7 */
BIO_write(outdata, ctx->options->indata + 4, 4);
/*
* u4 cbCabinet - size of this cabinet file in bytes: 8-11
* u4 reserved2 00000000: 12-15
* u4 coffFiles - offset of the first CFFILE entry: 16-19
* u4 reserved3 00000000: 20-23
* u1 versionMinor 03: 24
* u1 versionMajor 01: 25
* u2 cFolders - number of CFFOLDER entries in this cabinet: 26-27
* u2 cFiles - number of CFFILE entries in this cabinet: 28-29
*/
BIO_write(hash, ctx->options->indata + 8, 22);
/* u2 flags: 30-31 */
flags = GET_UINT16_LE(ctx->options->indata + 30);
PUT_UINT16_LE(flags, buf);
BIO_write(hash, buf, 2);
/* u2 setID must be the same for all cabinets in a set: 32-33 */
BIO_write(hash, ctx->options->indata + 32, 2);
/*
* u2 iCabinet - number of this cabinet file in a set: 34-35
* u2 cbCFHeader: 36-37
* u1 cbCFFolder: 38
* u1 cbCFData: 39
* u16 abReserve: 40-55
* - Additional data offset: 44-47
* - Additional data size: 48-51
*/
BIO_write(outdata, ctx->options->indata + 34, 22);
/* u4 abReserve: 56-59 */
BIO_write(hash, ctx->options->indata + 56, 4);
i = cab_write_optional_names(outdata, ctx->options->indata, 60, flags);
/*
* (u8 * cFolders) CFFOLDER - structure contains information about
* one of the folders or partial folders stored in this cabinet file
*/
nfolders = GET_UINT16_LE(ctx->options->indata + 26);
while (nfolders) {
BIO_write(hash, ctx->options->indata + i, 8);
i += 8;
nfolders--;
}
/* Write what's left - the compressed data bytes */
len = ctx->cab_ctx->sigpos - i;
while (len > 0) {
if (!BIO_write_ex(hash, ctx->options->indata + i, len, &written))
return 0; /* FAILED */
len -= written;
i += written;
}
return 1; /* OK */
}
/*
* Add signed CAB header.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO
* [out] outdata: outdata file BIO
* [returns] 0 on error or 1 on success
*/
static int cab_add_header(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata)
{
size_t i, written, len;
uint32_t tmp;
uint16_t nfolders, flags;
u_char cabsigned[] = {
0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
0xde, 0xad, 0xbe, 0xef, /* size of cab file */
0xde, 0xad, 0xbe, 0xef, /* size of asn1 blob */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
char *buf = OPENSSL_malloc(SIZE_64K);
memset(buf, 0, SIZE_64K);
/* u1 signature[4] 4643534D MSCF: 0-3 */
BIO_write(hash, ctx->options->indata, 4);
/* u4 reserved1 00000000: 4-7 */
BIO_write(outdata, ctx->options->indata + 4, 4);
/* u4 cbCabinet - size of this cabinet file in bytes: 8-11 */
tmp = GET_UINT32_LE(ctx->options->indata + 8) + 24;
PUT_UINT32_LE(tmp, buf);
BIO_write(hash, buf, 4);
/* u4 reserved2 00000000: 12-15 */
BIO_write(hash, ctx->options->indata + 12, 4);
/* u4 coffFiles - offset of the first CFFILE entry: 16-19 */
tmp = GET_UINT32_LE(ctx->options->indata + 16) + 24;
PUT_UINT32_LE(tmp, buf + 4);
BIO_write(hash, buf + 4, 4);
/*
* u4 reserved3 00000000: 20-23
* u1 versionMinor 03: 24
* u1 versionMajor 01: 25
* u2 cFolders - number of CFFOLDER entries in this cabinet: 26-27
* u2 cFiles - number of CFFILE entries in this cabinet: 28-29
*/
memcpy(buf + 4, ctx->options->indata + 20, 10);
flags = GET_UINT16_LE(ctx->options->indata + 30);
buf[4+10] = (char)flags | FLAG_RESERVE_PRESENT;
/* u2 setID must be the same for all cabinets in a set: 32-33 */
memcpy(buf + 16, ctx->options->indata + 32, 2);
BIO_write(hash, buf + 4, 14);
/* u2 iCabinet - number of this cabinet file in a set: 34-35 */
BIO_write(outdata, ctx->options->indata + 34, 2);
memcpy(cabsigned + 8, buf, 4);
BIO_write(outdata, cabsigned, 20);
BIO_write(hash, cabsigned+20, 4);
i = cab_write_optional_names(outdata, ctx->options->indata, 36, flags);
/*
* (u8 * cFolders) CFFOLDER - structure contains information about
* one of the folders or partial folders stored in this cabinet file
*/
nfolders = GET_UINT16_LE(ctx->options->indata + 26);
while (nfolders) {
tmp = GET_UINT32_LE(ctx->options->indata + i);
tmp += 24;
PUT_UINT32_LE(tmp, buf);
BIO_write(hash, buf, 4);
BIO_write(hash, ctx->options->indata + i + 4, 4);
i += 8;
nfolders--;
}
OPENSSL_free(buf);
/* Write what's left - the compressed data bytes */
len = ctx->cab_ctx->fileend - i;
while (len > 0) {
if (!BIO_write_ex(hash, ctx->options->indata + i, len, &written))
return 0; /* FAILED */
len -= written;
i += written;
}
return 1; /* OK */
}
/*
* Check if the signature exists.
* [in, out] ctx: structure holds input and output data
* [returns] 0 on error or 1 on success
*/
static int cab_check_file(FILE_FORMAT_CTX *ctx)
{
if (!ctx) {
printf("Init error\n\n");
return 0; /* FAILED */
}
if (ctx->cab_ctx->header_size != 20) {
printf("No signature found\n\n");
return 0; /* FAILED */
}
if (ctx->cab_ctx->sigpos == 0 || ctx->cab_ctx->siglen == 0
|| ctx->cab_ctx->sigpos > ctx->cab_ctx->fileend) {
printf("No signature found\n\n");
return 0; /* FAILED */
}
return 1; /* OK */
}
/*
Local Variables:
c-basic-offset: 4
tab-width: 4
indent-tabs-mode: nil
End:
vim: set ts=4 expandtab:
*/
osslsigncode-2.8/cat.c 0000664 0000000 0000000 00000034344 14571175157 0015017 0 ustar 00root root 0000000 0000000 /*
* CAT file support library
*
* Copyright (C) 2021-2023 Micha┼В Trojnara
* Author: Ma┼Вgorzata Olsz├│wka
*
* Catalog files are a bit odd, in that they are only a PKCS7 blob.
* CAT files do not support nesting (multiple signature)
*/
#include "osslsigncode.h"
#include "helpers.h"
typedef struct {
ASN1_BMPSTRING *tag;
ASN1_INTEGER *flags;
ASN1_OCTET_STRING *value;
} CatNameValueContent;
DECLARE_ASN1_FUNCTIONS(CatNameValueContent)
ASN1_SEQUENCE(CatNameValueContent) = {
ASN1_SIMPLE(CatNameValueContent, tag, ASN1_BMPSTRING),
ASN1_SIMPLE(CatNameValueContent, flags, ASN1_INTEGER),
ASN1_SIMPLE(CatNameValueContent, value, ASN1_OCTET_STRING)
} ASN1_SEQUENCE_END(CatNameValueContent)
IMPLEMENT_ASN1_FUNCTIONS(CatNameValueContent)
struct cat_ctx_st {
uint32_t sigpos;
uint32_t siglen;
uint32_t fileend;
PKCS7 *p7;
};
/* FILE_FORMAT method prototypes */
static FILE_FORMAT_CTX *cat_ctx_new(GLOBAL_OPTIONS *options, BIO *hash, BIO *outdata);
static int cat_verify_digests(FILE_FORMAT_CTX *ctx, PKCS7 *p7);
static PKCS7 *cat_pkcs7_extract(FILE_FORMAT_CTX *ctx);
static PKCS7 *cat_pkcs7_signature_new(FILE_FORMAT_CTX *ctx, BIO *hash);
static int cat_append_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7);
static void cat_bio_free(BIO *hash, BIO *outdata);
static void cat_ctx_cleanup(FILE_FORMAT_CTX *ctx);
FILE_FORMAT file_format_cat = {
.ctx_new = cat_ctx_new,
.verify_digests = cat_verify_digests,
.pkcs7_extract = cat_pkcs7_extract,
.pkcs7_signature_new = cat_pkcs7_signature_new,
.append_pkcs7 = cat_append_pkcs7,
.bio_free = cat_bio_free,
.ctx_cleanup = cat_ctx_cleanup,
};
/* Prototypes */
static CAT_CTX *cat_ctx_get(char *indata, uint32_t filesize);
static int cat_add_ms_ctl_object(PKCS7 *p7);
static int cat_sign_ms_ctl_content(PKCS7 *p7, PKCS7 *contents);
static int cat_list_content(PKCS7 *p7);
static int cat_print_content_member_digest(ASN1_TYPE *content);
static int cat_print_content_member_name(ASN1_TYPE *content);
static void cat_print_base64(ASN1_OCTET_STRING *value);
static void cat_print_utf16_as_ascii(ASN1_OCTET_STRING *value);
static int cat_check_file(FILE_FORMAT_CTX *ctx);
/*
* FILE_FORMAT method definitions
*/
/*
* Allocate and return a CAT file format context.
* [in, out] options: structure holds the input data
* [out] hash: message digest BIO (unused)
* [in] outdata: outdata file BIO (unused)
* [returns] pointer to CAT file format context
*/
static FILE_FORMAT_CTX *cat_ctx_new(GLOBAL_OPTIONS *options, BIO *hash, BIO *outdata)
{
FILE_FORMAT_CTX *ctx;
CAT_CTX *cat_ctx;
uint32_t filesize;
if (options->cmd == CMD_REMOVE || options->cmd==CMD_ATTACH || options->cmd == CMD_EXTRACT_DATA) {
printf("Unsupported command\n");
return NULL; /* FAILED */
}
filesize = get_file_size(options->infile);
if (filesize == 0)
return NULL; /* FAILED */
options->indata = map_file(options->infile, filesize);
if (!options->indata) {
return NULL; /* FAILED */
}
cat_ctx = cat_ctx_get(options->indata, filesize);
if (!cat_ctx) {
unmap_file(options->indata, filesize);
return NULL; /* FAILED */
}
ctx = OPENSSL_malloc(sizeof(FILE_FORMAT_CTX));
ctx->format = &file_format_cat;
ctx->options = options;
ctx->cat_ctx = cat_ctx;
/* Push hash on outdata, if hash is NULL the function does nothing */
BIO_push(hash, outdata);
if (options->cmd == CMD_VERIFY)
printf("Warning: Use -catalog option to verify that a file, listed in catalog file, is signed\n");
if (options->jp >= 0)
printf("Warning: -jp option is only valid for CAB files\n");
if (options->pagehash == 1)
printf("Warning: -ph option is only valid for PE files\n");
if (options->add_msi_dse == 1)
printf("Warning: -add-msi-dse option is only valid for MSI files\n");
return ctx;
}
/*
* ContentInfo value is the inner content of pkcs7-signedData.
* An extra verification is not necessary when a content type data
* is the inner content of the signed-data type.
*/
static int cat_verify_digests(FILE_FORMAT_CTX *ctx, PKCS7 *p7)
{
/* squash unused parameter warnings */
(void)ctx;
(void)p7;
return 1; /* OK */
}
/*
* Extract existing signature in DER format.
* [in] ctx: structure holds input and output data
* [returns] pointer to PKCS#7 structure
*/
static PKCS7 *cat_pkcs7_extract(FILE_FORMAT_CTX *ctx)
{
if (!cat_check_file(ctx)) {
return NULL; /* FAILED */
}
return PKCS7_dup(ctx->cat_ctx->p7);
}
/*
* Create a new PKCS#7 signature.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO (unused)
* [returns] pointer to PKCS#7 structure
*/
static PKCS7 *cat_pkcs7_signature_new(FILE_FORMAT_CTX *ctx, BIO *hash)
{
PKCS7 *p7 = NULL;
/* squash unused parameter warnings */
(void)hash;
p7 = pkcs7_create(ctx);
if (!p7) {
printf("Creating a new signature failed\n");
return NULL; /* FAILED */
}
if (!cat_add_ms_ctl_object(p7)) {
printf("Adding MS_CTL_OBJID failed\n");
PKCS7_free(p7);
return NULL; /* FAILED */
}
if (!cat_sign_ms_ctl_content(p7, ctx->cat_ctx->p7->d.sign->contents)) {
printf("Failed to set signed content\n");
PKCS7_free(p7);
return 0; /* FAILED */
}
return p7; /* OK */
}
/*
* Append signature to the outfile.
* [in, out] ctx: structure holds input and output data
* [out] outdata: outdata file BIO
* [in] p7: PKCS#7 signature
* [returns] 1 on error or 0 on success
*/
static int cat_append_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7)
{
return data_write_pkcs7(ctx, outdata, p7);
}
/*
* Free up an entire message digest BIO chain.
* [out] hash: message digest BIO
* [out] outdata: outdata file BIO (unused)
* [returns] none
*/
static void cat_bio_free(BIO *hash, BIO *outdata)
{
/* squash the unused parameter warning */
(void)outdata;
BIO_free_all(hash);
}
/*
* Deallocate a FILE_FORMAT_CTX structure and CAT format specific structure,
* unmap indata file.
* [in, out] ctx: structure holds all input and output data
* [out] hash: message digest BIO
* [in] outdata: outdata file BIO
* [returns] none
*/
static void cat_ctx_cleanup(FILE_FORMAT_CTX *ctx)
{
unmap_file(ctx->options->indata, ctx->cat_ctx->fileend);
PKCS7_free(ctx->cat_ctx->p7);
OPENSSL_free(ctx->cat_ctx);
OPENSSL_free(ctx);
}
/*
* CAT helper functions
*/
/*
* Verify mapped PKCS#7 (CAT) file and create CAT format specific structure.
* [in] indata: mapped file
* [in] filesize: size of file
* [returns] pointer to CAT format specific structure
*/
static CAT_CTX *cat_ctx_get(char *indata, uint32_t filesize)
{
CAT_CTX *cat_ctx;
PKCS7 *p7;
p7 = pkcs7_read_data(indata, filesize);
if (!p7)
return NULL; /* FAILED */
if (!PKCS7_type_is_signed(p7)) {
PKCS7_free(p7);
return NULL; /* FAILED */
}
cat_ctx = OPENSSL_zalloc(sizeof(CAT_CTX));
cat_ctx->p7 = p7;
cat_ctx->sigpos = 0;
cat_ctx->siglen = filesize;
cat_ctx->fileend = filesize;
return cat_ctx; /* OK */
}
/*
* Add "1.3.6.1.4.1.311.10.1" MS_CTL_OBJID signed attribute
* [in, out] p7: new PKCS#7 signature
* [returns] 0 on error or 1 on success
*/
static int cat_add_ms_ctl_object(PKCS7 *p7)
{
STACK_OF(PKCS7_SIGNER_INFO) *signer_info;
PKCS7_SIGNER_INFO *si;
signer_info = PKCS7_get_signer_info(p7);
if (!signer_info)
return 0; /* FAILED */
si = sk_PKCS7_SIGNER_INFO_value(signer_info, 0);
if (!si)
return 0; /* FAILED */
if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType,
V_ASN1_OBJECT, OBJ_txt2obj(MS_CTL_OBJID, 1)))
return 0; /* FAILED */
return 1; /* OK */
}
/*
* Sign the MS CTL blob.
* Certificate Trust List (CTL) is a list of file names or thumbprints.
* All the items in this list are authenticated (approved) by the signing entity.
* [in, out] p7: new PKCS#7 signature
* [in] contents: Certificate Trust List (CTL)
* [returns] 0 on error or 1 on success
*/
static int cat_sign_ms_ctl_content(PKCS7 *p7, PKCS7 *contents)
{
u_char *content;
int seqhdrlen, content_length;
seqhdrlen = asn1_simple_hdr_len(contents->d.other->value.sequence->data,
contents->d.other->value.sequence->length);
content = contents->d.other->value.sequence->data + seqhdrlen;
content_length = contents->d.other->value.sequence->length - seqhdrlen;
if (!pkcs7_sign_content(p7, content, content_length)) {
printf("Failed to sign content\n");
return 0; /* FAILED */
}
if (!PKCS7_set_content(p7, PKCS7_dup(contents))) {
printf("PKCS7_set_content failed\n");
return 0; /* FAILED */
}
return 1; /* OK */
}
/*
* Print each member of the CAT file by using the "-verbose" option.
* [in, out] p7: catalog file to verify
* [returns] 1 on error or 0 on success
*/
static int cat_list_content(PKCS7 *p7)
{
MsCtlContent *ctlc;
int i;
ctlc = ms_ctl_content_get(p7);
if (!ctlc) {
printf("Failed to extract MS_CTL_OBJID data\n");
return 1; /* FAILED */
}
printf("\nCatalog members:\n");
for (i = 0; i < sk_CatalogInfo_num(ctlc->header_attributes); i++) {
int j, found = 0;
CatalogInfo *header_attr = sk_CatalogInfo_value(ctlc->header_attributes, i);
if (header_attr == NULL)
continue;
for (j = 0; j < sk_CatalogAuthAttr_num(header_attr->attributes); j++) {
char object_txt[128];
CatalogAuthAttr *attribute;
ASN1_TYPE *content;
attribute = sk_CatalogAuthAttr_value(header_attr->attributes, j);
if (!attribute)
continue;
content = catalog_content_get(attribute);
if (!content)
continue;
object_txt[0] = 0x00;
OBJ_obj2txt(object_txt, sizeof object_txt, attribute->type, 1);
if (!strcmp(object_txt, CAT_NAMEVALUE_OBJID)) {
/* CAT_NAMEVALUE_OBJID OID: 1.3.6.1.4.1.311.12.2.1 */
found |= cat_print_content_member_name(content);
} else if (!strcmp(object_txt, SPC_INDIRECT_DATA_OBJID)) {
/* SPC_INDIRECT_DATA_OBJID OID: 1.3.6.1.4.1.311.2.1.4 */
found |= cat_print_content_member_digest(content);
}
ASN1_TYPE_free(content);
}
if (found)
printf("\n");
}
MsCtlContent_free(ctlc);
ERR_print_errors_fp(stdout);
return 0; /* OK */
}
/*
* Print a hash algorithm and a message digest from the SPC_INDIRECT_DATA_OBJID attribute.
* [in] content: catalog file content
* [returns] 0 on error or 1 on success
*/
static int cat_print_content_member_digest(ASN1_TYPE *content)
{
SpcIndirectDataContent *idc;
u_char mdbuf[EVP_MAX_MD_SIZE];
const u_char *data ;
int mdtype = -1;
ASN1_STRING *value;
value = content->value.sequence;
data = ASN1_STRING_get0_data(value);
idc = d2i_SpcIndirectDataContent(NULL, &data, ASN1_STRING_length(value));
if (!idc)
return 0; /* FAILED */
if (idc->messageDigest && idc->messageDigest->digest && idc->messageDigest->digestAlgorithm) {
/* get a digest algorithm a message digest of the file from the content */
mdtype = OBJ_obj2nid(idc->messageDigest->digestAlgorithm->algorithm);
memcpy(mdbuf, idc->messageDigest->digest->data, (size_t)idc->messageDigest->digest->length);
}
SpcIndirectDataContent_free(idc);
if (mdtype == -1) {
printf("Failed to extract current message digest\n\n");
return 0; /* FAILED */
}
printf("\tHash algorithm: %s\n", OBJ_nid2sn(mdtype));
print_hash("\tMessage digest", "", mdbuf, EVP_MD_size(EVP_get_digestbynid(mdtype)));
return 1; /* OK */
}
/*
* Print a file name from the CAT_NAMEVALUE_OBJID attribute.
* [in] content: catalog file content
* [returns] 0 on error or 1 on success
*/
static int cat_print_content_member_name(ASN1_TYPE *content)
{
CatNameValueContent *nvc;
const u_char *data = NULL;
ASN1_STRING *value;
value = content->value.sequence;
data = ASN1_STRING_get0_data(value);
nvc = d2i_CatNameValueContent(NULL, &data, ASN1_STRING_length(value));
if (!nvc) {
return 0; /* FAILED */
}
printf("\tFile name: ");
if (ASN1_INTEGER_get(nvc->flags) & 0x00020000) {
cat_print_base64(nvc->value);
} else {
cat_print_utf16_as_ascii(nvc->value);
}
printf("\n");
CatNameValueContent_free(nvc);
return 1; /* OK */
}
/*
* Print a CAT_NAMEVALUE_OBJID attribute represented in base-64 encoding.
* [in] value: catalog member file name
* [returns] none
*/
static void cat_print_base64(ASN1_OCTET_STRING *value)
{
BIO *stdbio, *b64;
stdbio = BIO_new_fp(stdout, BIO_NOCLOSE);
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
stdbio = BIO_push(b64, stdbio);
ASN1_STRING_print_ex(stdbio, value, 0);
BIO_free_all(stdbio);
}
/*
* Print a CAT_NAMEVALUE_OBJID attribute represented in plaintext.
* [in] value: catalog member file name
* [returns] none
*/
static void cat_print_utf16_as_ascii(ASN1_OCTET_STRING *value)
{
const u_char *data;
int len, i;
data = ASN1_STRING_get0_data(value);
len = ASN1_STRING_length(value);
for (i = 0; i < len && (data[i] || data[i+1]); i+=2)
putchar(isprint(data[i]) && !data[i+1] ? data[i] : '.');
}
/*
* Check if the signature exists.
* [in, out] ctx: structure holds input and output data
* [returns] 0 on error or 1 on success
*/
static int cat_check_file(FILE_FORMAT_CTX *ctx)
{
STACK_OF(PKCS7_SIGNER_INFO) *signer_info;
PKCS7_SIGNER_INFO *si;
if (!ctx) {
printf("Init error\n\n");
return 0; /* FAILED */
}
signer_info = PKCS7_get_signer_info(ctx->cat_ctx->p7);
if (!signer_info) {
printf("Failed catalog file\n\n");
return 0; /* FAILED */
}
si = sk_PKCS7_SIGNER_INFO_value(signer_info, 0);
if (!si) {
printf("No signature found\n\n");
return 0; /* FAILED */
}
if (ctx->options->verbose) {
(void)cat_list_content(ctx->cat_ctx->p7);
}
return 1; /* OK */
}
/*
Local Variables:
c-basic-offset: 4
tab-width: 4
indent-tabs-mode: nil
End:
vim: set ts=4 expandtab:
*/
osslsigncode-2.8/cmake/ 0000775 0000000 0000000 00000000000 14571175157 0015154 5 ustar 00root root 0000000 0000000 osslsigncode-2.8/cmake/CMakeDist.cmake 0000664 0000000 0000000 00000002735 14571175157 0017771 0 ustar 00root root 0000000 0000000 # make dist
# cmake --build . --target package_source
set(CPACK_PACKAGE_NAME ${PROJECT_NAME})
set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION})
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "OpenSSL based Authenticode signing for PE, CAB, CAT and MSI files")
set(CPACK_PACKAGE_INSTALL_DIRECTORY ${CPACK_PACKAGE_NAME})
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/COPYING.txt")
set(CPACK_SOURCE_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}")
set(CPACK_SOURCE_GENERATOR "TGZ")
set(CPACK_SOURCE_IGNORE_FILES "\.git/;\.gitignore")
list(APPEND CPACK_SOURCE_IGNORE_FILES "Makefile")
list(APPEND CPACK_SOURCE_IGNORE_FILES "CMakeCache.txt")
list(APPEND CPACK_SOURCE_IGNORE_FILES "CMakeFiles")
list(APPEND CPACK_SOURCE_IGNORE_FILES "CPackConfig.cmake")
list(APPEND CPACK_SOURCE_IGNORE_FILES "CPackSourceConfig.cmake")
list(APPEND CPACK_SOURCE_IGNORE_FILES "CTestTestfile.cmake")
list(APPEND CPACK_SOURCE_IGNORE_FILES "cmake_install.cmake")
list(APPEND CPACK_SOURCE_IGNORE_FILES "config.h")
list(APPEND CPACK_SOURCE_IGNORE_FILES "/CMakeFiles/")
list(APPEND CPACK_SOURCE_IGNORE_FILES "/Testing/")
list(APPEND CPACK_SOURCE_IGNORE_FILES "/_CPack_Packages/")
list(APPEND CPACK_SOURCE_IGNORE_FILES "/build/")
include(CPack)
add_custom_target(dist COMMAND ${CMAKE_MAKE_PROGRAM} package_source)
#[[
Local Variables:
c-basic-offset: 4
tab-width: 4
indent-tabs-mode: nil
End:
vim: set ts=4 expandtab:
]]
osslsigncode-2.8/cmake/CMakeTest.cmake 0000664 0000000 0000000 00000065517 14571175157 0020014 0 ustar 00root root 0000000 0000000 # make test
# ctest -C Release
########## Configure ##########
option(STOP_SERVER "Stop HTTP server after tests" ON)
# Remove http proxy configuration that may change behavior
unset(ENV{HTTP_PROXY})
unset(ENV{http_proxy})
include(FindPython3)
set(TEST_DIR "${PROJECT_BINARY_DIR}/Testing")
file(COPY
"${CMAKE_CURRENT_SOURCE_DIR}/tests/files"
"${CMAKE_CURRENT_SOURCE_DIR}/tests/conf"
"${CMAKE_CURRENT_SOURCE_DIR}/tests/client_http.py"
DESTINATION "${TEST_DIR}/")
file(MAKE_DIRECTORY "${TEST_DIR}/logs")
set(FILES "${TEST_DIR}/files")
set(CERTS "${TEST_DIR}/certs")
set(CONF "${TEST_DIR}/conf")
set(LOGS "${TEST_DIR}/logs")
set(CLIENT_HTTP "${TEST_DIR}/client_http.py")
if(UNIX)
file(COPY
"${CMAKE_CURRENT_SOURCE_DIR}/tests/server_http.py"
DESTINATION "${TEST_DIR}/")
set(SERVER_HTTP "${TEST_DIR}/server_http.py")
else(UNIX)
file(COPY
"${CMAKE_CURRENT_SOURCE_DIR}/tests/server_http.pyw"
DESTINATION "${TEST_DIR}/")
set(SERVER_HTTP "${TEST_DIR}/server_http.pyw")
endif(UNIX)
file(COPY
"${CMAKE_CURRENT_SOURCE_DIR}/tests/certs/ca-bundle.crt"
DESTINATION "${CONF}")
if(WIN32 OR APPLE)
if(WIN32)
message(STATUS "Use pythonw to start HTTP server: \"pythonw.exe Testing\\server_http.pyw\"")
else(WIN32)
message(STATUS "Use python3 to start HTTP server: \"python3 Testing/server_http.py --port 19254\"")
endif(WIN32)
set(default_certs 1)
else(WIN32 OR APPLE)
if(Python3_FOUND)
if(EXISTS ${LOGS}/port.log)
# Stop HTTP server if running
message(STATUS "Try to kill HTTP server")
execute_process(
COMMAND ${Python3_EXECUTABLE} "${CLIENT_HTTP}"
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
OUTPUT_VARIABLE client_output
RESULT_VARIABLE client_result)
if(NOT client_result)
# Successfully closed
message(STATUS "${client_output}")
endif(NOT client_result)
endif(EXISTS ${LOGS}/port.log)
# Start Time Stamping Authority and CRL distribution point HTTP server
execute_process(
COMMAND ${Python3_EXECUTABLE} "${SERVER_HTTP}"
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
OUTPUT_FILE ${LOGS}/server.log
ERROR_FILE ${LOGS}/server.log
RESULT_VARIABLE server_error)
if(server_error)
message(STATUS "HTTP server failed: ${server_error}")
message(STATUS "Use python3 to start HTTP server: \"python3 Testing/server_http.py --port 19254\"")
set(default_certs 1)
else(server_error)
# Check if file exists and is no-empty
while(NOT EXISTS ${LOGS}/port.log)
execute_process(COMMAND sleep 1)
endwhile(NOT EXISTS ${LOGS}/port.log)
file(READ ${LOGS}/port.log PORT)
while(NOT PORT)
execute_process(COMMAND sleep 1)
file(READ ${LOGS}/port.log PORT)
endwhile(NOT PORT)
file(STRINGS ${LOGS}/server.log server_log)
message(STATUS "${server_log}")
# Generate new cTest certificates
if(NOT SED_EXECUTABLE)
find_program(SED_EXECUTABLE sed)
mark_as_advanced(SED_EXECUTABLE)
endif(NOT SED_EXECUTABLE)
execute_process(
COMMAND ${SED_EXECUTABLE}
-i.bak s/:19254/:${PORT}/ "${CONF}/openssl_intermediate_crldp.cnf"
COMMAND ${SED_EXECUTABLE}
-i.bak s/:19254/:${PORT}/ "${CONF}/openssl_tsa_root.cnf")
execute_process(
COMMAND "${CONF}/makecerts.sh"
WORKING_DIRECTORY ${CONF}
OUTPUT_VARIABLE makecerts_output
RESULT_VARIABLE default_certs)
message(STATUS "${makecerts_output}")
endif(server_error)
endif(Python3_FOUND)
endif(WIN32 OR APPLE)
# Copy the set of default certificates
if(default_certs)
message(STATUS "Default certificates used by cTest")
set(PORT 19254)
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests/certs"
DESTINATION "${TEST_DIR}")
endif(default_certs)
# Compute a SHA256 hash of the leaf certificate (in DER form)
execute_process(
COMMAND ${CMAKE_COMMAND} -E sha256sum "${CERTS}/cert.der"
OUTPUT_VARIABLE sha256sum)
string(SUBSTRING ${sha256sum} 0 64 leafhash)
########## Testing ##########
enable_testing()
set(extensions_all "exe" "ex_" "msi" "256appx" "512appx" "cat" "ps1" "psc1" "mof")
set(extensions_nocat "exe" "ex_" "msi" "256appx" "512appx" "ps1" "psc1" "mof")
set(extensions_nocatappx "exe" "ex_" "msi" "ps1" "psc1" "mof")
set(formats "pem" "der")
# Test 1
# Print osslsigncode version
add_test(NAME version
COMMAND osslsigncode --version)
### Sign ###
# Tests 2-7
# Sign with PKCS#12 container with legacy RC2-40-CBC private key and certificate encryption algorithm
foreach(ext ${extensions_all})
add_test(
NAME legacy_${ext}
COMMAND osslsigncode "sign"
"-pkcs12" "${CERTS}/legacy.p12"
"-readpass" "${CERTS}/password.txt"
"-ac" "${CERTS}/CAcross.pem"
"-time" "1556668800" # Signing time: May 1 00:00:00 2019 GMT
"-add-msi-dse"
"-comm"
"-ph"
"-jp" "low"
"-h" "sha512" "-i" "https://www.osslsigncode.com/"
"-n" "osslsigncode"
"-in" "${FILES}/unsigned.${ext}"
"-out" "${FILES}/legacy.${ext}")
endforeach(ext ${extensions_all})
# Tests 8-13
# Sign with PKCS#12 container with legacy RC2-40-CBC private key and certificate encryption algorithm
# Disable legacy mode and don't automatically load the legacy provider
# Option "-nolegacy" requires OpenSSL 3.0.0 or later
# This tests are expected to fail
if(OPENSSL_VERSION VERSION_GREATER_EQUAL 3.0.0)
foreach(ext ${extensions_all})
add_test(
NAME nolegacy_${ext}
COMMAND osslsigncode "sign"
"-pkcs12" "${CERTS}/legacy.p12"
"-readpass" "${CERTS}/password.txt"
"-nolegacy" # Disable legacy mode
"-ac" "${CERTS}/CAcross.pem"
"-time" "1556668800" # Signing time: May 1 00:00:00 2019 GMT
"-add-msi-dse"
"-comm"
"-ph"
"-jp" "low"
"-h" "sha512" "-i" "https://www.osslsigncode.com/"
"-n" "osslsigncode"
"-in" "${FILES}/unsigned.${ext}"
"-out" "${FILES}/nolegacy.${ext}")
set_tests_properties(
nolegacy_${ext}
PROPERTIES
WILL_FAIL TRUE)
endforeach(ext ${extensions_all})
endif(OPENSSL_VERSION VERSION_GREATER_EQUAL 3.0.0)
# Tests 14-19
# Sign with PKCS#12 container with AES-256-CBC private key and certificate encryption algorithm
foreach(ext ${extensions_all})
add_test(
NAME signed_${ext}
COMMAND osslsigncode "sign"
"-pkcs12" "${CERTS}/cert.p12"
"-readpass" "${CERTS}/password.txt"
"-ac" "${CERTS}/CAcross.pem"
"-time" "1556668800" # Signing time: May 1 00:00:00 2019 GMT
"-add-msi-dse"
"-comm"
"-ph"
"-jp" "low"
"-h" "sha512" "-i" "https://www.osslsigncode.com/"
"-n" "osslsigncode"
"-in" "${FILES}/unsigned.${ext}"
"-out" "${FILES}/signed.${ext}")
endforeach(ext ${extensions_all})
# Tests 20-25
# Sign with revoked certificate
foreach(ext ${extensions_all})
add_test(
NAME revoked_${ext}
COMMAND osslsigncode "sign"
"-certs" "${CERTS}/revoked.pem"
"-key" "${CERTS}/keyp.pem"
"-readpass" "${CERTS}/password.txt"
"-ac" "${CERTS}/CAcross.pem"
"-time" "1556668800" # Signing time: May 1 00:00:00 2019 GMT
"-add-msi-dse"
"-comm"
"-ph"
"-jp" "low"
"-h" "sha512" "-i" "https://www.osslsigncode.com/"
"-n" "osslsigncode"
"-in" "${FILES}/unsigned.${ext}"
"-out" "${FILES}/revoked.${ext}")
endforeach(ext ${extensions_all})
# Tests 26-30
# Remove signature
# Unsupported command for CAT files
foreach(ext ${extensions_nocat})
add_test(
NAME removed_${ext}
COMMAND osslsigncode "remove-signature"
"-in" "${FILES}/signed.${ext}"
"-out" "${FILES}/removed.${ext}")
set_tests_properties(
removed_${ext}
PROPERTIES
DEPENDS "signed_${ext}"
REQUIRED_FILES "${FILES}/signed.${ext}")
endforeach(ext ${extensions_nocat})
# Tests 31-36
# Extract PKCS#7 signature in PEM format
foreach(ext ${extensions_all})
add_test(
NAME extract_pem_${ext}
COMMAND osslsigncode "extract-signature"
"-pem" # PEM format
"-in" "${FILES}/signed.${ext}"
"-out" "${FILES}/${ext}.pem")
set_tests_properties(
extract_pem_${ext}
PROPERTIES
DEPENDS "signed_${ext}"
REQUIRED_FILES "${FILES}/signed.${ext}")
endforeach(ext ${extensions_all})
# Tests 37-42
# Extract PKCS#7 signature in default DER format
foreach(ext ${extensions_all})
add_test(
NAME extract_der_${ext}
COMMAND osslsigncode "extract-signature"
"-in" "${FILES}/signed.${ext}"
"-out" "${FILES}/${ext}.der")
set_tests_properties(
extract_der_${ext}
PROPERTIES
DEPENDS "signed_${ext}"
REQUIRED_FILES "${FILES}/signed.${ext}")
endforeach(ext ${extensions_all})
# Tests 43-52
# Attach a nested signature in PEM or DER format
# Unsupported command for CAT files
foreach(ext ${extensions_nocat})
foreach(format ${formats})
add_test(
NAME attached_${format}_${ext}
COMMAND osslsigncode "attach-signature"
# sign options
"-require-leaf-hash" "SHA256:${leafhash}"
"-add-msi-dse"
"-h" "sha512"
"-nest"
"-sigin" "${FILES}/${ext}.${format}"
"-in" "${FILES}/signed.${ext}"
"-out" "${FILES}/attached_${format}.${ext}"
# verify options
"-time" "1567296000" # Signature verification time: Sep 1 00:00:00 2019 GMT
"-CAfile" "${CERTS}/CACert.pem"
"-CRLfile" "${CERTS}/CACertCRL.pem")
set_tests_properties(
attached_${format}_${ext}
PROPERTIES
DEPENDS "signed_${ext}:extract_${format}_${ext}"
REQUIRED_FILES "${FILES}/signed.${ext}"
REQUIRED_FILES "${FILES}/${ext}.${format}")
endforeach(format ${formats})
endforeach(ext ${extensions_nocat})
# Tests 53-58
# Add an unauthenticated blob to a previously-signed file
foreach(ext ${extensions_all})
add_test(
NAME added_${ext}
COMMAND osslsigncode "add"
"-addUnauthenticatedBlob"
"-add-msi-dse" "-h" "sha512"
"-in" "${FILES}/signed.${ext}"
"-out" "${FILES}/added.${ext}")
set_tests_properties(
added_${ext}
PROPERTIES
DEPENDS "signed_${ext}"
REQUIRED_FILES "${FILES}/signed.${ext}")
endforeach(ext ${extensions_all})
# Tests 59-64
# Add the new nested signature instead of replacing the first one
# APPX files do not support nesting (multiple signature)
foreach(ext ${extensions_all})
add_test(
NAME nested_${ext}
COMMAND osslsigncode "sign"
"-nest"
"-certs" "${CERTS}/cert.pem"
"-key" "${CERTS}/key.der"
"-pass" "passme"
"-ac" "${CERTS}/CAcross.pem"
"-time" "1556755200" # Signing time: May 2 00:00:00 2019 GMT
"-add-msi-dse"
"-comm"
"-ph"
"-jp" "low"
"-h" "sha512"
"-i" "https://www.osslsigncode.com/"
"-n" "osslsigncode"
"-in" "${FILES}/signed.${ext}"
"-out" "${FILES}/nested.${ext}")
set_tests_properties(
nested_${ext}
PROPERTIES
DEPENDS "signed_${ext}"
REQUIRED_FILES "${FILES}/signed.${ext}")
endforeach(ext ${extensions_all})
### Verify signature ###
# Tests 65-67
# Verify PE/MSI/CAB files signed in the catalog file
# CAT and APPX files do not support detached PKCS#7 signature
foreach(ext ${extensions_nocatappx})
add_test(
NAME verify_catalog_${ext}
COMMAND osslsigncode "verify"
"-catalog" "${FILES}/signed.cat" # catalog file
"-time" "1567296000" # Signature verification time: Sep 1 00:00:00 2019 GMT
"-require-leaf-hash" "SHA256:${leafhash}"
"-CAfile" "${CERTS}/CACert.pem"
"-CRLfile" "${CERTS}/CACertCRL.pem"
"-in" "${FILES}/unsigned.${ext}")
set_tests_properties(
verify_catalog_${ext}
PROPERTIES
DEPENDS "signed_${ext}"
REQUIRED_FILES "${FILES}/signed.cat"
REQUIRED_FILES "${FILES}/unsigned.${ext}")
endforeach(ext ${extensions_nocatappx})
# Tests 68-97
# Verify signature
set(files "legacy" "signed" "nested" "added" "revoked")
foreach(file ${files})
foreach(ext ${extensions_all})
add_test(
NAME verify_${file}_${ext}
COMMAND osslsigncode "verify"
"-time" "1567296000" # Signature verification time: Sep 1 00:00:00 2019 GMT
"-CAfile" "${CERTS}/CACert.pem"
"-CRLfile" "${CERTS}/CACertCRL.pem"
"-in" "${FILES}/${file}.${ext}")
set_tests_properties(
verify_${file}_${ext}
PROPERTIES
DEPENDS "${file}_${ext}"
REQUIRED_FILES "${FILES}/${file}.${ext}")
endforeach(ext ${extensions_all})
endforeach(file ${files})
# "revoked" tests are expected to fail
set(files "revoked")
foreach(file ${files})
foreach(ext ${extensions_all})
set_tests_properties(
verify_${file}_${ext}
PROPERTIES
WILL_FAIL TRUE)
endforeach(ext ${extensions_all})
endforeach(file ${files})
# Tests 98-102
# Verify removed signature
# "removed" tests are expected to fail
# "remove-signature" command is unsupported for CAT files
set(files "removed")
foreach(file ${files})
foreach(ext ${extensions_nocat})
add_test(
NAME verify_${file}_${ext}
COMMAND osslsigncode "verify"
"-time" "1567296000" # Signature verification time: Sep 1 00:00:00 2019 GMT
"-CAfile" "${CERTS}/CACert.pem"
"-CRLfile" "${CERTS}/CACertCRL.pem"
"-in" "${FILES}/${file}.${ext}")
set_tests_properties(
verify_${file}_${ext}
PROPERTIES
DEPENDS "${file}_${ext}"
REQUIRED_FILES "${FILES}/${file}.${ext}"
WILL_FAIL TRUE)
endforeach(ext ${extensions_nocat})
endforeach(file ${files})
# Tests 103-112
# Verify attached signature
# "attach-signature" command is unsupported for CAT files
set(files "attached_pem" "attached_der")
foreach(file ${files})
foreach(ext ${extensions_nocat})
add_test(
NAME verify_${file}_${ext}
COMMAND osslsigncode "verify"
"-time" "1567296000" # Signature verification time: Sep 1 00:00:00 2019 GMT
"-CAfile" "${CERTS}/CACert.pem"
"-CRLfile" "${CERTS}/CACertCRL.pem"
"-in" "${FILES}/${file}.${ext}")
set_tests_properties(
verify_${file}_${ext}
PROPERTIES
DEPENDS "${file}_${ext}"
REQUIRED_FILES "${FILES}/${file}.${ext}")
endforeach(ext ${extensions_nocat})
endforeach(file ${files})
if((Python3_FOUND OR server_error) AND CURL_FOUND)
### Sign with Time-Stamp Authority ###
# Tests 113-142
# Sign with the RFC3161 Time-Stamp Authority
# Use "cert" "expired" "revoked" without X509v3 CRL Distribution Points extension
# and "cert_crldp" "revoked_crldp" contain X509v3 CRL Distribution Points extension
set(pem_certs "cert" "expired" "revoked" "cert_crldp" "revoked_crldp")
foreach(ext ${extensions_all})
foreach(cert ${pem_certs})
add_test(
NAME sign_ts_${cert}_${ext}
COMMAND osslsigncode "sign"
"-certs" "${CERTS}/${cert}.pem"
"-key" "${CERTS}/key.pem"
"-ac" "${CERTS}/CAcross.pem"
"-comm"
"-ph"
"-jp" "low"
"-h" "sha384"
"-i" "https://www.osslsigncode.com/"
"-n" "osslsigncode"
"-time" "1556668800" # Signing time: May 1 00:00:00 2019 GMT
"-ts" "http://127.0.0.1:${PORT}"
"-in" "${FILES}/unsigned.${ext}"
"-out" "${FILES}/ts_${cert}.${ext}")
set_tests_properties(
sign_ts_${cert}_${ext}
PROPERTIES
ENVIRONMENT "HTTP_PROXY=;http_proxy=;"
REQUIRED_FILES "${LOGS}/port.log")
endforeach(cert ${pem_certs})
endforeach(ext ${extensions_all})
### Verify Time-Stamp Authority ###
# Tests 143-148
# Signature verification time: Sep 1 00:00:00 2019 GMT
foreach(ext ${extensions_all})
add_test(
NAME verify_ts_cert_${ext}
COMMAND osslsigncode "verify"
"-time" "1567296000" # Signature verification time: Sep 1 00:00:00 2019 GMT
"-CAfile" "${CERTS}/CACert.pem"
"-TSA-CAfile" "${CERTS}/TSACA.pem"
"-in" "${FILES}/ts_cert.${ext}")
set_tests_properties(
verify_ts_cert_${ext}
PROPERTIES
ENVIRONMENT "HTTP_PROXY=;http_proxy=;"
DEPENDS "sign_ts_cert_${ext}"
REQUIRED_FILES "${FILES}/ts_cert.${ext}"
REQUIRED_FILES "${LOGS}/port.log")
endforeach(ext ${extensions_all})
# Tests 149-154
# Signature verification time: Jan 1 00:00:00 2035 GMT
foreach(ext ${extensions_all})
add_test(
NAME verify_ts_future_${ext}
COMMAND osslsigncode "verify"
"-time" "2051222400" # Signature verification time: Jan 1 00:00:00 2035 GMT
"-CAfile" "${CERTS}/CACert.pem"
"-TSA-CAfile" "${CERTS}/TSACA.pem"
"-in" "${FILES}/ts_cert.${ext}")
set_tests_properties(
verify_ts_future_${ext}
PROPERTIES
ENVIRONMENT "HTTP_PROXY=;http_proxy=;"
DEPENDS "sign_ts_cert_${ext}"
REQUIRED_FILES "${FILES}/ts_cert.${ext}"
REQUIRED_FILES "${LOGS}/port.log")
endforeach(ext ${extensions_all})
# Tests 155-160
# Verify with ignored timestamp
# This tests are expected to fail
foreach(ext ${extensions_all})
add_test(
NAME verify_ts_ignore_${ext}
COMMAND osslsigncode "verify"
"-time" "2051222400" # Signature verification time: Jan 1 00:00:00 2035 GMT
"-ignore-timestamp"
"-CAfile" "${CERTS}/CACert.pem"
"-TSA-CAfile" "${CERTS}/TSACA.pem"
"-in" "${FILES}/ts_cert.${ext}")
set_tests_properties(
verify_ts_ignore_${ext}
PROPERTIES
ENVIRONMENT "HTTP_PROXY=;http_proxy=;"
DEPENDS "sign_ts_cert_${ext}"
REQUIRED_FILES "${FILES}/ts_cert.${ext}"
REQUIRED_FILES "${LOGS}/port.log"
WILL_FAIL TRUE)
endforeach(ext ${extensions_all})
### Verify CRL Distribution Points ###
# Tests 161-166
# Verify file signed with X509v3 CRL Distribution Points extension
# Signature verification time: Sep 1 00:00:00 2019 GMT
# Check X509v3 CRL Distribution Points extension, don't use "-CRLfile" and "-TSA-CRLfile" options
foreach(ext ${extensions_all})
add_test(
NAME verify_ts_cert_crldp_${ext}
COMMAND osslsigncode "verify"
"-time" "1567296000" # Signature verification time: Sep 1 00:00:00 2019 GMT
"-CAfile" "${CERTS}/CACert.pem"
"-TSA-CAfile" "${CERTS}/TSACA.pem"
"-in" "${FILES}/ts_cert_crldp.${ext}")
set_tests_properties(
verify_ts_cert_crldp_${ext}
PROPERTIES
ENVIRONMENT "HTTP_PROXY=;http_proxy=;"
DEPENDS "sign_ts_cert_crldp_${ext}"
REQUIRED_FILES "${FILES}/ts_cert_crldp.${ext}"
REQUIRED_FILES "${LOGS}/port.log")
endforeach(ext ${extensions_all})
# Tests 167-183
# Verify with expired or revoked certificate without X509v3 CRL Distribution Points extension
# This tests are expected to fail
set(failed_certs "expired" "revoked")
foreach(ext ${extensions_all})
foreach(cert ${failed_certs})
add_test(
NAME verify_ts_${cert}_${ext}
COMMAND osslsigncode "verify"
"-time" "1567296000" # Signature verification time: Sep 1 00:00:00 2019 GMT
"-CAfile" "${CERTS}/CACert.pem"
"-CRLfile" "${CERTS}/CACertCRL.pem"
"-TSA-CAfile" "${CERTS}/TSACA.pem"
"-in" "${FILES}/ts_${cert}.${ext}")
set_tests_properties(
verify_ts_${cert}_${ext}
PROPERTIES
ENVIRONMENT "HTTP_PROXY=;http_proxy=;"
DEPENDS "sign_ts_${cert}_${ext}"
REQUIRED_FILES "${FILES}/ts_${cert}.${ext}"
REQUIRED_FILES "${LOGS}/port.log"
WILL_FAIL TRUE)
endforeach(cert ${failed_certs})
endforeach(ext ${extensions_all})
# Tests 178-184
# Verify with revoked certificate contains X509v3 CRL Distribution Points extension
# Check X509v3 CRL Distribution Points extension, don't use "-CRLfile" and "-TSA-CRLfile" options
# This test is expected to fail
foreach(ext ${extensions_all})
add_test(
NAME verify_ts_revoked_crldp_${ext}
COMMAND osslsigncode "verify"
"-time" "1567296000" # Signature verification time: Sep 1 00:00:00 2019 GMT
"-CAfile" "${CERTS}/CACert.pem"
"-TSA-CAfile" "${CERTS}/TSACA.pem"
"-in" "${FILES}/ts_revoked_crldp.${ext}")
set_tests_properties(
verify_ts_revoked_crldp_${ext}
PROPERTIES
ENVIRONMENT "HTTP_PROXY=;http_proxy=;"
DEPENDS "sign_ts_revoked_crldp_${ext}"
REQUIRED_FILES "${FILES}/ts_revoked_crldp.${ext}"
REQUIRED_FILES "${LOGS}/port.log"
WILL_FAIL TRUE)
endforeach(ext ${extensions_all})
# Tests 185-234
# Unsupported command "extract-data" for CAT files
foreach(ext ${extensions_nocat})
# Extract PKCS#7 with data content, output in PEM format
add_test(
NAME data_${ext}_pem
COMMAND osslsigncode "extract-data"
"-ph"
"-h" "sha384"
"-add-msi-dse"
"-pem" # PEM format
"-in" "${FILES}/unsigned.${ext}"
"-out" "${FILES}/data_${ext}.pem")
# Extract PKCS#7 with data content, output in default DER format
add_test(
NAME data_${ext}_der
COMMAND osslsigncode "extract-data"
"-ph"
"-h" "sha384"
"-add-msi-dse"
"-in" "${FILES}/unsigned.${ext}"
"-out" "${FILES}/data_${ext}.der")
# Sign a data content, output in DER format
foreach(data_format ${formats})
add_test(
NAME signed_data_${ext}_${data_format}
COMMAND osslsigncode "sign"
"-pkcs12" "${CERTS}/cert.p12"
"-readpass" "${CERTS}/password.txt"
"-ac" "${CERTS}/CAcross.pem"
"-time" "1556668800" # Signing time: May 1 00:00:00 2019 GMT
"-add-msi-dse"
"-comm"
"-ph"
"-jp" "low"
"-h" "sha384" "-i" "https://www.osslsigncode.com/"
"-n" "osslsigncode"
"-in" "${FILES}/data_${ext}.${data_format}"
"-out" "${FILES}/signed_data_${ext}_${data_format}.der")
endforeach(data_format ${formats})
# Sign a data content, output in PEM format
foreach(data_format ${formats})
add_test(
NAME signed_data_pem_${ext}_${data_format}
COMMAND osslsigncode "sign"
"-pkcs12" "${CERTS}/cert.p12"
"-readpass" "${CERTS}/password.txt"
"-ac" "${CERTS}/CAcross.pem"
"-time" "1556668800" # Signing time: May 1 00:00:00 2019 GMT
"-add-msi-dse"
"-comm"
"-ph"
"-jp" "low"
"-h" "sha384" "-i" "https://www.osslsigncode.com/"
"-n" "osslsigncode"
"-pem" # PEM format
"-in" "${FILES}/data_${ext}.${data_format}"
"-out" "${FILES}/signed_data_${ext}_${data_format}.pem")
endforeach(data_format ${formats})
# Attach signature in PEM or DER format
foreach(data_format ${formats})
foreach(format ${formats})
add_test(
NAME attached_data_${ext}_${data_format}_${format}
COMMAND osslsigncode "attach-signature"
# sign options
"-require-leaf-hash" "SHA256:${leafhash}"
"-add-msi-dse"
"-h" "sha384"
"-sigin" "${FILES}/signed_data_${ext}_${data_format}.${format}"
"-in" "${FILES}/unsigned.${ext}"
"-out" "${FILES}/attached_data_${data_format}_${format}.${ext}"
# verify options
"-time" "1567296000" # Signature verification time: Sep 1 00:00:00 2019 GMT
"-CAfile" "${CERTS}/CACert.pem"
"-CRLfile" "${CERTS}/CACertCRL.pem")
set_tests_properties(
attached_${format}_${ext}
PROPERTIES
DEPENDS "signed_data_${ext}_${data_format}:data_${ext}_${format}")
endforeach(format ${formats})
endforeach(data_format ${formats})
endforeach(ext ${extensions_nocat})
### Cleanup ###
# Stop HTTP server
if(STOP_SERVER)
add_test(NAME stop_server
COMMAND ${Python3_EXECUTABLE} "${CLIENT_HTTP}")
set_tests_properties(
stop_server
PROPERTIES
REQUIRED_FILES "${LOGS}/port.log")
else(STOP_SERVER)
message(STATUS "Keep HTTP server after tests")
endif(STOP_SERVER)
else((Python3_FOUND OR server_error) AND CURL_FOUND)
message(STATUS "CTest skips some tests")
endif((Python3_FOUND OR server_error) AND CURL_FOUND)
# Delete test files
set(names "legacy" "signed" "signed_crldp" "nested" "revoked" "removed" "added")
foreach(ext ${extensions_all})
foreach(name ${names})
set(OUTPUT_FILES ${OUTPUT_FILES} "${FILES}/${name}.${ext}")
endforeach(name ${names})
foreach(cert ${pem_certs})
set(OUTPUT_FILES ${OUTPUT_FILES} "${FILES}/ts_${cert}.${ext}")
endforeach(cert ${pem_certs})
foreach(format ${formats})
set(OUTPUT_FILES ${OUTPUT_FILES} "${FILES}/${ext}.${format}")
set(OUTPUT_FILES ${OUTPUT_FILES} "${FILES}/${ext}.${format}")
set(OUTPUT_FILES ${OUTPUT_FILES} "${FILES}/attached_${format}.${ext}")
set(OUTPUT_FILES ${OUTPUT_FILES} "${FILES}/data_${ext}.${format}")
foreach(data_format ${formats})
set(OUTPUT_FILES ${OUTPUT_FILES} "${FILES}/signed_data_${ext}_${format}.${data_format}")
set(OUTPUT_FILES ${OUTPUT_FILES} "${FILES}/attached_data_${data_format}_${format}.${ext}")
endforeach(data_format ${formats})
endforeach(format ${formats})
set(OUTPUT_FILES ${OUTPUT_FILES} "${FILES}/jreq.tsq")
set(OUTPUT_FILES ${OUTPUT_FILES} "${FILES}/jresp.tsr")
endforeach(ext ${extensions_all})
add_test(NAME remove_files
COMMAND ${CMAKE_COMMAND} -E rm -f ${OUTPUT_FILES})
#[[
Local Variables:
c-basic-offset: 4
tab-width: 4
indent-tabs-mode: nil
End:
vim: set ts=4 expandtab:
]]
osslsigncode-2.8/cmake/FindHeaders.cmake 0000664 0000000 0000000 00000001235 14571175157 0020333 0 ustar 00root root 0000000 0000000 include(CheckIncludeFile)
include(CheckFunctionExists)
if(UNIX)
check_function_exists(getpass HAVE_GETPASS)
check_include_file(termios.h HAVE_TERMIOS_H)
check_include_file(sys/mman.h HAVE_SYS_MMAN_H)
if(HAVE_SYS_MMAN_H)
check_function_exists(mmap HAVE_MMAP)
endif(HAVE_SYS_MMAN_H)
else(UNIX)
check_include_file(windows.h HAVE_MAPVIEWOFFILE)
endif(UNIX)
if(NOT (HAVE_MMAP OR HAVE_MAPVIEWOFFILE))
message(FATAL_ERROR "Error: Need file mapping function to build.")
endif(NOT (HAVE_MMAP OR HAVE_MAPVIEWOFFILE))
#[[
Local Variables:
c-basic-offset: 4
tab-width: 4
indent-tabs-mode: nil
End:
vim: set ts=4 expandtab:
]]
osslsigncode-2.8/cmake/SetBashCompletion.cmake 0000664 0000000 0000000 00000002357 14571175157 0021550 0 ustar 00root root 0000000 0000000 # This list describes the default variables included in the bash-completion package:
# BASH_COMPLETION_VERSION "@VERSION@"
# BASH_COMPLETION_PREFIX "@prefix@"
# BASH_COMPLETION_COMPATDIR "@sysconfdir@/bash_completion.d"
# BASH_COMPLETION_COMPLETIONSDIR "@datadir@/@PACKAGE@/completions"
# BASH_COMPLETION_HELPERSDIR "@datadir@/@PACKAGE@/helpers"
# BASH_COMPLETION_FOUND "TRUE"
# https://github.com/scop/bash-completion/blob/master/bash-completion-config.cmake.in
if(NOT MSVC)
if(BASH_COMPLETION_USER_DIR)
set(BASH_COMPLETION_COMPLETIONSDIR "${BASH_COMPLETION_USER_DIR}/bash-completion/completions")
else(BASH_COMPLETION_USER_DIR)
find_package(bash-completion QUIET)
if(NOT BASH_COMPLETION_FOUND)
set(SHAREDIR "${CMAKE_INSTALL_PREFIX}/share")
set(BASH_COMPLETION_COMPLETIONSDIR "${SHAREDIR}/bash-completion/completions")
endif(NOT BASH_COMPLETION_FOUND)
endif(BASH_COMPLETION_USER_DIR)
message(STATUS "Using bash completions dir ${BASH_COMPLETION_COMPLETIONSDIR}")
install(FILES "osslsigncode.bash" DESTINATION ${BASH_COMPLETION_COMPLETIONSDIR})
endif(NOT MSVC)
#[[
Local Variables:
c-basic-offset: 4
tab-width: 4
indent-tabs-mode: nil
End:
vim: set ts=4 expandtab:
]]
osslsigncode-2.8/cmake/SetCompilerFlags.cmake 0000664 0000000 0000000 00000012114 14571175157 0021360 0 ustar 00root root 0000000 0000000 include(CheckCCompilerFlag)
set(CMAKE_REQUIRED_QUIET ON)
function(add_debug_flag_if_supported flagname targets)
check_c_compiler_flag("${flagname}" HAVE_FLAG_${flagname})
if (HAVE_FLAG_${flagname})
foreach(target ${targets})
target_compile_options(${target} PRIVATE $<$:${flagname}>)
endforeach(target ${targets})
endif(HAVE_FLAG_${flagname})
endfunction(add_debug_flag_if_supported flagname targets)
function(add_compile_flag_to_targets targets)
set(CHECKED_DEBUG_FLAGS
"-ggdb"
"-g"
"-O2"
"-pedantic"
"-Wall"
"-Wextra"
"-Wno-long-long"
"-Wconversion"
"-D_FORTIFY_SOURCE=2"
"-Wformat=2"
"-Wredundant-decls"
"-Wcast-qual"
"-Wnull-dereference"
"-Wno-deprecated-declarations"
"-Wmissing-declarations"
"-Wmissing-prototypes"
"-Wmissing-noreturn"
"-Wmissing-braces"
"-Wparentheses"
"-Wstrict-aliasing=3"
"-Wstrict-overflow=2"
"-Wlogical-op"
"-Wwrite-strings"
"-Wcast-align=strict"
"-Wdisabled-optimization"
"-Wshift-overflow=2"
"-Wundef"
"-Wshadow"
"-Wmisleading-indentation"
"-Wabsolute-value"
"-Wunused-parameter"
"-Wunused-function")
foreach(flag ${CHECKED_DEBUG_FLAGS})
add_debug_flag_if_supported(${flag} ${targets})
endforeach(flag ${CHECKED_DEBUG_FLAGS})
endfunction(add_compile_flag_to_targets targets)
function(add_compile_flags target)
if(MSVC)
# Enable parallel builds
target_compile_options(${target} PRIVATE /MP)
# Use address space layout randomization, generate PIE code for ASLR (default on)
target_link_options(${target} PRIVATE /DYNAMICBASE)
# Create terminal server aware application (default on)
target_link_options(${target} PRIVATE /TSAWARE)
# Mark the binary as compatible with Intel Control-flow Enforcement Technology (CET) Shadow Stack
target_link_options(${target} PRIVATE /CETCOMPAT)
# Enable compiler generation of Control Flow Guard security checks
target_compile_options(${target} PRIVATE /guard:cf)
target_link_options(${target} PRIVATE /guard:cf)
# Buffer Security Check
target_compile_options(${target} PRIVATE /GS)
# Suppress startup banner
target_link_options(${target} PRIVATE /NOLOGO)
# Generate debug info
target_link_options(${target} PRIVATE /DEBUG)
if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "8")
# High entropy ASLR for 64 bits targets (default on)
target_link_options(${target} PRIVATE /HIGHENTROPYVA)
# Enable generation of EH Continuation (EHCONT) metadata by the compiler
#target_compile_options(${target} PRIVATE /guard:ehcont)
#target_link_options(${target} PRIVATE /guard:ehcont)
else("${CMAKE_SIZEOF_VOID_P}" STREQUAL "8")
# Can handle addresses larger than 2 gigabytes
target_link_options(${target} PRIVATE /LARGEADDRESSAWARE)
# Safe structured exception handlers (x86 only)
target_link_options(${target} PRIVATE /SAFESEH)
endif("${CMAKE_SIZEOF_VOID_P}" STREQUAL "8")
target_compile_options(${target} PRIVATE $<$:/D_FORTIFY_SOURCE=2>)
# Unrecognized compiler options are errors
target_compile_options(${target} PRIVATE $<$:/options:strict>)
else(MSVC)
check_c_compiler_flag("-fstack-protector-all" HAVE_STACK_PROTECTOR_ALL)
if(HAVE_STACK_PROTECTOR_ALL)
target_link_options(${target} PRIVATE -fstack-protector-all)
else(HAVE_STACK_PROTECTOR_ALL)
check_c_compiler_flag("-fstack-protector" HAVE_STACK_PROTECTOR)
if(HAVE_STACK_PROTECTOR)
target_link_options(${target} PRIVATE -fstack-protector)
else(HAVE_STACK_PROTECTOR)
message(WARNING "No stack protection supported")
endif(HAVE_STACK_PROTECTOR)
endif(HAVE_STACK_PROTECTOR_ALL)
# Support address space layout randomization (ASLR)
if(NOT (MINGW OR CYGWIN OR CMAKE_C_COMPILER_ID STREQUAL "AppleClang"
OR ((CMAKE_SYSTEM_NAME MATCHES Darwin) AND (CMAKE_C_COMPILER_ID MATCHES Clang))))
target_compile_options(${target} PRIVATE -fPIE)
target_link_options(${target} PRIVATE -fPIE -pie)
target_link_options(${target} PRIVATE -Wl,-z,relro)
target_link_options(${target} PRIVATE -Wl,-z,now)
target_link_options(${target} PRIVATE -Wl,-z,noexecstack)
endif(NOT (MINGW OR CYGWIN OR CMAKE_C_COMPILER_ID STREQUAL "AppleClang"
OR ((CMAKE_SYSTEM_NAME MATCHES Darwin) AND (CMAKE_C_COMPILER_ID MATCHES Clang))))
target_link_options(${target} PRIVATE -fstack-check)
add_compile_flag_to_targets(${target})
endif(MSVC)
endfunction(add_compile_flags target)
add_compile_flags(osslsigncode)
#[[
Local Variables:
c-basic-offset: 4
tab-width: 4
indent-tabs-mode: nil
End:
vim: set ts=4 expandtab:
]]
osslsigncode-2.8/helpers.c 0000664 0000000 0000000 00000057733 14571175157 0015721 0 ustar 00root root 0000000 0000000 /*
* osslsigncode support library
*
* Copyright (C) 2021-2023 Micha┼В Trojnara
* Author: Ma┼Вgorzata Olsz├│wka
*/
#include "osslsigncode.h"
#include "helpers.h"
/* Prototypes */
static SpcSpOpusInfo *spc_sp_opus_info_create(FILE_FORMAT_CTX *ctx);
static int spc_indirect_data_content_create(u_char **blob, int *len, FILE_FORMAT_CTX *ctx);
static int pkcs7_signer_info_add_spc_sp_opus_info(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx);
static int pkcs7_signer_info_add_signing_time(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx);
static int pkcs7_signer_info_add_purpose(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx);
static int pkcs7_signer_info_add_sequence_number(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx);
static STACK_OF(X509) *X509_chain_get_sorted(FILE_FORMAT_CTX *ctx, int signer);
static int X509_compare(const X509 *const *a, const X509 *const *b);
/*
* Common functions
*/
/*
* [in] infile
* [returns] file size
*/
uint32_t get_file_size(const char *infile)
{
int ret;
#ifdef _WIN32
struct _stat64 st;
ret = _stat64(infile, &st);
#else
struct stat st;
ret = stat(infile, &st);
#endif
if (ret) {
printf("Failed to open file: %s\n", infile);
return 0;
}
if (st.st_size < 4) {
printf("Unrecognized file type - file is too short: %s\n", infile);
return 0;
}
if (st.st_size > UINT32_MAX) {
printf("Unsupported file - too large: %s\n", infile);
return 0;
}
return (uint32_t)st.st_size;
}
/*
* [in] infile: starting address for the new mapping
* [returns] pointer to the mapped area
*/
char *map_file(const char *infile, const size_t size)
{
char *indata = NULL;
#ifdef WIN32
HANDLE fhandle, fmap;
(void)size;
fhandle = CreateFile(infile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (fhandle == INVALID_HANDLE_VALUE) {
return NULL;
}
fmap = CreateFileMapping(fhandle, NULL, PAGE_READONLY, 0, 0, NULL);
CloseHandle(fhandle);
if (fmap == NULL) {
return NULL;
}
indata = (char *)MapViewOfFile(fmap, FILE_MAP_READ, 0, 0, 0);
CloseHandle(fmap);
#else
#ifdef HAVE_SYS_MMAN_H
int fd = open(infile, O_RDONLY);
if (fd < 0) {
return NULL;
}
indata = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
if (indata == MAP_FAILED) {
close(fd);
return NULL;
}
close(fd);
#else
printf("No file mapping function\n");
return NULL;
#endif /* HAVE_SYS_MMAN_H */
#endif /* WIN32 */
return indata;
}
/*
* [in] indata: starting address space
* [in] size: mapped area length
* [returns] none
*/
void unmap_file(char *indata, const size_t size)
{
if (!indata)
return;
#ifdef WIN32
(void)size;
UnmapViewOfFile(indata);
#else
munmap(indata, size);
#endif /* WIN32 */
}
/*
* Retrieve a decoded PKCS#7 structure
* [in] data: encoded PEM or DER data
* [in] size: data size
* [returns] pointer to PKCS#7 structure
*/
PKCS7 *pkcs7_read_data(char *data, uint32_t size)
{
PKCS7 *p7 = NULL;
BIO *bio;
const char pemhdr[] = "-----BEGIN PKCS7-----";
bio = BIO_new_mem_buf(data, (int)size);
if (size >= sizeof pemhdr && !memcmp(data, pemhdr, sizeof pemhdr - 1)) {
/* PEM format */
p7 = PEM_read_bio_PKCS7(bio, NULL, NULL, NULL);
} else { /* DER format */
p7 = d2i_PKCS7_bio(bio, NULL);
}
BIO_free_all(bio);
return p7;
}
/*
* [in, out] ctx: structure holds input and output data
* [out] outdata: BIO outdata file
* [in] p7: PKCS#7 signature
* [returns] 1 on error or 0 on success
*/
int data_write_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7)
{
int ret;
(void)BIO_reset(outdata);
if (ctx->options->output_pkcs7) {
/* PEM format */
ret = !PEM_write_bio_PKCS7(outdata, p7);
} else {
/* default DER format */
ret = !i2d_PKCS7_bio(outdata, p7);
}
if (ret) {
printf("Unable to write pkcs7 object\n");
}
return ret;
}
/*
* Allocate, set type, add content and return a new PKCS#7 signature
* [in] ctx: structure holds input and output data
* [returns] pointer to PKCS#7 structure
*/
PKCS7 *pkcs7_create(FILE_FORMAT_CTX *ctx)
{
int i, signer = -1;
PKCS7 *p7;
PKCS7_SIGNER_INFO *si = NULL;
STACK_OF(X509) *chain = NULL;
p7 = PKCS7_new();
PKCS7_set_type(p7, NID_pkcs7_signed);
PKCS7_content_new(p7, NID_pkcs7_data);
if (ctx->options->cert != NULL) {
/*
* the private key and corresponding certificate are parsed from the PKCS12
* structure or loaded from the security token, so we may omit to check
* the consistency of a private key with the public key in an X509 certificate
*/
si = PKCS7_add_signature(p7, ctx->options->cert, ctx->options->pkey,
ctx->options->md);
if (si == NULL)
return NULL; /* FAILED */
} else {
/* find the signer's certificate located somewhere in the whole certificate chain */
for (i=0; ioptions->certs); i++) {
X509 *signcert = sk_X509_value(ctx->options->certs, i);
if (X509_check_private_key(signcert, ctx->options->pkey)) {
si = PKCS7_add_signature(p7, signcert, ctx->options->pkey, ctx->options->md);
signer = i;
break;
}
}
if (si == NULL) {
printf("Failed to checking the consistency of a private key: %s\n",
ctx->options->keyfile);
printf(" with a public key in any X509 certificate: %s\n\n",
ctx->options->certfile);
return NULL; /* FAILED */
}
}
if (!pkcs7_signer_info_add_signing_time(si, ctx)) {
return NULL; /* FAILED */
}
if (!pkcs7_signer_info_add_purpose(si, ctx)) {
return NULL; /* FAILED */
}
if ((ctx->options->desc || ctx->options->url) &&
!pkcs7_signer_info_add_spc_sp_opus_info(si, ctx)) {
printf("Couldn't allocate memory for opus info\n");
return NULL; /* FAILED */
}
if ((ctx->options->nested_number >= 0) &&
!pkcs7_signer_info_add_sequence_number(si, ctx)) {
return NULL; /* FAILED */
}
/* create X509 chain sorted in ascending order by their DER encoding */
chain = X509_chain_get_sorted(ctx, signer);
if (chain == NULL) {
printf("Failed to create a sorted certificate chain\n");
return NULL; /* FAILED */
}
/* add sorted certificate chain */
for (i=0; ioptions->crls) {
for (i=0; ioptions->crls); i++)
PKCS7_add_crl(p7, sk_X509_CRL_value(ctx->options->crls, i));
}
sk_X509_free(chain);
return p7; /* OK */
}
/*
* PE, MSI, CAB and APPX file specific
* Add "1.3.6.1.4.1.311.2.1.4" SPC_INDIRECT_DATA_OBJID signed attribute
* [in, out] p7: new PKCS#7 signature
* [returns] 0 on error or 1 on success
*/
int add_indirect_data_object(PKCS7 *p7)
{
STACK_OF(PKCS7_SIGNER_INFO) *signer_info;
PKCS7_SIGNER_INFO *si;
signer_info = PKCS7_get_signer_info(p7);
if (!signer_info)
return 0; /* FAILED */
si = sk_PKCS7_SIGNER_INFO_value(signer_info, 0);
if (!si)
return 0; /* FAILED */
if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType,
V_ASN1_OBJECT, OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, 1)))
return 0; /* FAILED */
return 1; /* OK */
}
/*
* PE, MSI, CAB and APPX format specific
* Sign the MS Authenticode spcIndirectDataContent blob.
* The spcIndirectDataContent structure is used in Authenticode signatures
* to store the digest and other attributes of the signed file.
* [in, out] p7: new PKCS#7 signature
* [in] content: spcIndirectDataContent
* [returns] 0 on error or 1 on success
*/
int sign_spc_indirect_data_content(PKCS7 *p7, ASN1_OCTET_STRING *content)
{
int len, inf, tag, class;
long plen;
const u_char *data, *p;
PKCS7 *td7;
p = data = ASN1_STRING_get0_data(content);
len = ASN1_STRING_length(content);
inf = ASN1_get_object(&p, &plen, &tag, &class, len);
if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE
|| !pkcs7_sign_content(p7, p, (int)plen)) {
printf("Failed to sign spcIndirectDataContent\n");
return 0; /* FAILED */
}
td7 = PKCS7_new();
if (!td7) {
return 0; /* FAILED */
}
td7->type = OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, 1);
td7->d.other = ASN1_TYPE_new();
td7->d.other->type = V_ASN1_SEQUENCE;
td7->d.other->value.sequence = ASN1_STRING_new();
ASN1_STRING_set(td7->d.other->value.sequence, data, len);
if (!PKCS7_set_content(p7, td7)) {
printf("PKCS7_set_content failed\n");
PKCS7_free(td7);
return 0; /* FAILED */
}
return 1; /* OK */
}
/*
* Add encapsulated content to signed PKCS7 structure.
* [in] content: spcIndirectDataContent
* [returns] new PKCS#7 signature with encapsulated content
*/
PKCS7 *pkcs7_set_content(ASN1_OCTET_STRING *content)
{
PKCS7 *p7, *td7;
p7 = PKCS7_new();
if (!p7) {
return NULL; /* FAILED */
}
if (!PKCS7_set_type(p7, NID_pkcs7_signed)) {
PKCS7_free(p7);
return NULL; /* FAILED */
}
if (!PKCS7_content_new(p7, NID_pkcs7_data)) {
PKCS7_free(p7);
return NULL; /* FAILED */
}
td7 = PKCS7_new();
if (!td7) {
PKCS7_free(p7);
return NULL; /* FAILED */
}
td7->type = OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, 1);
td7->d.other = ASN1_TYPE_new();
td7->d.other->type = V_ASN1_SEQUENCE;
td7->d.other->value.sequence = content;
if (!PKCS7_set_content(p7, td7)) {
PKCS7_free(td7);
PKCS7_free(p7);
return NULL; /* FAILED */
}
return p7;
}
/*
* Return spcIndirectDataContent.
* [in] hash: message digest BIO
* [in] ctx: structure holds input and output data
* [returns] content
*/
ASN1_OCTET_STRING *spc_indirect_data_content_get(BIO *hash, FILE_FORMAT_CTX *ctx)
{
ASN1_OCTET_STRING *content;
u_char mdbuf[5 * EVP_MAX_MD_SIZE + 24];
int mdlen, hashlen, len = 0;
u_char *data, *p = NULL;
content = ASN1_OCTET_STRING_new();
if (!content) {
return NULL; /* FAILED */
}
if (!spc_indirect_data_content_create(&p, &len, ctx)) {
ASN1_OCTET_STRING_free(content);
return NULL; /* FAILED */
}
hashlen = ctx->format->hash_length_get(ctx);
if (hashlen > EVP_MAX_MD_SIZE) {
/* APPX format specific */
mdlen = BIO_read(hash, (char*)mdbuf, hashlen);
} else {
mdlen = BIO_gets(hash, (char*)mdbuf, EVP_MAX_MD_SIZE);
}
data = OPENSSL_malloc((size_t)(len + mdlen));
memcpy(data, p, (size_t)len);
OPENSSL_free(p);
memcpy(data + len, mdbuf, (size_t)mdlen);
if (!ASN1_OCTET_STRING_set(content, data, len + mdlen)) {
ASN1_OCTET_STRING_free(content);
OPENSSL_free(data);
return NULL; /* FAILED */
}
OPENSSL_free(data);
return content;
}
/*
* Signs the data and place the signature in p7
* [in, out] p7: new PKCS#7 signature
* [in] data: content data
* [in] len: content length
*/
int pkcs7_sign_content(PKCS7 *p7, const u_char *data, int len)
{
BIO *p7bio;
if ((p7bio = PKCS7_dataInit(p7, NULL)) == NULL) {
printf("PKCS7_dataInit failed\n");
return 0; /* FAILED */
}
BIO_write(p7bio, data, len);
(void)BIO_flush(p7bio);
if (!PKCS7_dataFinal(p7, p7bio)) {
printf("PKCS7_dataFinal failed\n");
BIO_free_all(p7bio);
return 0; /* FAILED */
}
BIO_free_all(p7bio);
return 1; /* OK */
}
/* Return the header length (tag and length octets) of the ASN.1 type
* [in] p: ASN.1 data
* [in] len: ASN.1 data length
* [returns] header length
*/
int asn1_simple_hdr_len(const u_char *p, int len)
{
if (len <= 2 || p[0] > 0x31)
return 0;
return (p[1]&0x80) ? (2 + (p[1]&0x7f)) : 2;
}
/*
* [in, out] hash: BIO with message digest method
* [in] indata: starting address space
* [in] idx: offset
* [in] fileend: the length of the hashed area
* [returns] 0 on error or 1 on success
*/
int bio_hash_data(BIO *hash, char *indata, size_t idx, size_t fileend)
{
while (idx < fileend) {
size_t want, written;
want = fileend - idx;
if (want > SIZE_64K)
want = SIZE_64K;
if (!BIO_write_ex(hash, indata + idx, want, &written))
return 0; /* FAILED */
idx += written;
}
return 1; /* OK */
}
/*
* [in] descript1, descript2: descriptions
* [in] mdbuf: message digest
* [in] len: message digest length
* [returns] none
*/
void print_hash(const char *descript1, const char *descript2, const u_char *mdbuf, int len)
{
char *hexbuf = NULL;
int size, i, j = 0;
size = 2 * len + 1;
hexbuf = OPENSSL_malloc((size_t)size);
for (i = 0; i < len; i++) {
#ifdef WIN32
j += sprintf_s(hexbuf + j, size - j, "%02X", mdbuf[i]);
#else
j += sprintf(hexbuf + j, "%02X", mdbuf[i]);
#endif /* WIN32 */
}
printf("%s: %s %s\n", descript1, hexbuf, descript2);
OPENSSL_free(hexbuf);
}
/*
* [in] p7: new PKCS#7 signature
* [in] objid: Microsoft OID Authenticode
* [returns] 0 on error or 1 on success
*/
int is_content_type(PKCS7 *p7, const char *objid)
{
ASN1_OBJECT *indir_objid;
int ret;
indir_objid = OBJ_txt2obj(objid, 1);
ret = p7 && PKCS7_type_is_signed(p7) &&
!OBJ_cmp(p7->d.sign->contents->type, indir_objid) &&
(p7->d.sign->contents->d.other->type == V_ASN1_SEQUENCE ||
p7->d.sign->contents->d.other->type == V_ASN1_OCTET_STRING);
ASN1_OBJECT_free(indir_objid);
return ret;
}
/*
* [in] p7: new PKCS#7 signature
* [returns] pointer to MsCtlContent structure
*/
MsCtlContent *ms_ctl_content_get(PKCS7 *p7)
{
ASN1_STRING *value;
const u_char *data;
if (!is_content_type(p7, MS_CTL_OBJID)) {
printf("Failed to find MS_CTL_OBJID\n");
return NULL; /* FAILED */
}
value = p7->d.sign->contents->d.other->value.sequence;
data = ASN1_STRING_get0_data(value);
return d2i_MsCtlContent(NULL, &data, ASN1_STRING_length(value));
}
/*
* [in] attribute: catalog attribute
* [returns] catalog content
*/
ASN1_TYPE *catalog_content_get(CatalogAuthAttr *attribute)
{
ASN1_STRING *value;
STACK_OF(ASN1_TYPE) *contents;
ASN1_TYPE *content;
const u_char *contents_data;
value = attribute->contents->value.sequence;
contents_data = ASN1_STRING_get0_data(value);
contents = d2i_ASN1_SET_ANY(NULL, &contents_data, ASN1_STRING_length(value));
if (!contents)
return 0; /* FAILED */
content = sk_ASN1_TYPE_value(contents, 0);
sk_ASN1_TYPE_free(contents);
return content;
}
/*
* PE and CAB format specific
* [in] none
* [returns] pointer to SpcLink
*/
SpcLink *spc_link_obsolete_get(void)
{
const u_char obsolete[] = {
0x00, 0x3c, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x4f,
0x00, 0x62, 0x00, 0x73, 0x00, 0x6f, 0x00, 0x6c,
0x00, 0x65, 0x00, 0x74, 0x00, 0x65, 0x00, 0x3e,
0x00, 0x3e, 0x00, 0x3e
};
SpcLink *link = SpcLink_new();
link->type = 2;
link->value.file = SpcString_new();
link->value.file->type = 0;
link->value.file->value.unicode = ASN1_BMPSTRING_new();
ASN1_STRING_set(link->value.file->value.unicode, obsolete, sizeof obsolete);
return link;
}
/*
* [in] mdbuf, cmdbuf: message digests
* [in] mdtype: message digest algorithm type
* [returns] 0 on error or 1 on success
*/
int compare_digests(u_char *mdbuf, u_char *cmdbuf, int mdtype)
{
int mdlen = EVP_MD_size(EVP_get_digestbynid(mdtype));
int mdok = !memcmp(mdbuf, cmdbuf, (size_t)mdlen);
printf("Message digest algorithm : %s\n", OBJ_nid2sn(mdtype));
print_hash("Current message digest ", "", mdbuf, mdlen);
print_hash("Calculated message digest ", mdok ? "\n" : " MISMATCH!!!\n", cmdbuf, mdlen);
return mdok;
}
/*
* Helper functions
*/
/*
* [in] ctx: FILE_FORMAT_CTX structure
* [returns] pointer to SpcSpOpusInfo structure
*/
static SpcSpOpusInfo *spc_sp_opus_info_create(FILE_FORMAT_CTX *ctx)
{
SpcSpOpusInfo *info = SpcSpOpusInfo_new();
if (ctx->options->desc) {
info->programName = SpcString_new();
info->programName->type = 1;
info->programName->value.ascii = ASN1_IA5STRING_new();
ASN1_STRING_set((ASN1_STRING *)info->programName->value.ascii,
ctx->options->desc, (int)strlen(ctx->options->desc));
}
if (ctx->options->url) {
info->moreInfo = SpcLink_new();
info->moreInfo->type = 0;
info->moreInfo->value.url = ASN1_IA5STRING_new();
ASN1_STRING_set((ASN1_STRING *)info->moreInfo->value.url,
ctx->options->url, (int)strlen(ctx->options->url));
}
return info;
}
/*
* [out] blob: SpcIndirectDataContent data
* [out] len: SpcIndirectDataContent data length
* [in] ctx: FILE_FORMAT_CTX structure
* [returns] 0 on error or 1 on success
*/
static int spc_indirect_data_content_create(u_char **blob, int *len, FILE_FORMAT_CTX *ctx)
{
u_char *p = NULL;
int mdtype, hashlen, l = 0;
void *hash;
SpcIndirectDataContent *idc = SpcIndirectDataContent_new();
if (!ctx->format->data_blob_get || !ctx->format->hash_length_get) {
return 0; /* FAILED */
}
if (ctx->format->md_get) {
/* APPX file specific - use a hash algorithm specified in the AppxBlockMap.xml file */
mdtype = EVP_MD_nid(ctx->format->md_get(ctx));
} else {
mdtype = EVP_MD_nid(ctx->options->md);
}
idc->data->value = ASN1_TYPE_new();
idc->data->value->type = V_ASN1_SEQUENCE;
idc->data->value->value.sequence = ASN1_STRING_new();
idc->data->type = ctx->format->data_blob_get(&p, &l, ctx);
idc->data->value->value.sequence->data = p;
idc->data->value->value.sequence->length = l;
idc->messageDigest->digestAlgorithm->algorithm = OBJ_nid2obj(mdtype);
idc->messageDigest->digestAlgorithm->parameters = ASN1_TYPE_new();
idc->messageDigest->digestAlgorithm->parameters->type = V_ASN1_NULL;
hashlen = ctx->format->hash_length_get(ctx);
hash = OPENSSL_zalloc((size_t)hashlen);
ASN1_OCTET_STRING_set(idc->messageDigest->digest, hash, hashlen);
OPENSSL_free(hash);
*len = i2d_SpcIndirectDataContent(idc, NULL);
*blob = OPENSSL_malloc((size_t)*len);
p = *blob;
i2d_SpcIndirectDataContent(idc, &p);
SpcIndirectDataContent_free(idc);
*len -= hashlen;
return 1; /* OK */
}
/*
* [in, out] si: PKCS7_SIGNER_INFO structure
* [in] ctx: FILE_FORMAT_CTX structure
* [returns] 0 on error or 1 on success
*/
static int pkcs7_signer_info_add_spc_sp_opus_info(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx)
{
SpcSpOpusInfo *opus;
ASN1_STRING *astr;
int len;
u_char *p = NULL;
opus = spc_sp_opus_info_create(ctx);
if ((len = i2d_SpcSpOpusInfo(opus, NULL)) <= 0
|| (p = OPENSSL_malloc((size_t)len)) == NULL) {
SpcSpOpusInfo_free(opus);
return 0; /* FAILED */
}
i2d_SpcSpOpusInfo(opus, &p);
p -= len;
astr = ASN1_STRING_new();
ASN1_STRING_set(astr, p, len);
OPENSSL_free(p);
SpcSpOpusInfo_free(opus);
return PKCS7_add_signed_attribute(si, OBJ_txt2nid(SPC_SP_OPUS_INFO_OBJID),
V_ASN1_SEQUENCE, astr);
}
/*
* Add a custom, non-trusted time to the PKCS7 structure to prevent OpenSSL
* adding the _current_ time. This allows to create a deterministic signature
* when no trusted timestamp server was specified, making osslsigncode
* behaviour closer to signtool.exe (which doesn't include any non-trusted
* time in this case.)
* [in, out] si: PKCS7_SIGNER_INFO structure
* [in] ctx: structure holds input and output data
* [returns] 0 on error or 1 on success
*/
static int pkcs7_signer_info_add_signing_time(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx)
{
if (ctx->options->time == INVALID_TIME) /* -time option was not specified */
return 1; /* SUCCESS */
return PKCS7_add_signed_attribute(si, NID_pkcs9_signingTime, V_ASN1_UTCTIME,
ASN1_TIME_adj(NULL, ctx->options->time, 0, 0));
}
/*
* [in, out] si: PKCS7_SIGNER_INFO structure
* [in] ctx: structure holds input and output data
* [returns] 0 on error or 1 on success
*/
static int pkcs7_signer_info_add_purpose(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx)
{
static const u_char purpose_ind[] = {
0x30, 0x0c, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04,
0x01, 0x82, 0x37, 0x02, 0x01, 0x15
};
static const u_char purpose_comm[] = {
0x30, 0x0c, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04,
0x01, 0x82, 0x37, 0x02, 0x01, 0x16
};
ASN1_STRING *purpose = ASN1_STRING_new();
if (ctx->options->comm) {
ASN1_STRING_set(purpose, purpose_comm, sizeof purpose_comm);
} else {
ASN1_STRING_set(purpose, purpose_ind, sizeof purpose_ind);
}
return PKCS7_add_signed_attribute(si, OBJ_txt2nid(SPC_STATEMENT_TYPE_OBJID),
V_ASN1_SEQUENCE, purpose);
}
/*
* [in, out] si: PKCS7_SIGNER_INFO structure
* [in] ctx: structure holds input and output data
* [returns] 0 on error or 1 on success
*/
static int pkcs7_signer_info_add_sequence_number(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx)
{
ASN1_INTEGER *number = ASN1_INTEGER_new();
if (!number)
return 0; /* FAILED */
if (!ASN1_INTEGER_set(number, ctx->options->nested_number + 1)) {
ASN1_INTEGER_free(number);
return 0; /* FAILED */
}
return PKCS7_add_signed_attribute(si, OBJ_txt2nid(PKCS9_SEQUENCE_NUMBER),
V_ASN1_INTEGER, number);
}
/*
* Create certificate chain sorted in ascending order by their DER encoding.
* [in] ctx: structure holds input and output data
* [in] signer: signer's certificate number in the certificate chain
* [returns] sorted certificate chain
*/
static STACK_OF(X509) *X509_chain_get_sorted(FILE_FORMAT_CTX *ctx, int signer)
{
int i;
STACK_OF(X509) *chain = sk_X509_new(X509_compare);
/* add the signer's certificate */
if (ctx->options->cert != NULL && !sk_X509_push(chain, ctx->options->cert)) {
sk_X509_free(chain);
return NULL;
}
if (signer != -1 && !sk_X509_push(chain, sk_X509_value(ctx->options->certs, signer))) {
sk_X509_free(chain);
return NULL;
}
/* add the certificate chain */
for (i=0; ioptions->certs); i++) {
if (i == signer)
continue;
if (!sk_X509_push(chain, sk_X509_value(ctx->options->certs, i))) {
sk_X509_free(chain);
return NULL;
}
}
/* add all cross certificates */
if (ctx->options->xcerts) {
for (i=0; ioptions->xcerts); i++) {
if (!sk_X509_push(chain, sk_X509_value(ctx->options->xcerts, i))) {
sk_X509_free(chain);
return NULL;
}
}
}
/* sort certificate chain using the supplied comparison function */
sk_X509_sort(chain);
return chain;
}
/*
* X.690-compliant certificate comparison function
* Windows requires catalog files to use PKCS#7
* content ordering specified in X.690 section 11.6
* https://support.microsoft.com/en-us/topic/october-13-2020-kb4580358-security-only-update-d3f6eb3c-d7c4-a9cb-0de6-759386bf7113
* This algorithm is different from X509_cmp()
* [in] a_ptr, b_ptr: pointers to X509 certificates
* [returns] certificates order
*/
static int X509_compare(const X509 *const *a, const X509 *const *b)
{
u_char *a_data, *b_data, *a_tmp, *b_tmp;
size_t a_len, b_len;
int ret;
a_len = (size_t)i2d_X509(*a, NULL);
a_tmp = a_data = OPENSSL_malloc(a_len);
i2d_X509(*a, &a_tmp);
b_len = (size_t)i2d_X509(*b, NULL);
b_tmp = b_data = OPENSSL_malloc(b_len);
i2d_X509(*b, &b_tmp);
ret = memcmp(a_data, b_data, MIN(a_len, b_len));
OPENSSL_free(a_data);
OPENSSL_free(b_data);
if (ret == 0 && a_len != b_len) /* identical up to the length of the shorter DER */
ret = a_len < b_len ? -1 : 1; /* shorter is smaller */
return ret;
}
/*
Local Variables:
c-basic-offset: 4
tab-width: 4
indent-tabs-mode: nil
End:
vim: set ts=4 expandtab:
*/
osslsigncode-2.8/helpers.h 0000664 0000000 0000000 00000002634 14571175157 0015714 0 ustar 00root root 0000000 0000000 /*
* osslsigncode support library
*
* Copyright (C) 2021-2023 Micha┼В Trojnara
* Author: Ma┼Вgorzata Olsz├│wka
*/
/* Common functions */
uint32_t get_file_size(const char *infile);
char *map_file(const char *infile, const size_t size);
void unmap_file(char *indata, const size_t size);
PKCS7 *pkcs7_read_data(char *indata, uint32_t size);
int data_write_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7);
PKCS7 *pkcs7_create(FILE_FORMAT_CTX *ctx);
int add_indirect_data_object(PKCS7 *p7);
int sign_spc_indirect_data_content(PKCS7 *p7, ASN1_OCTET_STRING *content);
PKCS7 *pkcs7_set_content(ASN1_OCTET_STRING *content);
ASN1_OCTET_STRING *spc_indirect_data_content_get(BIO *hash, FILE_FORMAT_CTX *ctx);
int pkcs7_sign_content(PKCS7 *p7, const u_char *data, int len);
int asn1_simple_hdr_len(const u_char *p, int len);
int bio_hash_data(BIO *hash, char *indata, size_t idx, size_t fileend);
void print_hash(const char *descript1, const char *descript2, const u_char *hashbuf, int length);
int is_content_type(PKCS7 *p7, const char *objid);
MsCtlContent *ms_ctl_content_get(PKCS7 *p7);
ASN1_TYPE *catalog_content_get(CatalogAuthAttr *attribute);
SpcLink *spc_link_obsolete_get(void);
int compare_digests(u_char *mdbuf, u_char *cmdbuf, int mdtype);
/*
Local Variables:
c-basic-offset: 4
tab-width: 4
indent-tabs-mode: nil
End:
vim: set ts=4 expandtab:
*/
osslsigncode-2.8/misc/ 0000775 0000000 0000000 00000000000 14571175157 0015027 5 ustar 00root root 0000000 0000000 osslsigncode-2.8/misc/pagehash.py 0000664 0000000 0000000 00000006154 14571175157 0017167 0 ustar 00root root 0000000 0000000 #!/usr/bin/python
import struct
import sys
import hashlib
from pyasn1.type import univ
from pyasn1.codec.ber import encoder, decoder
f = open(sys.argv[1], 'rb')
filehdr = f.read(1024)
if filehdr[0:2] != 'MZ':
print "Not a DOS file."
sys.exit(0)
pepos = struct.unpack('